diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index eb90f57..0000000 --- a/Dockerfile +++ /dev/null @@ -1,21 +0,0 @@ -FROM node:12.6.0 - -LABEL "com.github.actions.name"="todo-actions" -LABEL "com.github.actions.description"="Convert TODO comments into issues" -LABEL "com.github.actions.icon"="alert-circle" -LABEL "com.github.actions.color"="gray-dark" - -LABEL "repository"="http://github.com/dtinth/todo-actions" -LABEL "homepage"="http://github.com/dtinth/todo-actions" -LABEL "maintainer"="dtinth " - -ENV GIT_COMMITTER_NAME=TODO -ENV GIT_AUTHOR_NAME=TODO -ENV EMAIL=todo-actions[bot]@users.noreply.github.com - -RUN mkdir -p /app -ADD entrypoint.sh package.json tsconfig.json yarn.lock /app/ -RUN cd /app && yarn --frozen-lockfile -ADD src /app/src -RUN cd /app && yarn build -ENTRYPOINT ["/app/entrypoint.sh"] diff --git a/__mocks__/@actions/core.js b/__mocks__/@actions/core.js new file mode 100644 index 0000000..386c551 --- /dev/null +++ b/__mocks__/@actions/core.js @@ -0,0 +1,12 @@ +const fs = require('fs') +const yaml = require('js-yaml') + +const content = fs.readFileSync(`${__dirname}/../../action.yml`, 'utf-8') +const config = yaml.safeLoad(content) + +module.exports = { + getInput (name) { + return (config.inputs[name] || {}).default || '' + } +} + diff --git a/src/TodoActionsMain.test.ts b/__tests__/TodoActionsMain.test.ts similarity index 87% rename from src/TodoActionsMain.test.ts rename to __tests__/TodoActionsMain.test.ts index 7231778..7466b8d 100644 --- a/src/TodoActionsMain.test.ts +++ b/__tests__/TodoActionsMain.test.ts @@ -1,10 +1,11 @@ -import { runMain } from './TodoActionsMain' -import { resetMockWorld } from './__mocks__/World' +import { runMain } from '../src/TodoActionsMain' +import { resetMockWorld } from '../src/__mocks__/World' import sortBy from 'lodash.sortby' -jest.mock('./DataStore') -jest.mock('./CodeRepository') -jest.mock('./TaskManagementSystem') +jest.mock('@actions/core') +jest.mock('../src/DataStore') +jest.mock('../src/CodeRepository') +jest.mock('../src/TaskManagementSystem') const MARKER = 'TODO' @@ -37,11 +38,11 @@ it('works', async () => { expect(world.commits[1].files.get('main.js')).toMatch( new RegExp(`${MARKER} \\[#\\d+\\]: Hello world`), ) + expect(world.commits[1].message).toMatch(/#1/) expect(world.commits[1].message).toMatch(/#2/) // Round 1: Assert tasks - expect(world.tasks.length).toEqual(2) expect(sortBy(world.tasks.map(t => t.title))).toEqual([ 'Hello world', 'Somebody once told me', diff --git a/src/TodoParser.test.ts b/__tests__/TodoParser.test.ts similarity index 96% rename from src/TodoParser.test.ts rename to __tests__/TodoParser.test.ts index 6e65d81..8980eba 100644 --- a/src/TodoParser.test.ts +++ b/__tests__/TodoParser.test.ts @@ -1,5 +1,5 @@ -import { parseTodos } from './TodoParser' -import { MockFile } from './File' +import { parseTodos } from '../src/TodoParser' +import { MockFile } from '../src/File' const MARKER = 'TODO' diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..e610c8f --- /dev/null +++ b/action.yml @@ -0,0 +1,25 @@ +name: 'Todo Actions' +description: 'Convert TODO comments into issues' + +inputs: + collect_commit_msg: + description: 'Commit message of collecting issues' + default: 'Collect TODO comments' + collect_commit_body: + description: 'Commit body of collecting issues' + default: '' + + reference_commit_msg: + description: 'Commit message of referencing issues' + default: 'Update TODO references: %s' + reference_commit_body: + description: 'Commit body of referencing issues' + default: '' + + branch: + description: 'Working branch' + default: 'master' + +runs: + using: 'node12' + main: 'dist/index.js' diff --git a/dist/code-points.mem b/dist/code-points.mem new file mode 100644 index 0000000..4781b06 Binary files /dev/null and b/dist/code-points.mem differ diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..1a0ca5d --- /dev/null +++ b/dist/index.js @@ -0,0 +1,75177 @@ +require('./sourcemap-register.js');module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 1689: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tkt_1 = __webpack_require__(9508); +const TodoActionsMain_1 = __webpack_require__(2357); +const MongoDB = __importStar(__webpack_require__(4983)); +tkt_1.cli() + .command('$0', 'Collect TODOs and create issues', {}, (args) => __awaiter(void 0, void 0, void 0, function* () { + yield TodoActionsMain_1.runMain(); + yield MongoDB.close(); +})) + .parse(); + + +/***/ }), + +/***/ 2121: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.scanCodeRepository = exports.repoContext = void 0; +const core_1 = __webpack_require__(6432); +const github_1 = __webpack_require__(5438); +const fs_1 = __webpack_require__(5747); +const tkt_1 = __webpack_require__(9508); +const child_process_1 = __webpack_require__(3129); +const File_1 = __webpack_require__(3304); +const log = tkt_1.logger('CodeRepository'); +const event = process.env.GITHUB_EVENT_PATH && fs_1.existsSync(process.env.GITHUB_EVENT_PATH) + ? (log.debug('Found GitHub Action event file'), + JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8'))) + : (log.debug('No GitHub Action event file found'), null); +exports.repoContext = { + repositoryNodeId: process.env.GITHUB_REPO_NODE_ID || + (event && event.repository && event.repository.node_id) || + tkt_1.invariant(false, 'GitHub Repo Node ID not found, either in GitHub Action event payload and GITHUB_REPO_NODE_ID environment variable.'), + repositoryOwner: process.env.GITHUB_REPO_OWNER || + (event && event.repository && event.repository.full_name.split('/')[0]) || + tkt_1.invariant(false, 'GitHub Repo Owner not found, either in GitHub Action event payload and GITHUB_REPO_OWNER environment variable.'), + repositoryName: process.env.GITHUB_REPO_NAME || + (event && event.repository && event.repository.full_name.split('/')[1]) || + tkt_1.invariant(false, 'GitHub Repo Name not found, either in GitHub Action event payload and GITHUB_REPO_NAME environment variable.'), + defaultBranch: process.env.GITHUB_REPO_DEFAULT_BRANCH || + (event && event.repository && event.repository.default_branch) || + tkt_1.invariant(false, 'GitHub Repo Default Branch not found, either in GitHub Action event payload and GITHUB_REPO_DEFAULT_BRANCH environment variable.'), +}; +function scanCodeRepository() { + return __awaiter(this, void 0, void 0, function* () { + log.info('Search for files with TODO tags...'); + const filesWithTodoMarker = child_process_1.execSync('git grep -Il TODO', { + encoding: 'utf8', + }) + .split('\n') + .filter(name => name); + const files = []; + log.info('Parsing TODO tags...'); + for (const filePath of filesWithTodoMarker) { + const file = new File_1.File(filePath); + files.push(file); + } + return { + files, + saveChanges(commitMessage, commitBody) { + return __awaiter(this, void 0, void 0, function* () { + const changedFiles = files.filter(file => file.contents.changed); + log.info('Files changed: %s', changedFiles.length); + if (changedFiles.length === 0) { + return; + } + for (const file of changedFiles) { + file.save(); + } + log.info(`"${commitMessage}"`, `"${commitBody}"`); + process.env.GIT_COMMITTER_NAME = 'todo-actions'; + process.env.GIT_AUTHOR_NAME = 'todo-actions'; + process.env.GIT_AUTHOR_EMAIL = 'todo-actions[bot]@users.noreply.github.com'; + child_process_1.execFileSync('git', ['add', ...changedFiles.map(file => file.fileName)]); + child_process_1.execFileSync('git', ['commit', '-m', commitMessage, '-m', commitBody], { + stdio: 'inherit' + }); + if (!process.env.GITHUB_TOKEN) { + throw `Maybe you forgot to enable the GITHUB_TOKEN secret?`; + } + const ref = core_1.getInput('branch') || "$GITHUB_REF"; + child_process_1.execSync(`git push "https://x-access-token:${process.env.GITHUB_TOKEN}@github.com/${github_1.context.repo.owner}/${github_1.context.repo.repo}.git" HEAD:${ref}`, { + stdio: 'inherit' + }); + }); + }, + }; + }); +} +exports.scanCodeRepository = scanCodeRepository; + + +/***/ }), + +/***/ 407: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.findAllUncompletedTasks = exports.beginTaskResolution = void 0; +const tkt_1 = __webpack_require__(9508); +const mongodb_1 = __webpack_require__(5517); +const MongoDB_1 = __webpack_require__(4983); +const ProcessId_1 = __webpack_require__(7644); +const log = tkt_1.logger('DataStore'); +function beginTaskResolution(todoUniqueKey, repositoryId, todo) { + return __awaiter(this, void 0, void 0, function* () { + const db = yield MongoDB_1.getMongoDb(); + const _id = mongodb_1.ObjectId.createFromHexString(todoUniqueKey); + // Ensure a task exists in the database. + const task = yield db.tasks.findOneAndUpdate({ _id: _id }, { + $setOnInsert: { + _id: _id, + repositoryId: repositoryId, + taskReference: null, + createdAt: new Date(), + ownerProcessId: null, + ownerProcessTimestamp: null, + }, + }, { upsert: true, returnOriginal: false }); + if (!task.value) { + throw new Error('Failed to upsert a task.'); + } + if (task.value.taskReference) { + log.debug('Found already-existing identifier %s for TODO %s.', task.value.taskReference, todoUniqueKey); + return { existingTaskReference: task.value.taskReference }; + } + return { + acquireTaskCreationLock() { + return __awaiter(this, void 0, void 0, function* () { + // Acquire a lock... + log.debug('Acquiring lock for TODO %s (currentProcessId=%s).', todoUniqueKey, ProcessId_1.currentProcessId); + const lockedTask = yield db.tasks.findOneAndUpdate({ + _id: _id, + $or: [ + { ownerProcessTimestamp: null }, + { ownerProcessTimestamp: { $lt: new Date(Date.now() - 60e3) } }, + ], + }, { + $set: { + ownerProcessId: ProcessId_1.currentProcessId, + ownerProcessTimestamp: new Date(), + }, + }, { returnOriginal: false }); + if (!lockedTask.value) { + throw new Error('Failed to acquire a lock for this task.'); + } + return { + finish(taskReference, state) { + return __awaiter(this, void 0, void 0, function* () { + // Associate + log.debug('Created task %s for TODO %s. Saving changes.', taskReference, todoUniqueKey); + yield db.tasks.findOneAndUpdate({ _id: _id }, { $set: { taskReference: taskReference, hash: state.hash } }); + }); + }, + }; + }); + }, + }; + }); +} +exports.beginTaskResolution = beginTaskResolution; +function findAllUncompletedTasks(repositoryId) { + return __awaiter(this, void 0, void 0, function* () { + const db = yield MongoDB_1.getMongoDb(); + const result = yield db.tasks + .find({ + repositoryId: repositoryId, + completed: { $ne: true }, + taskReference: { $ne: null }, + }) + .toArray(); + return result.map(taskData => { + return { + taskReference: taskData.taskReference || + tkt_1.invariant(false, 'Unexpected unassociated task.'), + state: { + hash: taskData.hash || '', + }, + markAsCompleted() { + return __awaiter(this, void 0, void 0, function* () { + yield db.tasks.findOneAndUpdate({ _id: taskData._id }, { $set: { completed: true } }); + }); + }, + updateState(newState) { + return __awaiter(this, void 0, void 0, function* () { + yield db.tasks.findOneAndUpdate({ _id: taskData._id }, { $set: { hash: newState.hash } }); + }); + }, + }; + }); + }); +} +exports.findAllUncompletedTasks = findAllUncompletedTasks; + + +/***/ }), + +/***/ 3304: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FileContents = exports.MockFile = exports.File = void 0; +class File { + constructor(fileName) { + this.fileName = fileName; + this.contents = new FileContents(__webpack_require__(5747).readFileSync(fileName, 'utf8')); + } + save() { + if (this.contents.changed) { + __webpack_require__(5747).writeFileSync(this.fileName, this.contents.toString(), 'utf8'); + this.contents.changed = false; + } + } +} +exports.File = File; +/** + * A mock file. + */ +class MockFile { + constructor(fileName, contents) { + this.fileName = fileName; + this.contents = new FileContents(contents); + } + save() { + this.contents.changed = false; + } +} +exports.MockFile = MockFile; +class FileContents { + constructor(contents) { + this.lines = contents.split('\n'); + this.changed = false; + } + changeLine(lineIndex, newLineContents) { + this.lines[lineIndex] = newLineContents; + this.changed = true; + } + toString() { + return this.lines.join('\n'); + } +} +exports.FileContents = FileContents; + + +/***/ }), + +/***/ 4983: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.close = exports.getMongoDb = void 0; +const tkt_1 = __webpack_require__(9508); +let mongoPromise; +const log = tkt_1.logger('mongo'); +function getMongoDb() { + return __awaiter(this, void 0, void 0, function* () { + if (mongoPromise) + return mongoPromise; + return (mongoPromise = (() => __awaiter(this, void 0, void 0, function* () { + const { MongoClient } = yield Promise.resolve().then(() => __importStar(__webpack_require__(5517))); + log.info('Connecting...'); + const client = new MongoClient(process.env.TODO_ACTIONS_MONGO_URL || + tkt_1.invariant(false, 'Missing environment variable: TODO_ACTIONS_MONGO_URL')); + yield client.connect(); + log.info('Connected!'); + const db = client.db(); + const tasks = db.collection('tasks'); + tasks.createIndex({ repositoryId: 1 }); + return { + client, + tasks: tasks, + }; + }))()); + }); +} +exports.getMongoDb = getMongoDb; +function close() { + return __awaiter(this, void 0, void 0, function* () { + if (!mongoPromise) + return; + const mongo = yield mongoPromise; + mongo.client.close(); + }); +} +exports.close = close; + + +/***/ }), + +/***/ 7644: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.currentProcessId = void 0; +const bson_1 = __webpack_require__(4044); +exports.currentProcessId = new bson_1.ObjectId().toHexString(); + + +/***/ }), + +/***/ 5720: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.generateTaskInformationFromTodo = void 0; +const core_1 = __webpack_require__(6432); +const crypto_1 = __webpack_require__(6417); +const CodeRepository_1 = __webpack_require__(2121); +const tkt_1 = __webpack_require__(9508); +const graphql_1 = __webpack_require__(8467); +const owner = CodeRepository_1.repoContext.repositoryOwner; +const repo = CodeRepository_1.repoContext.repositoryName; +const branch = core_1.getInput('branch') || CodeRepository_1.repoContext.defaultBranch; +const log = tkt_1.logger('TaskInformationGenerator'); +let cache = 'meh'; +function fetchCommit() { + return __awaiter(this, void 0, void 0, function* () { + if (cache !== 'meh') { + return cache; + } + // Some random check to filter out tests + if (!('GITHUB_TOKEN' in process.env)) { + log.info(`Skipping local testing env`); + return ''; + } + cache = ''; + log.info('Fetching commit'); + try { + const { repository: { ref: { target: { history: { nodes: [{ oid }] } } } } } = yield graphql_1.graphql(`{ + repository(name: "${repo}", owner: "${owner}") { + ref(qualifiedName: "${branch}") { + target { + ... on Commit { + history(first: 1) { + nodes { + oid + } + } + } + } + } + } + }`, { + headers: { + authorization: `token ${process.env.GITHUB_TOKEN || + tkt_1.invariant(false, 'Required GITHUB_TOKEN variable.')}`, + }, + }); + cache = oid; + } + catch (err) { + console.error(err); + } + return cache; + }); +} +function generateTaskInformationFromTodo(todo) { + return __awaiter(this, void 0, void 0, function* () { + const title = todo.title; + const file = todo.file.fileName; + // TODO [#31]: Also link to end line in addition to just the starting line. + // This requires changing `IFile` interface and `File` class to also keep track of where the TODO comment ends. + const line = todo.startLine; + const commit = yield fetchCommit(); + const url = `https://github.com/${owner}/${repo}/blob/${commit || branch}/${file}#L${line}`; + const link = `[${file}:${line}](${url})`; + const body = [ + todo.body, + '', + '---', + `_` + + `This issue has been automatically created by [todo-actions](https://github.com/apps/todo-actions) based on a TODO comment found in ${link}. ` + + `It will automatically be closed when the TODO comment is removed from ${branch}.` + + `_`, + ].join('\n'); + return { + state: { + hash: crypto_1.createHash('md5') + .update(title) + .update(body) + .digest('hex'), + }, + title, + body, + }; + }); +} +exports.generateTaskInformationFromTodo = generateTaskInformationFromTodo; + + +/***/ }), + +/***/ 2094: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.updateTask = exports.completeTask = exports.createTask = void 0; +const tkt_1 = __webpack_require__(9508); +const rest_1 = __webpack_require__(5375); +const graphql_1 = __webpack_require__(8467); +const CodeRepository = __importStar(__webpack_require__(2121)); +const log = tkt_1.logger('TaskManagementSystem'); +function createTask(information) { + return __awaiter(this, void 0, void 0, function* () { + const { createIssue } = yield graphql_1.graphql(` + mutation CreateIssue($input: CreateIssueInput!) { + createIssue(input: $input) { + issue { + number + } + } + } + `, { + input: { + repositoryId: CodeRepository.repoContext.repositoryNodeId, + title: information.title, + body: information.body, + }, + headers: { + authorization: `token ${process.env.GITHUB_TOKEN || tkt_1.invariant(false, 'Required GITHUB_TOKEN variable.')}`, + }, + }); + log.debug('Create issue result:', createIssue); + return createIssue.issue.number + ? `#${createIssue.issue.number}` + : tkt_1.invariant(false, 'Failed to get issue number out of createIssue API call.'); + }); +} +exports.createTask = createTask; +function completeTask(taskReference) { + return __awaiter(this, void 0, void 0, function* () { + const octokit = new rest_1.Octokit({ + auth: `token ${process.env.GITHUB_TOKEN || + tkt_1.invariant(false, 'Required GITHUB_TOKEN variable.')}`, + }); + const result = yield octokit.issues.update({ + owner: CodeRepository.repoContext.repositoryOwner, + repo: CodeRepository.repoContext.repositoryName, + issue_number: +taskReference.substr(1), + state: 'closed', + }); + log.debug('Issue close result:', result.data); + }); +} +exports.completeTask = completeTask; +function updateTask(taskReference, information) { + return __awaiter(this, void 0, void 0, function* () { + const octokit = new rest_1.Octokit({ + auth: `token ${process.env.GITHUB_TOKEN || + tkt_1.invariant(false, 'Required GITHUB_TOKEN variable.')}`, + }); + const result = yield octokit.issues.update({ + owner: CodeRepository.repoContext.repositoryOwner, + repo: CodeRepository.repoContext.repositoryName, + issue_number: +taskReference.substr(1), + title: information.title, + body: information.body, + }); + log.debug('Issue update result:', result.data); + }); +} +exports.updateTask = updateTask; + + +/***/ }), + +/***/ 4038: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveTask = exports.reconcileTasks = exports.ensureAllTodosAreAssociated = void 0; +const tkt_1 = __webpack_require__(9508); +const CodeRepository = __importStar(__webpack_require__(2121)); +const TaskManagementSystem = __importStar(__webpack_require__(2094)); +const DataStore = __importStar(__webpack_require__(407)); +const TaskInformationGenerator = __importStar(__webpack_require__(5720)); +const log = tkt_1.logger('TaskUpdater'); +function ensureAllTodosAreAssociated(todos) { + return __awaiter(this, void 0, void 0, function* () { + const references = []; + for (const todo of todos) { + const reference = todo.reference || tkt_1.invariant(false, 'Unexpected unidentified TODO marker'); + const unassociated = reference.startsWith('$'); + if (unassociated) { + // TODO [#37]: Isolate error when creating tasks + // Failure to create a task should not prevent the action from progressing forward. + // We can simply skip processing this comment for now. + // Since this script is designed to be idempotent, it can be retried later. + const todoUniqueKey = reference.substr(1); + log.debug('Found unresolved TODO %s, resolving task...', todoUniqueKey); + const taskReference = yield resolveTask(todoUniqueKey, todo); + log.debug('Resolved TODO %s => task %s', todoUniqueKey, taskReference); + todo.reference = taskReference; + references.push(taskReference); + } + } + return references; + }); +} +exports.ensureAllTodosAreAssociated = ensureAllTodosAreAssociated; +function reconcileTasks(todos) { + return __awaiter(this, void 0, void 0, function* () { + const uncompletedTasks = yield DataStore.findAllUncompletedTasks(CodeRepository.repoContext.repositoryNodeId); + log.info('Number of registered uncompleted tasks: %s', uncompletedTasks.length); + for (const todo of todos) { + const reference = todo.reference || tkt_1.invariant(false, 'Unexpected unidentified TODO marker'); + tkt_1.invariant(!reference.startsWith('$'), 'Expected all TODO comments to be associated by now.'); + const task = uncompletedTasks.find(t => t.taskReference === reference); + if (!task) { + log.warn('Cannot find a matching task for TODO comment with reference "%s"', reference); + continue; + } + // TODO [#38]: Isolate error when updating tasks + // Failure to update a task should not prevent the action from progressing forward. + // We can simply skip processing this task for now. + // Since this script is designed to be idempotent, it can be retried later. + const { title, body, state, } = yield TaskInformationGenerator.generateTaskInformationFromTodo(todo); + if (task.state.hash !== state.hash) { + log.info('Hash for "%s" changed: "%s" => "%s" -- must update task.', reference, task.state.hash, state.hash); + yield TaskManagementSystem.updateTask(reference, { title, body }); + yield task.updateState(state); + } + else { + log.info('Hash for "%s" remains unchanged: "%s".', reference, task.state.hash); + } + } + for (const task of uncompletedTasks) { + if (todos.find(todo => todo.reference === task.taskReference)) + continue; + log.info('TODO for task "%s" is gone -- completing task!', task.taskReference); + // TODO [#39]: Isolate error when completing tasks + // Failure to complete a task should not prevent the action from progressing forward. + // We can simply skip processing this task for now. + // Since this script is designed to be idempotent, it can be retried later. + yield TaskManagementSystem.completeTask(task.taskReference); + yield task.markAsCompleted(); + } + }); +} +exports.reconcileTasks = reconcileTasks; +function resolveTask(todoUniqueKey, todo) { + return __awaiter(this, void 0, void 0, function* () { + const resolution = yield DataStore.beginTaskResolution(todoUniqueKey, CodeRepository.repoContext.repositoryNodeId, todo); + if ('existingTaskReference' in resolution) { + return resolution.existingTaskReference; + } + const taskCreationLock = yield resolution.acquireTaskCreationLock(); + log.debug('Lock acquired. Now creating task for TODO %s.', todoUniqueKey); + const { title, body, state, } = yield TaskInformationGenerator.generateTaskInformationFromTodo(todo); + const taskReference = yield TaskManagementSystem.createTask({ title, body }); + taskCreationLock.finish(taskReference, state); + return taskReference; + }); +} +exports.resolveTask = resolveTask; + + +/***/ }), + +/***/ 2357: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.runMain = void 0; +const core_1 = __webpack_require__(6432); +const tkt_1 = __webpack_require__(9508); +const tkt_2 = __webpack_require__(9508); +const bson_1 = __webpack_require__(4044); +const TodoParser = __importStar(__webpack_require__(6228)); +const TaskUpdater = __importStar(__webpack_require__(4038)); +const CodeRepository = __importStar(__webpack_require__(2121)); +const log = tkt_2.logger('main'); +function runMain() { + return __awaiter(this, void 0, void 0, function* () { + log.info('Search for files with TODO tags...'); + const { files, saveChanges } = yield CodeRepository.scanCodeRepository(); + const todoComments = []; + for (const file of files) { + // TODO [#22]: Implement ignoring paths + if (file.fileName === 'README.md') + continue; + const todos = TodoParser.parseTodos(file); + log.info('%s: %s found', file.fileName, todos.length); + todoComments.push(...todos); + } + log.info('Total TODOs found: %s', todoComments.length); + const todosWithoutReference = todoComments.filter(todo => !todo.reference); + log.info('TODOs without references: %s', todosWithoutReference.length); + if (todosWithoutReference.length > 0) { + for (const todo of todosWithoutReference) { + todo.reference = `$${new bson_1.ObjectId().toHexString()}`; + } + yield saveChanges(core_1.getInput('collect_commit_msg'), core_1.getInput('collect_commit_body')); + } + // Every TODO must have a reference by now. + for (const todo of todoComments) { + tkt_1.invariant(todo.reference, 'TODO "%s" at %s must have a reference by now!', todo.title, todo.file.fileName); + } + // Update all the tasks according to the TODO state. + const associated = yield TaskUpdater.ensureAllTodosAreAssociated(todoComments); + yield saveChanges(core_1.getInput('reference_commit_msg').replace(/%s/, associated.join(', ')), core_1.getInput('reference_commit_body').replace(/%s/, associated.join(', '))); + // Reconcile all tasks + yield TaskUpdater.reconcileTasks(todoComments); + }); +} +exports.runMain = runMain; + + +/***/ }), + +/***/ 6228: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseTodos = void 0; +function parseTodos(file) { + const out = []; + let currentTodo; + for (const [lineIndex, line] of file.contents.lines.entries()) { + const match = line.match(/^(\W+\s)TODO(?: \[([^\]\s]+)\])?:(.*)/); + if (match) { + const todo = new Todo(file, lineIndex, match[1], match[2], match[3]); + currentTodo = todo; + out.push(todo); + } + else if (currentTodo) { + const beforePrefix = line.substr(0, currentTodo.prefix.length); + const afterPrefix = line.substr(currentTodo.prefix.length); + if (beforePrefix.trimRight() === currentTodo.prefix.trimRight() && + (!afterPrefix || beforePrefix.match(/\s$/))) { + currentTodo.handleLine(afterPrefix); + } + else { + currentTodo = undefined; + } + } + } + return out; +} +exports.parseTodos = parseTodos; +class Todo { + constructor(file, line, prefix, reference, suffix) { + this.file = file; + this.line = line; + this.prefix = prefix; + this.currentReference = reference; + this.suffix = suffix; + this.title = suffix.trim(); + this.body = ''; + } + get reference() { + return this.currentReference; + } + set reference(newRef) { + this.currentReference = newRef; + this.file.contents.changeLine(this.line, `${this.prefix}TODO${newRef ? ` [${newRef}]` : ''}:${this.suffix}`); + } + get startLine() { + return this.line + 1; + } + handleLine(line) { + if (!this.title) { + this.title = line; + } + else if (this.body || line) { + this.body += (this.body ? '\n' : '') + line; + } + } +} + + +/***/ }), + +/***/ 7351: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const os = __importStar(__webpack_require__(2087)); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +} +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); +} +exports.toCommandValue = toCommandValue; +function escapeData(s) { + return toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map + +/***/ }), + +/***/ 6432: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const command_1 = __webpack_require__(7351); +const os = __importStar(__webpack_require__(2087)); +const path = __importStar(__webpack_require__(5622)); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = command_1.toCommandValue(val); + process.env[name] = convertedVal; + command_1.issueCommand('set-env', { name }, convertedVal); +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + command_1.issueCommand('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + command_1.issueCommand('add-path', {}, inputPath); + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. The value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); + } + return val.trim(); +} +exports.getInput = getInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + command_1.issueCommand('set-output', { name }, value); +} +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + command_1.issue('echo', enabled ? 'on' : 'off'); +} +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + command_1.issueCommand('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + */ +function error(message) { + command_1.issue('error', message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds an warning issue + * @param message warning issue message. Errors will be converted to string via toString() + */ +function warning(message) { + command_1.issue('warning', message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + command_1.issue('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + command_1.issue('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + command_1.issueCommand('save-state', { name }, value); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +//# sourceMappingURL=core.js.map + +/***/ }), + +/***/ 4087: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Context = void 0; +const fs_1 = __webpack_require__(5747); +const os_1 = __webpack_require__(2087); +class Context { + /** + * Hydrate the context from the environment + */ + constructor() { + this.payload = {}; + if (process.env.GITHUB_EVENT_PATH) { + if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) { + this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); + } + else { + const path = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); + } + } + this.eventName = process.env.GITHUB_EVENT_NAME; + this.sha = process.env.GITHUB_SHA; + this.ref = process.env.GITHUB_REF; + this.workflow = process.env.GITHUB_WORKFLOW; + this.action = process.env.GITHUB_ACTION; + this.actor = process.env.GITHUB_ACTOR; + this.job = process.env.GITHUB_JOB; + this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); + this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); + } + get issue() { + const payload = this.payload; + return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + } + get repo() { + if (process.env.GITHUB_REPOSITORY) { + const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); + return { owner, repo }; + } + if (this.payload.repository) { + return { + owner: this.payload.repository.owner.login, + repo: this.payload.repository.name + }; + } + throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); + } +} +exports.Context = Context; +//# sourceMappingURL=context.js.map + +/***/ }), + +/***/ 5438: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokit = exports.context = void 0; +const Context = __importStar(__webpack_require__(4087)); +const utils_1 = __webpack_require__(3030); +exports.context = new Context.Context(); +/** + * Returns a hydrated octokit ready to use for GitHub Actions + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokit(token, options) { + return new utils_1.GitHub(utils_1.getOctokitOptions(token, options)); +} +exports.getOctokit = getOctokit; +//# sourceMappingURL=github.js.map + +/***/ }), + +/***/ 7914: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0; +const httpClient = __importStar(__webpack_require__(9925)); +function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error('Parameter token or opts.auth is required'); + } + else if (token && options.auth) { + throw new Error('Parameters token and opts.auth may not both be specified'); + } + return typeof options.auth === 'string' ? options.auth : `token ${token}`; +} +exports.getAuthString = getAuthString; +function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); +} +exports.getProxyAgent = getProxyAgent; +function getApiBaseUrl() { + return process.env['GITHUB_API_URL'] || 'https://api.github.com'; +} +exports.getApiBaseUrl = getApiBaseUrl; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 3030: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokitOptions = exports.GitHub = exports.context = void 0; +const Context = __importStar(__webpack_require__(4087)); +const Utils = __importStar(__webpack_require__(7914)); +// octokit + plugins +const core_1 = __webpack_require__(6762); +const plugin_rest_endpoint_methods_1 = __webpack_require__(3044); +const plugin_paginate_rest_1 = __webpack_require__(4193); +exports.context = new Context.Context(); +const baseUrl = Utils.getApiBaseUrl(); +const defaults = { + baseUrl, + request: { + agent: Utils.getProxyAgent(baseUrl) + } +}; +exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(defaults); +/** + * Convience function to correctly format Octokit Options to pass into the constructor. + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokitOptions(token, options) { + const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller + // Auth + const auth = Utils.getAuthString(token, opts); + if (auth) { + opts.auth = auth; + } + return opts; +} +exports.getOctokitOptions = getOctokitOptions; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 9925: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const url = __webpack_require__(8835); +const http = __webpack_require__(8605); +const https = __webpack_require__(7211); +const pm = __webpack_require__(6443); +let tunnel; +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers = exports.Headers || (exports.Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +/** + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ +function getProxyUrl(serverUrl) { + let proxyUrl = pm.getProxyUrl(url.parse(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; +} +exports.getProxyUrl = getProxyUrl; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; +const ExponentialBackoffCeiling = 10; +const ExponentialBackoffTimeSlice = 5; +class HttpClientResponse { + constructor(message) { + this.message = message; + } + readBody() { + return new Promise(async (resolve, reject) => { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + }); + } +} +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + let parsedUrl = url.parse(requestUrl); + return parsedUrl.protocol === 'https:'; +} +exports.isHttps = isHttps; +class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + } + get(requestUrl, additionalHeaders) { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + } + del(requestUrl, additionalHeaders) { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + } + post(requestUrl, data, additionalHeaders) { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + } + patch(requestUrl, data, additionalHeaders) { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + } + put(requestUrl, data, additionalHeaders) { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + } + head(requestUrl, additionalHeaders) { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return this.request(verb, requestUrl, stream, additionalHeaders); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + async getJson(requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + let res = await this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + async postJson(requestUrl, obj, additionalHeaders = {}) { + let data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + let res = await this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + async putJson(requestUrl, obj, additionalHeaders = {}) { + let data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + let res = await this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + async patchJson(requestUrl, obj, additionalHeaders = {}) { + let data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + let res = await this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + async request(verb, requestUrl, data, headers) { + if (this._disposed) { + throw new Error('Client has already been disposed.'); + } + let parsedUrl = url.parse(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + while (numTries < maxTries) { + response = await this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (let i = 0; i < this.handlers.length; i++) { + if (this.handlers[i].canHandleAuthentication(response)) { + authenticationHandler = this.handlers[i]; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + let parsedRedirectUrl = url.parse(redirectUrl); + if (parsedUrl.protocol == 'https:' && + parsedUrl.protocol != parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + await response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (let header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = await this.requestRaw(info, data); + redirectsRemaining--; + } + if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + await response.readBody(); + await this._performExponentialBackoff(numTries); + } + } + return response; + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info, data) { + return new Promise((resolve, reject) => { + let callbackForResult = function (err, res) { + if (err) { + reject(err); + } + resolve(res); + }; + this.requestRawWithCallback(info, data, callbackForResult); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info, data, onResult) { + let socket; + if (typeof data === 'string') { + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); + } + let callbackCalled = false; + let handleResult = (err, res) => { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + }; + let req = info.httpModule.request(info.options, (msg) => { + let res = new HttpClientResponse(msg); + handleResult(null, res); + }); + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); + } + handleResult(new Error('Request timeout: ' + info.options.path), null); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err, null); + }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); + } + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); + } + else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + let parsedUrl = url.parse(serverUrl); + return this._getAgent(parsedUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; + } + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + this.handlers.forEach(handler => { + handler.prepareRequest(info.options); + }); + } + return info; + } + _mergeHeaders(headers) { + const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); + } + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default; + } + _getAgent(parsedUrl) { + let agent; + let proxyUrl = pm.getProxyUrl(parsedUrl); + let useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (this._keepAlive && !useProxy) { + agent = this._agent; + } + // if agent is already assigned use that agent. + if (!!agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (!!this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (useProxy) { + // If using proxy, need tunnel + if (!tunnel) { + tunnel = __webpack_require__(4294); + } + const agentOptions = { + maxSockets: maxSockets, + keepAlive: this._keepAlive, + proxy: { + proxyAuth: proxyUrl.auth, + host: proxyUrl.hostname, + port: proxyUrl.port + } + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } + else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + // if reusing agent across request and tunneling agent isn't assigned create a new agent + if (this._keepAlive && !agent) { + const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + // if not using private agent and tunnel agent isn't setup then use global agent + if (!agent) { + agent = usingSsl ? https.globalAgent : http.globalAgent; + } + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _performExponentialBackoff(retryNumber) { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + } + static dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + let a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + async _processResponse(res, options) { + return new Promise(async (resolve, reject) => { + const statusCode = res.message.statusCode; + const response = { + statusCode: statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode == HttpCodes.NotFound) { + resolve(response); + } + let obj; + let contents; + // get the result from the body + try { + contents = await res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // Invalid resource (contents not json); leaving result obj null + } + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = 'Failed request: (' + statusCode + ')'; + } + let err = new Error(msg); + // attach statusCode and body obj (if available) to the error object + err['statusCode'] = statusCode; + if (response.result) { + err['result'] = response.result; + } + reject(err); + } + else { + resolve(response); + } + }); + } +} +exports.HttpClient = HttpClient; + + +/***/ }), + +/***/ 6443: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const url = __webpack_require__(8835); +function getProxyUrl(reqUrl) { + let usingSsl = reqUrl.protocol === 'https:'; + let proxyUrl; + if (checkBypass(reqUrl)) { + return proxyUrl; + } + let proxyVar; + if (usingSsl) { + proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; + } + else { + proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + if (proxyVar) { + proxyUrl = url.parse(proxyVar); + } + return proxyUrl; +} +exports.getProxyUrl = getProxyUrl; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + if (!noProxy) { + return false; + } + // Determine the request port + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } + else if (reqUrl.protocol === 'http:') { + reqPort = 80; + } + else if (reqUrl.protocol === 'https:') { + reqPort = 443; + } + // Format the request hostname and hostname with port + let upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === 'number') { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + // Compare request host against noproxy + for (let upperNoProxyItem of noProxy + .split(',') + .map(x => x.trim().toUpperCase()) + .filter(x => x)) { + if (upperReqHosts.some(x => x === upperNoProxyItem)) { + return true; + } + } + return false; +} +exports.checkBypass = checkBypass; + + +/***/ }), + +/***/ 7174: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + + +const internals = { + suspectRx: /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*\:/ +}; + + +exports.parse = function (text, reviver, options) { + + // Normalize arguments + + if (!options) { + if (reviver && + typeof reviver === 'object') { + + options = reviver; + reviver = undefined; + } + else { + options = {}; + } + } + + // Parse normally, allowing exceptions + + const obj = JSON.parse(text, reviver); + + // options.protoAction: 'error' (default) / 'remove' / 'ignore' + + if (options.protoAction === 'ignore') { + return obj; + } + + // Ignore null and non-objects + + if (!obj || + typeof obj !== 'object') { + + return obj; + } + + // Check original string for potential exploit + + if (!text.match(internals.suspectRx)) { + return obj; + } + + // Scan result for proto keys + + exports.scan(obj, options); + + return obj; +}; + + +exports.scan = function (obj, options) { + + options = options || {}; + + let next = [obj]; + + while (next.length) { + const nodes = next; + next = []; + + for (const node of nodes) { + if (Object.prototype.hasOwnProperty.call(node, '__proto__')) { // Avoid calling node.hasOwnProperty directly + if (options.protoAction !== 'remove') { + throw new SyntaxError('Object contains forbidden prototype property'); + } + + delete node.__proto__; + } + + for (const key in node) { + const value = node[key]; + if (value && + typeof value === 'object') { + + next.push(node[key]); + } + } + } + } +}; + + +exports.safeParse = function (text, reviver) { + + try { + return exports.parse(text, reviver); + } + catch (ignoreError) { + return null; + } +}; + + +/***/ }), + +/***/ 334: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +async function auth(token) { + const tokenType = token.split(/\./).length === 3 ? "app" : /^v\d+\./.test(token) ? "installation" : "oauth"; + return { + type: "token", + token: token, + tokenType + }; +} + +/** + * Prefix token for usage in the Authorization header + * + * @param token OAuth token or JSON Web Token + */ +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + + return `token ${token}`; +} + +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge(route, parameters); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); +} + +const createTokenAuth = function createTokenAuth(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } + + if (typeof token !== "string") { + throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string"); + } + + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; + +exports.createTokenAuth = createTokenAuth; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 6762: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var universalUserAgent = __webpack_require__(5030); +var beforeAfterHook = __webpack_require__(3682); +var request = __webpack_require__(6234); +var graphql = __webpack_require__(8467); +var authToken = __webpack_require__(334); + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; +} + +const VERSION = "3.1.2"; + +class Octokit { + constructor(options = {}) { + const hook = new beforeAfterHook.Collection(); + const requestDefaults = { + baseUrl: request.request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + hook: hook.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" + } + }; // prepend default user agent with `options.userAgent` if set + + requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); + + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } + + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + + this.request = request.request.defaults(requestDefaults); + this.graphql = graphql.withCustomRequest(this.request).defaults(_objectSpread2(_objectSpread2({}, requestDefaults), {}, { + baseUrl: requestDefaults.baseUrl.replace(/\/api\/v3$/, "/api") + })); + this.log = Object.assign({ + debug: () => {}, + info: () => {}, + warn: console.warn.bind(console), + error: console.error.bind(console) + }, options.log); + this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance + // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registred. + // (2) If only `options.auth` is set, use the default token authentication strategy. + // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance. + // TODO [$5f5fbe42fcabad09c1c24195]: type `options.auth` based on `options.authStrategy`. + + if (!options.authStrategy) { + if (!options.auth) { + // (1) + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + // (2) + const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ + + hook.wrap("request", auth.hook); + this.auth = auth; + } + } else { + const auth = options.authStrategy(Object.assign({ + request: this.request + }, options.auth)); // @ts-ignore ¯\_(ツ)_/¯ + + hook.wrap("request", auth.hook); + this.auth = auth; + } // apply plugins + // https://stackoverflow.com/a/16345172 + + + const classConstructor = this.constructor; + classConstructor.plugins.forEach(plugin => { + Object.assign(this, plugin(this, options)); + }); + } + + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + + if (typeof defaults === "function") { + super(defaults(options)); + return; + } + + super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null)); + } + + }; + return OctokitWithDefaults; + } + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + + + static plugin(...newPlugins) { + var _a; + + const currentPlugins = this.plugins; + const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a); + return NewOctokit; + } + +} +Octokit.VERSION = VERSION; +Octokit.plugins = []; + +exports.Octokit = Octokit; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 9440: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var isPlainObject = __webpack_require__(558); +var universalUserAgent = __webpack_require__(5030); + +function lowercaseKeys(object) { + if (!object) { + return {}; + } + + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); +} + +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach(key => { + if (isPlainObject.isPlainObject(options[key])) { + if (!(key in defaults)) Object.assign(result, { + [key]: options[key] + });else result[key] = mergeDeep(defaults[key], options[key]); + } else { + Object.assign(result, { + [key]: options[key] + }); + } + }); + return result; +} + +function merge(defaults, route, options) { + if (typeof route === "string") { + let [method, url] = route.split(" "); + options = Object.assign(url ? { + method, + url + } : { + url: method + }, options); + } else { + options = Object.assign({}, route); + } // lowercase header names before merging with defaults to avoid duplicates + + + options.headers = lowercaseKeys(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten + + if (defaults && defaults.mediaType.previews.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); + } + + mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); + return mergedOptions; +} + +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); + + if (names.length === 0) { + return url; + } + + return url + separator + names.map(name => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} + +const urlVariableRegex = /\{[^}]+\}/g; + +function removeNonChars(variableName) { + return variableName.replace(/^\W+|\W+$/g, "").split(/,/); +} + +function extractUrlVariableNames(url) { + const matches = url.match(urlVariableRegex); + + if (!matches) { + return []; + } + + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); +} + +function omit(object, keysToOmit) { + return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { + obj[key] = object[key]; + return obj; + }, {}); +} + +// Based on https://github.com/bramstein/url-template, licensed under BSD +// TODO [$5f5fbe42fcabad09c1c24196]: create separate package. +// +// Copyright (c) 2012-2014, Bram Stein +// 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. 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 COPYRIGHT OWNER 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. + +/* istanbul ignore file */ +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + } + + return part; + }).join(""); +} + +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} + +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } +} + +function isDefined(value) { + return value !== undefined && value !== null; +} + +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} + +function getValues(context, operator, key, modifier) { + var value = context[key], + result = []; + + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + value = value.toString(); + + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } + + result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function (value) { + result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + }); + } else { + Object.keys(value).forEach(function (k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function (value) { + tmp.push(encodeValue(operator, value)); + }); + } else { + Object.keys(value).forEach(function (k) { + if (isDefined(value[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value[k].toString())); + } + }); + } + + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); + } + } + } + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + + return result; +} + +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} + +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } + + expression.split(/,/g).forEach(function (variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); + + if (operator && operator !== "+") { + var separator = ","; + + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); + } + } else { + return encodeReserved(literal); + } + }); +} + +function parse(options) { + // https://fetch.spec.whatwg.org/#methods + let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible + + let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{+$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later + + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); + + if (!/^http/.test(url)) { + url = options.baseUrl + url; + } + + const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); + + if (!isBinaryRequest) { + if (options.mediaType.format) { + // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw + headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); + } + + if (options.mediaType.previews.length) { + const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; + headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } + } // for GET/HEAD requests, set URL query parameters from remaining parameters + // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters + + + if (["GET", "HEAD"].includes(method)) { + url = addQueryParameters(url, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } else { + headers["content-length"] = 0; + } + } + } // default content-type for JSON if body is set + + + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. + // fetch does not allow to set `content-length` header, but we can set body to an empty string + + + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } // Only return body/request keys if present + + + return Object.assign({ + method, + url, + headers + }, typeof body !== "undefined" ? { + body + } : null, options.request ? { + request: options.request + } : null); +} + +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} + +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS = merge(oldDefaults, newDefaults); + const endpoint = endpointWithDefaults.bind(null, DEFAULTS); + return Object.assign(endpoint, { + DEFAULTS, + defaults: withDefaults.bind(null, DEFAULTS), + merge: merge.bind(null, DEFAULTS), + parse + }); +} + +const VERSION = "6.0.6"; + +const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. +// So we use RequestParameters and add method as additional required property. + +const DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "", + previews: [] + } +}; + +const endpoint = withDefaults(null, DEFAULTS); + +exports.endpoint = endpoint; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 558: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; +} + +function isPlainObject(o) { + var ctor,prot; + + if (isObject(o) === false) return false; + + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; + + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } + + // Most likely a plain Object + return true; +} + +exports.isPlainObject = isPlainObject; + + +/***/ }), + +/***/ 8467: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var request = __webpack_require__(6234); +var universalUserAgent = __webpack_require__(5030); + +const VERSION = "4.5.6"; + +class GraphqlError extends Error { + constructor(request, response) { + const message = response.data.errors[0].message; + super(message); + Object.assign(this, response.data); + Object.assign(this, { + headers: response.headers + }); + this.name = "GraphqlError"; + this.request = request; // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + +} + +const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"]; +const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request, query, options) { + if (typeof query === "string" && options && "query" in options) { + return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`)); + } + + const parsedOptions = typeof query === "string" ? Object.assign({ + query + }, options) : query; + const requestOptions = Object.keys(parsedOptions).reduce((result, key) => { + if (NON_VARIABLE_OPTIONS.includes(key)) { + result[key] = parsedOptions[key]; + return result; + } + + if (!result.variables) { + result.variables = {}; + } + + result.variables[key] = parsedOptions[key]; + return result; + }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix + // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451 + + const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl; + + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + + return request(requestOptions).then(response => { + if (response.data.errors) { + const headers = {}; + + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + + throw new GraphqlError(requestOptions, { + headers, + data: response.data + }); + } + + return response.data.data; + }); +} + +function withDefaults(request$1, newDefaults) { + const newRequest = request$1.defaults(newDefaults); + + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: request.request.endpoint + }); +} + +const graphql$1 = withDefaults(request.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}` + }, + method: "POST", + url: "/graphql" +}); +function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); +} + +exports.graphql = graphql$1; +exports.withCustomRequest = withCustomRequest; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 4193: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const VERSION = "2.3.3"; + +/** + * Some “list” response that can be paginated have a different response structure + * + * They have a `total_count` key in the response (search also has `incomplete_results`, + * /installation/repositories also has `repository_selection`), as well as a key with + * the list of the items which name varies from endpoint to endpoint. + * + * Octokit normalizes these responses so that paginated results are always returned following + * the same structure. One challenge is that if the list response has only one page, no Link + * header is provided, so this header alone is not sufficient to check wether a response is + * paginated or not. + * + * We check if a "total_count" key is present in the response data, but also make sure that + * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would + * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref + */ +function normalizePaginatedListResponse(response) { + const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); + if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way + // to retrieve the same information. + + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } + + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + + response.data.total_count = totalCount; + return response; +} + +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + next() { + if (!url) { + return Promise.resolve({ + done: true + }); + } + + return requestMethod({ + method, + url, + headers + }).then(normalizePaginatedListResponse).then(response => { + // `response.headers.link` format: + // '; rel="next", ; rel="last"' + // sets `url` to undefined if "next" URL is not present or `link` header is not set + url = ((response.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; + return { + value: response + }; + }); + } + + }) + }; +} + +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = undefined; + } + + return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); +} + +function gather(octokit, results, iterator, mapFn) { + return iterator.next().then(result => { + if (result.done) { + return results; + } + + let earlyExit = false; + + function done() { + earlyExit = true; + } + + results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); + + if (earlyExit) { + return results; + } + + return gather(octokit, results, iterator, mapFn); + }); +} + +/** + * @param octokit Octokit instance + * @param options Options passed to Octokit constructor + */ + +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; +} +paginateRest.VERSION = VERSION; + +exports.paginateRest = paginateRest; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 8883: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const VERSION = "1.0.0"; + +/** + * @param octokit Octokit instance + * @param options Options passed to Octokit constructor + */ + +function requestLog(octokit) { + octokit.hook.wrap("request", (request, options) => { + octokit.log.debug("request", options); + const start = Date.now(); + const requestOptions = octokit.request.endpoint.parse(options); + const path = requestOptions.url.replace(options.baseUrl, ""); + return request(options).then(response => { + octokit.log.info(`${requestOptions.method} ${path} - ${response.status} in ${Date.now() - start}ms`); + return response; + }).catch(error => { + octokit.log.info(`${requestOptions.method} ${path} - ${error.status} in ${Date.now() - start}ms`); + throw error; + }); + }); +} +requestLog.VERSION = VERSION; + +exports.requestLog = requestLog; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 3044: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const Endpoints = { + actions: { + addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], + cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"], + createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"], + createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"], + deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"], + deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"], + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], + downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"], + downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"], + downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"], + getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"], + listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"], + listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], + setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"], + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}"], + checkToken: ["POST /applications/{client_id}/token"], + createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", { + mediaType: { + previews: ["corsair"] + } + }], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens"], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"], + getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"], + getUserInstallation: ["GET /users/{username}/installation"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"], + listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories"], + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"], + removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: ["GET /users/{username}/settings/billing/actions"], + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: ["GET /users/{username}/settings/billing/packages"], + getSharedStorageBillingOrg: ["GET /orgs/{org}/settings/billing/shared-storage"], + getSharedStorageBillingUser: ["GET /users/{username}/settings/billing/shared-storage"] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs", { + mediaType: { + previews: ["antiope"] + } + }], + createSuite: ["POST /repos/{owner}/{repo}/check-suites", { + mediaType: { + previews: ["antiope"] + } + }], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}", { + mediaType: { + previews: ["antiope"] + } + }], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}", { + mediaType: { + previews: ["antiope"] + } + }], + listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", { + mediaType: { + previews: ["antiope"] + } + }], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs", { + mediaType: { + previews: ["antiope"] + } + }], + listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", { + mediaType: { + previews: ["antiope"] + } + }], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites", { + mediaType: { + previews: ["antiope"] + } + }], + rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest", { + mediaType: { + previews: ["antiope"] + } + }], + setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences", { + mediaType: { + previews: ["antiope"] + } + }], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}", { + mediaType: { + previews: ["antiope"] + } + }] + }, + codeScanning: { + getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_id}"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct", { + mediaType: { + previews: ["scarlet-witch"] + } + }], + getConductCode: ["GET /codes_of_conduct/{key}", { + mediaType: { + previews: ["scarlet-witch"] + } + }], + getForRepo: ["GET /repos/{owner}/{repo}/community/code_of_conduct", { + mediaType: { + previews: ["scarlet-witch"] + } + }] + }, + emojis: { + get: ["GET /emojis"] + }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"] + }, + interactions: { + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }] + }, + issues: { + addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", { + mediaType: { + previews: ["mockingbird"] + } + }], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"], + removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"], + removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: ["POST /markdown/raw", { + headers: { + "content-type": "text/plain; charset=utf-8" + } + }] + }, + meta: { + get: ["GET /meta"] + }, + migrations: { + cancelImport: ["DELETE /repos/{owner}/{repo}/import"], + deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive", { + mediaType: { + previews: ["wyandotte"] + } + }], + deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive", { + mediaType: { + previews: ["wyandotte"] + } + }], + downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive", { + mediaType: { + previews: ["wyandotte"] + } + }], + getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive", { + mediaType: { + previews: ["wyandotte"] + } + }], + getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"], + getImportStatus: ["GET /repos/{owner}/{repo}/import"], + getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}", { + mediaType: { + previews: ["wyandotte"] + } + }], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}", { + mediaType: { + previews: ["wyandotte"] + } + }], + listForAuthenticatedUser: ["GET /user/migrations", { + mediaType: { + previews: ["wyandotte"] + } + }], + listForOrg: ["GET /orgs/{org}/migrations", { + mediaType: { + previews: ["wyandotte"] + } + }], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories", { + mediaType: { + previews: ["wyandotte"] + } + }], + listReposForUser: ["GET /user/migrations/{migration_id}/repositories", { + mediaType: { + previews: ["wyandotte"] + } + }], + mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], + setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + startImport: ["PUT /repos/{owner}/{repo}/import"], + unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock", { + mediaType: { + previews: ["wyandotte"] + } + }], + unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock", { + mediaType: { + previews: ["wyandotte"] + } + }], + updateImport: ["PATCH /repos/{owner}/{repo}/import"] + }, + orgs: { + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"], + createInvitation: ["POST /orgs/{org}/invitations"], + createWebhook: ["POST /orgs/{org}/hooks"], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + get: ["GET /orgs/{org}"], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations"], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listMembers: ["GET /orgs/{org}/members"], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listWebhooks: ["GET /orgs/{org}/hooks"], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"], + removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"] + }, + projects: { + addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}", { + mediaType: { + previews: ["inertia"] + } + }], + createCard: ["POST /projects/columns/{column_id}/cards", { + mediaType: { + previews: ["inertia"] + } + }], + createColumn: ["POST /projects/{project_id}/columns", { + mediaType: { + previews: ["inertia"] + } + }], + createForAuthenticatedUser: ["POST /user/projects", { + mediaType: { + previews: ["inertia"] + } + }], + createForOrg: ["POST /orgs/{org}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + createForRepo: ["POST /repos/{owner}/{repo}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + delete: ["DELETE /projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + deleteCard: ["DELETE /projects/columns/cards/{card_id}", { + mediaType: { + previews: ["inertia"] + } + }], + deleteColumn: ["DELETE /projects/columns/{column_id}", { + mediaType: { + previews: ["inertia"] + } + }], + get: ["GET /projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + getCard: ["GET /projects/columns/cards/{card_id}", { + mediaType: { + previews: ["inertia"] + } + }], + getColumn: ["GET /projects/columns/{column_id}", { + mediaType: { + previews: ["inertia"] + } + }], + getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission", { + mediaType: { + previews: ["inertia"] + } + }], + listCards: ["GET /projects/columns/{column_id}/cards", { + mediaType: { + previews: ["inertia"] + } + }], + listCollaborators: ["GET /projects/{project_id}/collaborators", { + mediaType: { + previews: ["inertia"] + } + }], + listColumns: ["GET /projects/{project_id}/columns", { + mediaType: { + previews: ["inertia"] + } + }], + listForOrg: ["GET /orgs/{org}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + listForRepo: ["GET /repos/{owner}/{repo}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + listForUser: ["GET /users/{username}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + moveCard: ["POST /projects/columns/cards/{card_id}/moves", { + mediaType: { + previews: ["inertia"] + } + }], + moveColumn: ["POST /projects/columns/{column_id}/moves", { + mediaType: { + previews: ["inertia"] + } + }], + removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}", { + mediaType: { + previews: ["inertia"] + } + }], + update: ["PATCH /projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + updateCard: ["PATCH /projects/columns/cards/{card_id}", { + mediaType: { + previews: ["inertia"] + } + }], + updateColumn: ["PATCH /projects/columns/{column_id}", { + mediaType: { + previews: ["inertia"] + } + }] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"], + deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], + listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], + requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], + submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch", { + mediaType: { + previews: ["lydian"] + } + }], + updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"] + }, + rateLimit: { + get: ["GET /rate_limit"] + }, + reactions: { + createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteLegacy: ["DELETE /reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }, { + deprecated: "octokit.reactions.deleteLegacy() is deprecated, see https://developer.github.com/v3/reactions/#delete-a-reaction-legacy" + }], + listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }] + }, + repos: { + acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}"], + addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts" + }], + addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams" + }], + addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users" + }], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts", { + mediaType: { + previews: ["dorian"] + } + }], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"], + createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + createForAuthenticatedUser: ["POST /user/repos"], + createFork: ["POST /repos/{owner}/{repo}/forks"], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages", { + mediaType: { + previews: ["switcheroo"] + } + }], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate", { + mediaType: { + previews: ["baptiste"] + } + }], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}"], + delete: ["DELETE /repos/{owner}/{repo}"], + deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], + deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"], + deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], + deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages", { + mediaType: { + previews: ["switcheroo"] + } + }], + deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes", { + mediaType: { + previews: ["london"] + } + }], + disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts", { + mediaType: { + previews: ["dorian"] + } + }], + downloadArchive: ["GET /repos/{owner}/{repo}/{archive_format}/{ref}"], + enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes", { + mediaType: { + previews: ["london"] + } + }], + enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts", { + mediaType: { + previews: ["dorian"] + } + }], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], + getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"], + getAllTopics: ["GET /repos/{owner}/{repo}/topics", { + mediaType: { + previews: ["mercy"] + } + }], + getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile", { + mediaType: { + previews: ["black-panther"] + } + }], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], + getReadme: ["GET /repos/{owner}/{repo}/readme"], + getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], + getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], + getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], + getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", { + mediaType: { + previews: ["groot"] + } + }], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", { + mediaType: { + previews: ["groot"] + } + }], + listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"], + removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts" + }], + removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams" + }], + removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users" + }], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", { + mediaType: { + previews: ["mercy"] + } + }], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts" + }], + setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams" + }], + setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users" + }], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"], + updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"], + updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", { + baseUrl: "https://uploads.github.com" + }] + }, + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits", { + mediaType: { + previews: ["cloak"] + } + }], + issuesAndPullRequests: ["GET /search/issues"], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics", { + mediaType: { + previews: ["mercy"] + } + }], + users: ["GET /search/users"] + }, + teams: { + addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"], + addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], + deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], + getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"], + listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"], + removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"], + removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], + updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] + }, + users: { + addEmailForAuthenticated: ["POST /user/emails"], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKeyForAuthenticated: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: ["POST /user/keys"], + deleteEmailForAuthenticated: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}"], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}"], + list: ["GET /users"], + listBlockedByAuthenticated: ["GET /user/blocks"], + listEmailsForAuthenticated: ["GET /user/emails"], + listFollowedByAuthenticated: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeysForAuthenticated: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmailsForAuthenticated: ["GET /user/public_emails"], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: ["GET /user/keys"], + setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility"], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] + } +}; + +const VERSION = "4.1.4"; + +function endpointsToMethods(octokit, endpointsMap) { + const newMethods = {}; + + for (const [scope, endpoints] of Object.entries(endpointsMap)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign({ + method, + url + }, defaults); + + if (!newMethods[scope]) { + newMethods[scope] = {}; + } + + const scopeMethods = newMethods[scope]; + + if (decorations) { + scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); + continue; + } + + scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); + } + } + + return newMethods; +} + +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + /* istanbul ignore next */ + + function withDecorations(...args) { + // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData` + + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: undefined + }); + return requestWithDefaults(options); + } + + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`); + } + + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } + + if (decorations.renamedParameters) { + // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + const options = requestWithDefaults.endpoint.merge(...args); + + for (const [name, alias] of Object.entries(decorations.renamedParameters)) { + if (name in options) { + octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`); + + if (!(alias in options)) { + options[alias] = options[name]; + } + + delete options[name]; + } + } + + return requestWithDefaults(options); + } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + + + return requestWithDefaults(...args); + } + + return Object.assign(withDecorations, requestWithDefaults); +} + +/** + * This plugin is a 1:1 copy of internal @octokit/rest plugins. The primary + * goal is to rebuild @octokit/rest on top of @octokit/core. Once that is + * done, we will remove the registerEndpoints methods and return the methods + * directly as with the other plugins. At that point we will also remove the + * legacy workarounds and deprecations. + * + * See the plan at + * https://github.com/octokit/plugin-rest-endpoint-methods.js/pull/1 + */ + +function restEndpointMethods(octokit) { + return endpointsToMethods(octokit, Endpoints); +} +restEndpointMethods.VERSION = VERSION; + +exports.restEndpointMethods = restEndpointMethods; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 537: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var deprecation = __webpack_require__(8932); +var once = _interopDefault(__webpack_require__(1223)); + +const logOnce = once(deprecation => console.warn(deprecation)); +/** + * Error with extra properties to help with debugging + */ + +class RequestError extends Error { + constructor(message, statusCode, options) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = "HttpError"; + this.status = statusCode; + Object.defineProperty(this, "code", { + get() { + logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); + return statusCode; + } + + }); + this.headers = options.headers || {}; // redact request credentials without mutating original request options + + const requestCopy = Object.assign({}, options.request); + + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") + }); + } + + requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit + // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications + .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended + // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header + .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); + this.request = requestCopy; + } + +} + +exports.RequestError = RequestError; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 6234: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var endpoint = __webpack_require__(9440); +var universalUserAgent = __webpack_require__(5030); +var isPlainObject = __webpack_require__(9062); +var nodeFetch = _interopDefault(__webpack_require__(467)); +var requestError = __webpack_require__(537); + +const VERSION = "5.4.8"; + +function getBufferResponse(response) { + return response.arrayBuffer(); +} + +function fetchWrapper(requestOptions) { + if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + + let headers = {}; + let status; + let url; + const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch; + return fetch(requestOptions.url, Object.assign({ + method: requestOptions.method, + body: requestOptions.body, + headers: requestOptions.headers, + redirect: requestOptions.redirect + }, requestOptions.request)).then(response => { + url = response.url; + status = response.status; + + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + + if (status === 204 || status === 205) { + return; + } // GitHub API returns 200 for HEAD requests + + + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + + throw new requestError.RequestError(response.statusText, status, { + headers, + request: requestOptions + }); + } + + if (status === 304) { + throw new requestError.RequestError("Not modified", status, { + headers, + request: requestOptions + }); + } + + if (status >= 400) { + return response.text().then(message => { + const error = new requestError.RequestError(message, status, { + headers, + request: requestOptions + }); + + try { + let responseBody = JSON.parse(error.message); + Object.assign(error, responseBody); + let errors = responseBody.errors; // Assumption `errors` would always be in Array format + + error.message = error.message + ": " + errors.map(JSON.stringify).join(", "); + } catch (e) {// ignore, see octokit/rest.js#684 + } + + throw error; + }); + } + + const contentType = response.headers.get("content-type"); + + if (/application\/json/.test(contentType)) { + return response.json(); + } + + if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { + return response.text(); + } + + return getBufferResponse(response); + }).then(data => { + return { + status, + url, + headers, + data + }; + }).catch(error => { + if (error instanceof requestError.RequestError) { + throw error; + } + + throw new requestError.RequestError(error.message, 500, { + headers, + request: requestOptions + }); + }); +} + +function withDefaults(oldEndpoint, newDefaults) { + const endpoint = oldEndpoint.defaults(newDefaults); + + const newApi = function (route, parameters) { + const endpointOptions = endpoint.merge(route, parameters); + + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint.parse(endpointOptions)); + } + + const request = (route, parameters) => { + return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters))); + }; + + Object.assign(request, { + endpoint, + defaults: withDefaults.bind(null, endpoint) + }); + return endpointOptions.request.hook(request, endpointOptions); + }; + + return Object.assign(newApi, { + endpoint, + defaults: withDefaults.bind(null, endpoint) + }); +} + +const request = withDefaults(endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}` + } +}); + +exports.request = request; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 9062: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; +} + +function isPlainObject(o) { + var ctor,prot; + + if (isObject(o) === false) return false; + + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; + + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } + + // Most likely a plain Object + return true; +} + +exports.isPlainObject = isPlainObject; + + +/***/ }), + +/***/ 5375: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var core = __webpack_require__(6762); +var pluginRequestLog = __webpack_require__(8883); +var pluginPaginateRest = __webpack_require__(4193); +var pluginRestEndpointMethods = __webpack_require__(3044); + +const VERSION = "18.0.5"; + +const Octokit = core.Octokit.plugin(pluginRequestLog.requestLog, pluginRestEndpointMethods.restEndpointMethods, pluginPaginateRest.paginateRest).defaults({ + userAgent: `octokit-rest.js/${VERSION}` +}); + +exports.Octokit = Octokit; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 6950: +/***/ ((module) => { + +"use strict"; + + +/* global SharedArrayBuffer, Atomics */ + +if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') { + const nil = new Int32Array(new SharedArrayBuffer(4)) + + function sleep (ms) { + // also filters out NaN, non-number types, including empty strings, but allows bigints + const valid = ms > 0 && ms < Infinity + if (valid === false) { + if (typeof ms !== 'number' && typeof ms !== 'bigint') { + throw TypeError('sleep: ms must be a number') + } + throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') + } + + Atomics.wait(nil, 0, 0, Number(ms)) + } + module.exports = sleep +} else { + + function sleep (ms) { + // also filters out NaN, non-number types, including empty strings, but allows bigints + const valid = ms > 0 && ms < Infinity + if (valid === false) { + if (typeof ms !== 'number' && typeof ms !== 'bigint') { + throw TypeError('sleep: ms must be a number') + } + throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') + } + const target = Date.now() + Number(ms) + while (target > Date.now()){} + } + + module.exports = sleep + +} + + +/***/ }), + +/***/ 6071: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var aws4 = exports, + url = __webpack_require__(8835), + querystring = __webpack_require__(1191), + crypto = __webpack_require__(6417), + lru = __webpack_require__(4225), + credentialsCache = lru(1000) + +// 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) +} + +function hash(string, encoding) { + return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) +} + +// 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 encodeRfc3986Full(str) { + return encodeRfc3986(encodeURIComponent(str)) +} + +// request: { path | body, [host], [method], [headers], [service], [region] } +// credentials: { accessKeyId, secretAccessKey, [sessionToken] } +function RequestSigner(request, credentials) { + + if (typeof request === 'string') request = url.parse(request) + + var headers = request.headers = (request.headers || {}), + hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host) + + this.request = request + this.credentials = credentials || this.defaultCredentials() + + 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' + + if (!headers.Host && !headers.host) { + headers.Host = request.hostname || request.host || this.createHost() + + // 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 + + this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' +} + +RequestSigner.prototype.matchHost = function(host) { + var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/) + var hostParts = (match || []).slice(1, 3) + + // 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() + + if (hostParts[1] == 's3') { + hostParts[0] = 's3' + hostParts[1] = 'us-east-1' + } else { + for (var i = 0; i < 2; i++) { + if (/^s3-/.test(hostParts[i])) { + hostParts[1] = hostParts[i].slice(3) + hostParts[0] = 's3' + break + } + } + } + + 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 +} + +RequestSigner.prototype.createHost = function() { + var region = this.isSingleRegion() ? '' : '.' + this.region, + subdomain = this.service === 'ses' ? 'email' : this.service + return subdomain + region + '.amazonaws.com' +} + +RequestSigner.prototype.prepareRequest = function() { + this.parsePath() + + var request = this.request, headers = request.headers, query + + if (request.signQuery) { + + this.parsedPath.query = query = this.parsedPath.query || {} + + if (this.credentials.sessionToken) + query['X-Amz-Security-Token'] = this.credentials.sessionToken + + if (this.service === 's3' && !query['X-Amz-Expires']) + query['X-Amz-Expires'] = 86400 + + 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() + + } else { + + 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) + + if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) + headers['X-Amz-Security-Token'] = this.credentials.sessionToken + + if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) + headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') + + 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() + } + + delete headers.Authorization + delete headers.authorization + } +} + +RequestSigner.prototype.sign = function() { + if (!this.parsedPath) this.prepareRequest() + + if (this.request.signQuery) { + this.parsedPath.query['X-Amz-Signature'] = this.signature() + } else { + this.request.headers.Authorization = this.authHeader() + } + + this.request.path = this.formatPath() + + return this.request +} + +RequestSigner.prototype.getDateTime = function() { + if (!this.datetime) { + var headers = this.request.headers, + date = new Date(headers.Date || headers.date || new Date) + + 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 +} + +RequestSigner.prototype.getDate = function() { + return this.getDateTime().substr(0, 8) +} + +RequestSigner.prototype.authHeader = function() { + return [ + 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), + 'SignedHeaders=' + this.signedHeaders(), + 'Signature=' + this.signature(), + ].join(', ') +} + +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') +} + +RequestSigner.prototype.stringToSign = function() { + return [ + 'AWS4-HMAC-SHA256', + this.getDateTime(), + this.credentialString(), + hash(this.canonicalString(), 'hex'), + ].join('\n') +} + +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 + + 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 (query) { + var reducedQuery = Object.keys(query).reduce(function(obj, key) { + if (!key) return obj + obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] : + (firstValOnly ? query[key][0] : query[key]) + return obj + }, {}) + var encodedQueryPieces = [] + Object.keys(reducedQuery).sort().forEach(function(key) { + if (!Array.isArray(reducedQuery[key])) { + encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key])) + } else { + reducedQuery[key].map(encodeRfc3986Full).sort() + .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) }) + } + }) + queryStr = encodedQueryPieces.join('&') + } + 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 = decodeURIComponent(piece.replace(/\+/g, ' ')) + path.push(encodeRfc3986Full(piece)) + } + return path + }, []).join('/') + if (pathStr[0] !== '/') pathStr = '/' + pathStr + if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') + } + + return [ + this.request.method || 'GET', + pathStr, + queryStr, + this.canonicalHeaders() + '\n', + this.signedHeaders(), + bodyHash, + ].join('\n') +} + +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') +} + +RequestSigner.prototype.signedHeaders = function() { + return Object.keys(this.request.headers) + .map(function(key) { return key.toLowerCase() }) + .sort() + .join(';') +} + +RequestSigner.prototype.credentialString = function() { + return [ + this.getDate(), + this.region, + this.service, + 'aws4_request', + ].join('/') +} + +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, + } +} + +RequestSigner.prototype.parsePath = function() { + var path = this.request.path || '/' + + // 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 = encodeURI(decodeURI(path)) + } + + var queryIx = path.indexOf('?'), + query = null + + if (queryIx >= 0) { + query = querystring.parse(path.slice(queryIx + 1)) + path = path.slice(0, queryIx) + } + + this.parsedPath = { + path: path, + query: query, + } +} + +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)) +} + +aws4.RequestSigner = RequestSigner + +aws4.sign = function(request, credentials) { + return new RequestSigner(request, credentials).sign() +} + + +/***/ }), + +/***/ 4225: +/***/ ((module) => { + +module.exports = function(size) { + return new LruCache(size) +} + +function LruCache(size) { + this.capacity = size | 0 + this.map = Object.create(null) + this.list = new DoublyLinkedList() +} + +LruCache.prototype.get = function(key) { + var node = this.map[key] + if (node == null) return undefined + this.used(node) + return node.val +} + +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 +} + +LruCache.prototype.used = function(node) { + this.list.moveToFront(node) +} + +LruCache.prototype.prune = function() { + var node = this.list.pop() + if (node != null) { + delete this.map[node.key] + this.capacity++ + } +} + + +function DoublyLinkedList() { + this.firstNode = null + this.lastNode = null +} + +DoublyLinkedList.prototype.moveToFront = function(node) { + if (this.firstNode == node) return + + this.remove(node) + + 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 + } +} + +DoublyLinkedList.prototype.pop = function() { + var lastNode = this.lastNode + if (lastNode != null) { + this.remove(lastNode) + } + return lastNode +} + +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 + } +} + + +function DoublyLinkedNode(key, val) { + this.key = key + this.val = val + this.prev = null + this.next = null +} + + +/***/ }), + +/***/ 3682: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var register = __webpack_require__(4670) +var addHook = __webpack_require__(5549) +var removeHook = __webpack_require__(6819) + +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind +var bindable = bind.bind(bind) + +function bindApi (hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) + hook.api = { remove: removeHookRef } + hook.remove = removeHookRef + + ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind] + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) + }) +} + +function HookSingular () { + var singularHookName = 'h' + var singularHookState = { + registry: {} + } + var singularHook = register.bind(null, singularHookState, singularHookName) + bindApi(singularHook, singularHookState, singularHookName) + return singularHook +} + +function HookCollection () { + var state = { + registry: {} + } + + var hook = register.bind(null, state) + bindApi(hook, state) + + return hook +} + +var collectionHookDeprecationMessageDisplayed = false +function Hook () { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4') + collectionHookDeprecationMessageDisplayed = true + } + return HookCollection() +} + +Hook.Singular = HookSingular.bind() +Hook.Collection = HookCollection.bind() + +module.exports = Hook +// expose constructors as a named property for TypeScript +module.exports.Hook = Hook +module.exports.Singular = Hook.Singular +module.exports.Collection = Hook.Collection + + +/***/ }), + +/***/ 5549: +/***/ ((module) => { + +module.exports = addHook + +function addHook (state, kind, name, hook) { + var orig = hook + if (!state.registry[name]) { + state.registry[name] = [] + } + + if (kind === 'before') { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)) + } + } + + if (kind === 'after') { + hook = function (method, options) { + var result + return Promise.resolve() + .then(method.bind(null, options)) + .then(function (result_) { + result = result_ + return orig(result, options) + }) + .then(function () { + return result + }) + } + } + + if (kind === 'error') { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options) + }) + } + } + + state.registry[name].push({ + hook: hook, + orig: orig + }) +} + + +/***/ }), + +/***/ 4670: +/***/ ((module) => { + +module.exports = register + +function register (state, name, method, options) { + if (typeof method !== 'function') { + throw new Error('method for before hook must be a function') + } + + if (!options) { + options = {} + } + + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options) + }, method)() + } + + return Promise.resolve() + .then(function () { + if (!state.registry[name]) { + return method(options) + } + + return (state.registry[name]).reduce(function (method, registered) { + return registered.hook.bind(null, method, options) + }, method)() + }) +} + + +/***/ }), + +/***/ 6819: +/***/ ((module) => { + +module.exports = removeHook + +function removeHook (state, name, method) { + if (!state.registry[name]) { + return + } + + var index = state.registry[name] + .map(function (registered) { return registered.orig }) + .indexOf(method) + + if (index === -1) { + return + } + + state.registry[name].splice(index, 1) +} + + +/***/ }), + +/***/ 336: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var DuplexStream = __webpack_require__(1642).Duplex + , util = __webpack_require__(1669) + , Buffer = __webpack_require__(1867).Buffer + +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) +} + + +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 + } +} + +BufferList.prototype._reverseOffset = function (blOffset) { + var bufferId = blOffset[0] + var offset = blOffset[1] + for (var i = 0; i < bufferId; i++) { + offset += this._bufs[i].length + } + return offset +} + +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(Buffer.from(buf)) + } + + 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 + } +} + + +BufferList.prototype.get = function get (index) { + if (index > this.length || index < 0) { + return undefined + } + var offset = this._offset(index) + return this._bufs[offset[0]][offset[1]] +} + + +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) +} + + +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 || Buffer.alloc(0) + if (srcEnd <= 0) + return dst || Buffer.alloc(0) + + var copy = !!dst + , off = this._offset(srcStart) + , len = srcEnd - srcStart + , bytes = len + , bufoff = (copy && dstStart) || 0 + , start = off[1] + , l + , i + + // 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 + } + + return dst + } + + // 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) + } + + if (!copy) // a slice, we need something to copy in to + dst = Buffer.allocUnsafe(len) + + for (i = off[0]; i < this._bufs.length; i++) { + l = this._bufs[i].length - start + + if (bytes > l) { + this._bufs[i].copy(dst, bufoff, start) + bufoff += l + } else { + this._bufs[i].copy(dst, bufoff, start, start + bytes) + bufoff += l + break + } + + bytes -= l + + if (start) + start = 0 + } + + // safeguard so that we don't return uninitialized memory + if (dst.length > bufoff) return dst.slice(0, bufoff) + + return dst +} + +BufferList.prototype.shallowSlice = function shallowSlice (start, end) { + start = start || 0 + end = typeof end !== 'number' ? this.length : end + + if (start < 0) + start += this.length + if (end < 0) + end += this.length + + if (start === end) { + return new BufferList() + } + 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) +} + +BufferList.prototype.toString = function toString (encoding, start, end) { + return this.slice(start, end).toString(encoding) +} + +BufferList.prototype.consume = function consume (bytes) { + // first, normalize the argument, in accordance with how Buffer does it + bytes = Math.trunc(bytes) + // do nothing if not a positive number + if (Number.isNaN(bytes) || bytes <= 0) return this + + 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 +} + + +BufferList.prototype.duplicate = function duplicate () { + var i = 0 + , copy = new BufferList() + + for (; i < this._bufs.length; i++) + copy.append(this._bufs[i]) + + return copy +} + + +BufferList.prototype.destroy = function destroy () { + this._bufs.length = 0 + this.length = 0 + this.push(null) +} + + +BufferList.prototype.indexOf = function (search, offset, encoding) { + if (encoding === undefined && typeof offset === 'string') { + encoding = offset + offset = undefined + } + if (typeof search === 'function' || Array.isArray(search)) { + throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') + } else if (typeof search === 'number') { + search = Buffer.from([search]) + } else if (typeof search === 'string') { + search = Buffer.from(search, encoding) + } else if (search instanceof BufferList) { + search = search.slice() + } else if (!Buffer.isBuffer(search)) { + search = Buffer.from(search) + } + + offset = Number(offset || 0) + if (isNaN(offset)) { + offset = 0 + } + + if (offset < 0) { + offset = this.length + offset + } + + if (offset < 0) { + offset = 0 + } + + if (search.length === 0) { + return offset > this.length ? this.length : offset + } + + var blOffset = this._offset(offset) + var blIndex = blOffset[0] // index of which internal buffer we're working on + var buffOffset = blOffset[1] // offset of the internal buffer we're working on + + // scan over each buffer + for (blIndex; blIndex < this._bufs.length; blIndex++) { + var buff = this._bufs[blIndex] + while(buffOffset < buff.length) { + var availableWindow = buff.length - buffOffset + if (availableWindow >= search.length) { + var nativeSearchResult = buff.indexOf(search, buffOffset) + if (nativeSearchResult !== -1) { + return this._reverseOffset([blIndex, nativeSearchResult]) + } + buffOffset = buff.length - search.length + 1 // end of native search window + } else { + var revOffset = this._reverseOffset([blIndex, buffOffset]) + if (this._match(revOffset, search)) { + return revOffset + } + buffOffset++ + } + } + buffOffset = 0 + } + return -1 +} + +BufferList.prototype._match = function(offset, search) { + if (this.length - offset < search.length) { + return false + } + for (var searchOffset = 0; searchOffset < search.length ; searchOffset++) { + if(this.get(offset + searchOffset) !== search[searchOffset]){ + return false + } + } + return true +} + + +;(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 + , 'readIntBE' : null + , 'readIntLE' : null + , 'readUIntBE' : null + , 'readUIntLE' : null + } + + for (var m in methods) { + (function (m) { + if (methods[m] === null) { + BufferList.prototype[m] = function (offset, byteLength) { + return this.slice(offset, offset + byteLength)[m](0, byteLength) + } + } + else { + BufferList.prototype[m] = function (offset) { + return this.slice(offset, offset + methods[m])[m](0) + } + } + }(m)) + } +}()) + + +module.exports = BufferList + + +/***/ }), + +/***/ 4044: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var BSON = __webpack_require__(6800), + Binary = __webpack_require__(5497), + Code = __webpack_require__(7113), + DBRef = __webpack_require__(3797), + Decimal128 = __webpack_require__(414), + Double = __webpack_require__(972), + Int32 = __webpack_require__(6142), + Long = __webpack_require__(8522), + Map = __webpack_require__(3639), + MaxKey = __webpack_require__(5846), + MinKey = __webpack_require__(5325), + ObjectId = __webpack_require__(9502), + BSONRegExp = __webpack_require__(4636), + Symbol = __webpack_require__(2259), + Timestamp = __webpack_require__(1031); + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Add BSON types to function creation +BSON.Binary = Binary; +BSON.Code = Code; +BSON.DBRef = DBRef; +BSON.Decimal128 = Decimal128; +BSON.Double = Double; +BSON.Int32 = Int32; +BSON.Long = Long; +BSON.Map = Map; +BSON.MaxKey = MaxKey; +BSON.MinKey = MinKey; +BSON.ObjectId = ObjectId; +BSON.ObjectID = ObjectId; +BSON.BSONRegExp = BSONRegExp; +BSON.Symbol = Symbol; +BSON.Timestamp = Timestamp; + +// Return the BSON +module.exports = BSON; + + +/***/ }), + +/***/ 5497: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * Module dependencies. + * @ignore + */ + +// Test if we're in Node via presence of "global" not absence of "window" +// to support hybrid environments like Electron +if (typeof global !== 'undefined') { + var Buffer = __webpack_require__(4293).Buffer; // TODO just use global Buffer +} + +var utils = __webpack_require__(2863); + +/** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ +function Binary(buffer, subType) { + if (!(this instanceof Binary)) return new Binary(buffer, subType); + + if ( + buffer != null && + !(typeof buffer === 'string') && + !Buffer.isBuffer(buffer) && + !(buffer instanceof Uint8Array) && + !Array.isArray(buffer) + ) { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + + this._bsontype = 'Binary'; + + if (buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if (buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if (typeof buffer === 'string') { + // Different ways of writing the length of the string for the different types + if (typeof Buffer !== 'undefined') { + this.buffer = utils.toBuffer(buffer); + } else if ( + typeof Uint8Array !== 'undefined' || + Object.prototype.toString.call(buffer) === '[object Array]' + ) { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if (typeof Buffer !== 'undefined') { + this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); + } else if (typeof Uint8Array !== 'undefined') { + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } +} + +/** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ +Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) + throw new Error('only accepts single character String, Uint8Array or Array'); + if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255) + throw new Error('only accepts number in a valid unsigned byte range 0-255'); + + // Decode the byte value once + var decoded_byte = null; + if (typeof byte_value === 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if (byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + buffer = null; + // Create a new buffer (typed or normal array) + if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for (var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } +}; + +/** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ +Binary.prototype.write = function write(string, offset) { + offset = typeof offset === 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = utils.allocBuffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); + // Copy the content + for (var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length + } else if ( + typeof Buffer !== 'undefined' && + typeof string === 'string' && + Buffer.isBuffer(this.buffer) + ) { + this.buffer.write(string, offset, 'binary'); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length; + } else if ( + Object.prototype.toString.call(string) === '[object Uint8Array]' || + (Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') + ) { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if (typeof string === 'string') { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } +}; + +/** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ +Binary.prototype.read = function read(position, length) { + length = length && length > 0 ? length : this.position; + + // Let's return the data based on the type we have + if (this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(length)) + : new Array(length); + for (var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; +}; + +/** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if ( + asRaw && + typeof Buffer !== 'undefined' && + Buffer.isBuffer(this.buffer) && + this.buffer.length === this.position + ) + return this.buffer; + + // If it's a node.js buffer object + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw + ? this.buffer.slice(0, this.position) + : this.buffer.toString('binary', 0, this.position); + } else { + if (asRaw) { + // we support the slice command use it + if (this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = + Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' + ? new Uint8Array(new ArrayBuffer(this.position)) + : new Array(this.position); + // Copy content + for (var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } +}; + +/** + * Length. + * + * @method + * @return {number} the length of the binary. + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +}; + +/** + * @ignore + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +}; + +/** + * Binary default subtype + * @ignore + */ +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + */ +var writeStringToArray = function(data) { + // Create a buffer + var buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(data.length)) + : new Array(data.length); + // Write the content to the buffer + for (var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; +}; + +/** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ''; + for (var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +Binary.BUFFER_SIZE = 256; + +/** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_DEFAULT = 0; +/** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_FUNCTION = 1; +/** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_BYTE_ARRAY = 2; +/** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID_OLD = 3; +/** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID = 4; +/** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_MD5 = 5; +/** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_USER_DEFINED = 128; + +/** + * Expose. + */ +module.exports = Binary; +module.exports.Binary = Binary; + + +/***/ }), + +/***/ 6800: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var Map = __webpack_require__(3639), + Long = __webpack_require__(8522), + Double = __webpack_require__(972), + Timestamp = __webpack_require__(1031), + ObjectID = __webpack_require__(9502), + BSONRegExp = __webpack_require__(4636), + Symbol = __webpack_require__(2259), + Int32 = __webpack_require__(6142), + Code = __webpack_require__(7113), + Decimal128 = __webpack_require__(414), + MinKey = __webpack_require__(5325), + MaxKey = __webpack_require__(5846), + DBRef = __webpack_require__(3797), + Binary = __webpack_require__(5497); + +// Parts of the parser +var deserialize = __webpack_require__(2139), + serializer = __webpack_require__(9290), + calculateObjectSize = __webpack_require__(1273), + utils = __webpack_require__(2863); + +/** + * @ignore + * @api private + */ +// Default Max Size +var MAXSIZE = 1024 * 1024 * 17; + +// Current Internal Temporary Serialization Buffer +var buffer = utils.allocBuffer(MAXSIZE); + +var BSON = function() {}; + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function serialize(object, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = + typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = utils.allocBuffer(minInternalBufferSize); + } + + // Attempt to serialize + var serializationIndex = serializer( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + [] + ); + // Create the final buffer + var finishedBuffer = utils.allocBuffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +}; + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + + // Attempt to serialize + var serializationIndex = serializer( + finalBuffer, + object, + checkKeys, + startIndex || 0, + 0, + serializeFunctions, + ignoreUndefined + ); + + // Return the index + return serializationIndex - 1; +}; + +/** + * Deserialize data as BSON. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(buffer, options) { + return deserialize(buffer, options); +}; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, options) { + options = options || {}; + + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); +}; + +/** + * Deserialize stream data as BSON documents. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function( + data, + startIndex, + numberOfDocuments, + documents, + docStartIndex, + options +) { + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = + data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24); + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +}; + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// Return BSON +module.exports = BSON; +module.exports.Code = Code; +module.exports.Map = Map; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.Int32 = Int32; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.BSONRegExp = BSONRegExp; +module.exports.Decimal128 = Decimal128; + + +/***/ }), + +/***/ 7113: +/***/ ((module) => { + +/** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +var Code = function Code(code, scope) { + if (!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope; +}; + +/** + * @ignore + */ +Code.prototype.toJSON = function() { + return { scope: this.scope, code: this.code }; +}; + +module.exports = Code; +module.exports.Code = Code; + + +/***/ }), + +/***/ 3797: +/***/ ((module) => { + +/** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ +function DBRef(namespace, oid, db) { + if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; +} + +/** + * @ignore + * @api private + */ +DBRef.prototype.toJSON = function() { + return { + $ref: this.namespace, + $id: this.oid, + $db: this.db == null ? '' : this.db + }; +}; + +module.exports = DBRef; +module.exports.DBRef = DBRef; + + +/***/ }), + +/***/ 414: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var Long = __webpack_require__(8522); + +var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + +var EXPONENT_MAX = 6111; +var EXPONENT_MIN = -6176; +var EXPONENT_BIAS = 6176; +var MAX_DIGITS = 34; + +// Nan value bits as 32 bit values (due to lack of longs) +var NAN_BUFFER = [ + 0x7c, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); +// Infinity value bits 32 bit values (due to lack of longs) +var INF_NEGATIVE_BUFFER = [ + 0xf8, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); +var INF_POSITIVE_BUFFER = [ + 0x78, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); + +var EXPONENT_REGEX = /^([-+])?(\d+)?$/; + +var utils = __webpack_require__(2863); + +// Detect if the value is a digit +var isDigit = function(value) { + return !isNaN(parseInt(value, 10)); +}; + +// Divide two uint128 values +var divideu128 = function(value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + var i = 0; + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low_; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; +}; + +// Multiply two Long values and return the 128 bit value +var multiply64x2 = function(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; +}; + +var lessThan = function(left, right) { + // Make values unsigned + var uhleft = left.high_ >>> 0; + var uhright = right.high_ >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + var ulleft = left.low_ >>> 0; + var ulright = right.low_ >>> 0; + if (ulleft < ulright) return true; + } + + return false; +}; + +// var longtoHex = function(value) { +// var buffer = utils.allocBuffer(8); +// var index = 0; +// // Encode the low 64 bits of the decimal +// // Encode low bits +// buffer[index++] = value.low_ & 0xff; +// buffer[index++] = (value.low_ >> 8) & 0xff; +// buffer[index++] = (value.low_ >> 16) & 0xff; +// buffer[index++] = (value.low_ >> 24) & 0xff; +// // Encode high bits +// buffer[index++] = value.high_ & 0xff; +// buffer[index++] = (value.high_ >> 8) & 0xff; +// buffer[index++] = (value.high_ >> 16) & 0xff; +// buffer[index++] = (value.high_ >> 24) & 0xff; +// return buffer.reverse().toString('hex'); +// }; + +// var int32toHex = function(value) { +// var buffer = utils.allocBuffer(4); +// var index = 0; +// // Encode the low 64 bits of the decimal +// // Encode low bits +// buffer[index++] = value & 0xff; +// buffer[index++] = (value >> 8) & 0xff; +// buffer[index++] = (value >> 16) & 0xff; +// buffer[index++] = (value >> 24) & 0xff; +// return buffer.reverse().toString('hex'); +// }; + +/** + * A class representation of the BSON Decimal128 type. + * + * @class + * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. + * @return {Double} + */ +var Decimal128 = function(bytes) { + this._bsontype = 'Decimal128'; + this.bytes = bytes; +}; + +/** + * Create a Decimal128 instance from a string representation + * + * @method + * @param {string} string a numeric string representation. + * @return {Decimal128} returns a Decimal128 instance. + */ +Decimal128.fromString = function(string) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = [0, 0]; + // The low 17 digits of the significand + var significandLow = [0, 0]; + // The biased exponent + var biasedExponent = 0; + + // Read index + var index = 0; + + // Trim the string + string = string.trim(); + + // Naively prevent against REDOS attacks. + // TODO [$5f5fbe42fcabad09c1c24197]: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (string.length >= 7000) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Results + var stringMatch = string.match(PARSE_STRING_REGEXP); + var infMatch = string.match(PARSE_INF_REGEXP); + var nanMatch = string.match(PARSE_NAN_REGEXP); + + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Check if we have an illegal exponent format + if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Get the negative or positive sign + if (string[index] === '+' || string[index] === '-') { + isNegative = string[index++] === '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(string[index]) && string[index] !== '.') { + if (string[index] === 'i' || string[index] === 'I') { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if (string[index] === 'N') { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + } + + // Read all the digits + while (isDigit(string[index]) || string[index] === '.') { + if (string[index] === '.') { + if (sawRadix) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < 34) { + if (string[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(string[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) { + nDigits = nDigits + 1; + } + + if (sawRadix) { + radixPosition = radixPosition + 1; + } + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Read exponent if exists + if (string[index] === 'e' || string[index] === 'E') { + // Read exponent digits + var match = string.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (string[index]) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + + if (exponent !== 0 && significantDigits !== 1) { + while (string[firstNonZero + significantDigits - 1] === '0') { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + + exponent = exponent - 1; + } + + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit + if (lastDigit === 0) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { + var endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix && exponent === EXPONENT_MIN) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1; + + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(string[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + var dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128( + utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) + ); + } + } + } else { + break; + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit - firstDigit < 17) { + dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if ( + significand.high + .shiftRightUnsigned(49) + .and(Long.fromNumber(1)) + .equals(Long.fromNumber) + ) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or( + Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) + ); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + var buffer = utils.allocBuffer(16); + index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low_ & 0xff; + buffer[index++] = (dec.low.low_ >> 8) & 0xff; + buffer[index++] = (dec.low.low_ >> 16) & 0xff; + buffer[index++] = (dec.low.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high_ & 0xff; + buffer[index++] = (dec.low.high_ >> 8) & 0xff; + buffer[index++] = (dec.low.high_ >> 16) & 0xff; + buffer[index++] = (dec.low.high_ >> 24) & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low_ & 0xff; + buffer[index++] = (dec.high.low_ >> 8) & 0xff; + buffer[index++] = (dec.high.low_ >> 16) & 0xff; + buffer[index++] = (dec.high.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high_ & 0xff; + buffer[index++] = (dec.high.high_ >> 8) & 0xff; + buffer[index++] = (dec.high.high_ >> 16) & 0xff; + buffer[index++] = (dec.high.high_ >> 24) & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); +}; + +// Extract least significant 5 bits +var COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +var EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +var COMBINATION_INFINITY = 30; +// Value of combination field for NaN +var COMBINATION_NAN = 31; +// Value of combination field for NaN +// var COMBINATION_SNAN = 32; +// decimal128 exponent bias +EXPONENT_BIAS = 6176; + +/** + * Create a string representation of the raw Decimal128 value + * + * @method + * @return {string} returns a Decimal128 string representation. + */ +Decimal128.prototype.toString = function() { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // bits 0 - 31 + var high; + // bits 32 - 63 + var midh; + // bits 64 - 95 + var midl; + // bits 96 - 127 + var low; + // bits 1 - 5 + var combination; + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + var index = 0; + + // unbiased exponent + var exponent; + // the exponent if scientific notation is used + var scientific_exponent; + + // true if the number is zero + var is_zero = false; + + // the most signifcant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: new Array(4) }; + // indexing variables + i; + var j, k; + + // Output string + var string = []; + + // Unpack index + index = 0; + + // Buffer reference + var buffer = this.bytes; + + // Unpack the low 64bits into a long + low = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + midl = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack the high 64bits into a long + midh = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + high = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack index + index = 0; + + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + combination = (high >> 26) & COMBINATION_MASK; + + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } else if (combination === COMBINATION_NAN) { + return 'NaN'; + } else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + + exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if ( + significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0 + ) { + is_zero = true; + } else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Peform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low_; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + i = 0; + + while (!significand[index]) { + i++; + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + string.push(significand[index++]); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } else { + string.push(scientific_exponent); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + } else { + var radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (i = 0; i < radix_position; i++) { + string.push(significand[index++]); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(significand[index++]); + } + } + } + + return string.join(''); +}; + +Decimal128.prototype.toJSON = function() { + return { $numberDecimal: this.toString() }; +}; + +module.exports = Decimal128; +module.exports.Decimal128 = Decimal128; + + +/***/ }), + +/***/ 972: +/***/ ((module) => { + +/** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ +function Double(value) { + if (!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; +} + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Double.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Double; +module.exports.Double = Double; + + +/***/ }), + +/***/ 7281: +/***/ ((__unused_webpack_module, exports) => { + +var __webpack_unused_export__; +// Copyright (c) 2008, Fair Oaks Labs, 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: +// +// * 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 Fair Oaks Labs, Inc. 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 OWNER 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. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White + +var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { + var e, + m, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : nBytes - 1, + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << -nBits) - 1); + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << -nBits) - 1); + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { + var e, + m, + c, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, + i = bBE ? nBytes - 1 : 0, + d = bBE ? -1 : 1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +__webpack_unused_export__ = readIEEE754; +exports.P = writeIEEE754; + + +/***/ }), + +/***/ 6142: +/***/ ((module) => { + +/** + * A class representation of a BSON Int32 type. + * + * @class + * @param {number} value the number we want to represent as an int32. + * @return {Int32} + */ +var Int32 = function(value) { + if (!(this instanceof Int32)) return new Int32(value); + + this._bsontype = 'Int32'; + this.value = value; +}; + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped int32 number. + */ +Int32.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Int32.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Int32; +module.exports.Int32 = Int32; + + +/***/ }), + +/***/ 8522: +/***/ ((module) => { + +// 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. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ +function Long(low, high) { + if (!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +} + +/** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Long.prototype.toJSON = function() { + return this.toString(); +}; + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Long.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Long.prototype.getLowBitsUnsigned = function() { + return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ +Long.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Long.prototype.isZero = function() { + return this.high_ === 0 && this.low_ === 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) === 1; +}; + +/** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ +Long.prototype.equals = function(other) { + return this.high_ === other.high_ && this.low_ === other.low_; +}; + +/** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ +Long.prototype.notEquals = function(other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; +}; + +/** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Long.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ +Long.prototype.negate = function() { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } +}; + +/** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ +Long.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ +Long.prototype.multiply = function(other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate() + .multiply(other) + .negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ +Long.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate() + .div(other) + .negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ +Long.prototype.and = function(other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ +Long.prototype.or = function(other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ +Long.prototype.xor = function(other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ +Long.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); + } else { + return Long.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ +Long.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); + } else { + return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Long.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); + } else if (numBits === 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ +Long.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ +Long.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ +Long.fromString = function(str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + +/** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ +Long.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + +/** @type {Long} */ +Long.ZERO = Long.fromInt(0); + +/** @type {Long} */ +Long.ONE = Long.fromInt(1); + +/** @type {Long} */ +Long.NEG_ONE = Long.fromInt(-1); + +/** @type {Long} */ +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); + +/** @type {Long} */ +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + +/** + * @type {Long} + * @ignore + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Long; +module.exports.Long = Long; + + +/***/ }), + +/***/ 3639: +/***/ ((module) => { + +"use strict"; + + +// We have an ES6 Map available, return the native instance +if (typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; +} else { + // We will return a polyfill + var Map = function(array) { + this._keys = []; + this._values = {}; + + for (var i = 0; i < array.length; i++) { + if (array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + }; + + Map.prototype.clear = function() { + this._keys = []; + this._values = {}; + }; + + Map.prototype.delete = function(key) { + var value = this._values[key]; + if (value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + + Map.prototype.entries = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.forEach = function(callback, self) { + self = self || this; + + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + + Map.prototype.get = function(key) { + return this._values[key] ? this._values[key].v : undefined; + }; + + Map.prototype.has = function(key) { + return this._values[key] != null; + }; + + Map.prototype.keys = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.set = function(key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + + Map.prototype.values = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable: true, + get: function() { + return this._keys.length; + } + }); + + module.exports = Map; + module.exports.Map = Map; +} + + +/***/ }), + +/***/ 5846: +/***/ ((module) => { + +/** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ +function MaxKey() { + if (!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +module.exports = MaxKey; +module.exports.MaxKey = MaxKey; + + +/***/ }), + +/***/ 5325: +/***/ ((module) => { + +/** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ +function MinKey() { + if (!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +module.exports = MinKey; +module.exports.MinKey = MinKey; + + +/***/ }), + +/***/ 9502: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// Custom inspect property name / symbol. +var inspect = 'inspect'; + +var utils = __webpack_require__(2863); + +/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ +var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + +// Check if buffer exists +try { + if (Buffer && Buffer.from) { + var hasBufferType = true; + inspect = __webpack_require__(1669).inspect.custom || 'inspect'; + } +} catch (err) { + hasBufferType = false; +} + +/** +* Create a new ObjectID instance +* +* @class +* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @property {number} generationTime The generation time of this ObjectId instance +* @return {ObjectID} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id) { + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectID) return id; + if (!(this instanceof ObjectID)) return new ObjectID(id); + + this._bsontype = 'ObjectID'; + + // The most common usecase (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this.id = this.generate(id); + // If we are caching the hex string + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + // Return the object + return; + } + + // Check if the passed in id is valid + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if (!valid && id != null) { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { + return new ObjectID(utils.toBuffer(id, 'hex')); + } else if (valid && typeof id === 'string' && id.length === 24) { + return ObjectID.createFromHexString(id); + } else if (id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if (id != null && typeof id.toHexString === 'function') { + // Duck-typing to support ObjectId from different npm packages + return id; + } else { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } + + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); +}; + +// Allow usage of ObjectId as well as ObjectID +// var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @method +* @return {string} return the 24 byte hex string representation. +*/ +ObjectID.prototype.toHexString = function() { + if (ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + if (!this.id || !this.id.length) { + throw new Error( + 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + + JSON.stringify(this.id) + + ']' + ); + } + + if (this.id instanceof _Buffer) { + hexString = convertToHex(this.id); + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + } + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.get_inc = function() { + return (ObjectID.index = (ObjectID.index + 1) % 0xffffff); +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id buffer used in ObjectID's +* +* @method +* @param {number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {Buffer} return the 12 byte id buffer string. +*/ +ObjectID.prototype.generate = function(time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + + // Use pid + var pid = + (typeof process === 'undefined' || process.pid === 1 + ? Math.floor(Math.random() * 100000) + : process.pid) % 0xffff; + var inc = this.get_inc(); + // Buffer used + var buffer = utils.allocBuffer(12); + // Encode time + buffer[3] = time & 0xff; + buffer[2] = (time >> 8) & 0xff; + buffer[1] = (time >> 16) & 0xff; + buffer[0] = (time >> 24) & 0xff; + // Encode machine + buffer[6] = MACHINE_ID & 0xff; + buffer[5] = (MACHINE_ID >> 8) & 0xff; + buffer[4] = (MACHINE_ID >> 16) & 0xff; + // Encode pid + buffer[8] = pid & 0xff; + buffer[7] = (pid >> 8) & 0xff; + // Encode index + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + // Return the buffer + return buffer; +}; + +/** +* Converts the id into a 24 byte hex string for printing +* +* @param {String} format The Buffer toString format parameter. +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toString = function(format) { + // Is the id a buffer then use the buffer toString method to return the format + if (this.id && this.id.copy) { + return this.id.toString(typeof format === 'string' ? format : 'hex'); + } + + // if(this.buffer ) + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype[inspect] = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @method +* @param {object} otherID ObjectID instance to compare against. +* @return {boolean} the result of comparing two ObjectID's +*/ +ObjectID.prototype.equals = function equals(otherId) { + // var id; + + if (otherId instanceof ObjectID) { + return this.toString() === otherId.toString(); + } else if ( + typeof otherId === 'string' && + ObjectID.isValid(otherId) && + otherId.length === 12 && + this.id instanceof _Buffer + ) { + return otherId === this.id.toString('binary'); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { + return otherId === this.id; + } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { + return otherId.toHexString() === this.toHexString(); + } else { + return false; + } +}; + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @method +* @return {date} the generation date +*/ +ObjectID.prototype.getTimestamp = function() { + var timestamp = new Date(); + var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; +}; + +/** +* @ignore +*/ +ObjectID.index = ~~(Math.random() * 0xffffff); + +/** +* @ignore +*/ +ObjectID.createPk = function createPk() { + return new ObjectID(); +}; + +/** +* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. +* +* @method +* @param {number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromTime = function createFromTime(time) { + var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer[3] = time & 0xff; + buffer[2] = (time >> 8) & 0xff; + buffer[1] = (time >> 16) & 0xff; + buffer[0] = (time >> 24) & 0xff; + // Return the new objectId + return new ObjectID(buffer); +}; + +// Lookup tables +//var encodeLookup = '0123456789abcdef'.split(''); +var decodeLookup = []; +i = 0; +while (i < 10) decodeLookup[0x30 + i] = i++; +while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; + +var _Buffer = Buffer; +var convertToHex = function(bytes) { + return bytes.toString('hex'); +}; + +/** +* Creates an ObjectID from a hex string representation of an ObjectID. +* +* @method +* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromHexString = function createFromHexString(string) { + // Throw an error if it's not a valid setup + if (typeof string === 'undefined' || (string != null && string.length !== 24)) { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } + + // Use Buffer.from method if available + if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); + + // Calculate lengths + var array = new _Buffer(12); + var n = 0; + var i = 0; + + while (i < 24) { + array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; + } + + return new ObjectID(array); +}; + +/** +* Checks if a value is a valid bson ObjectId +* +* @method +* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. +*/ +ObjectID.isValid = function isValid(id) { + if (id == null) return false; + + if (typeof id === 'number') { + return true; + } + + if (typeof id === 'string') { + return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); + } + + if (id instanceof ObjectID) { + return true; + } + + if (id instanceof _Buffer) { + return true; + } + + // Duck-Typing detection of ObjectId like objects + if ( + typeof id.toHexString === 'function' && + (id.id instanceof _Buffer || typeof id.id === 'string') + ) { + return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); + } + + return false; +}; + +/** +* @ignore +*/ +Object.defineProperty(ObjectID.prototype, 'generationTime', { + enumerable: true, + get: function() { + return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); + }, + set: function(value) { + // Encode time into first 4 bytes + this.id[3] = value & 0xff; + this.id[2] = (value >> 8) & 0xff; + this.id[1] = (value >> 16) & 0xff; + this.id[0] = (value >> 24) & 0xff; + } +}); + +/** + * Expose. + */ +module.exports = ObjectID; +module.exports.ObjectID = ObjectID; +module.exports.ObjectId = ObjectID; + + +/***/ }), + +/***/ 1273: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var Long = __webpack_require__(8522).Long, + Double = __webpack_require__(972).Double, + Timestamp = __webpack_require__(1031).Timestamp, + ObjectID = __webpack_require__(9502).ObjectID, + Symbol = __webpack_require__(2259).Symbol, + BSONRegExp = __webpack_require__(4636).BSONRegExp, + Code = __webpack_require__(7113).Code, + Decimal128 = __webpack_require__(414), + MinKey = __webpack_require__(5325).MinKey, + MaxKey = __webpack_require__(5846).MaxKey, + DBRef = __webpack_require__(3797).DBRef, + Binary = __webpack_require__(5497).Binary; + +var normalizedFunctionString = __webpack_require__(2863).normalizedFunctionString; + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +}; + +var calculateObjectSize = function calculateObjectSize( + object, + serializeFunctions, + ignoreUndefined +) { + var totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement( + i.toString(), + object[i], + serializeFunctions, + true, + ignoreUndefined + ); + } + } else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; +}; + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if ( + value == null || + value instanceof MinKey || + value instanceof MaxKey || + value['_bsontype'] === 'MinKey' || + value['_bsontype'] === 'MaxKey' + ) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length + ); + } else if ( + value instanceof Long || + value instanceof Double || + value instanceof Timestamp || + value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp' + ) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } else if (value instanceof Code || value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + ); + } + } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + (value.position + 1 + 4 + 1 + 4) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) + ); + } + } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + Buffer.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1 + ); + } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + $ref: value.namespace, + $id: value.oid + }; + + // Add db reference if it exists + if (null != value.db) { + ordered_values['$db'] = value.db; + } + + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) + ); + } else if ( + value instanceof RegExp || + Object.prototype.toString.call(value) === '[object RegExp]' + ) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.pattern, 'utf8') + + 1 + + Buffer.byteLength(value.options, 'utf8') + + 1 + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1 + ); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if ( + value instanceof RegExp || + Object.prototype.toString.call(value) === '[object RegExp]' || + String.call(value) === '[object RegExp]' + ) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else if (serializeFunctions) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + ); + } + } + } + + return 0; +} + +var BSON = {}; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = calculateObjectSize; + + +/***/ }), + +/***/ 2139: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var Long = __webpack_require__(8522).Long, + Double = __webpack_require__(972).Double, + Timestamp = __webpack_require__(1031).Timestamp, + ObjectID = __webpack_require__(9502).ObjectID, + Symbol = __webpack_require__(2259).Symbol, + Code = __webpack_require__(7113).Code, + MinKey = __webpack_require__(5325).MinKey, + MaxKey = __webpack_require__(5846).MaxKey, + Decimal128 = __webpack_require__(414), + Int32 = __webpack_require__(6142), + DBRef = __webpack_require__(3797).DBRef, + BSONRegExp = __webpack_require__(4636).BSONRegExp, + Binary = __webpack_require__(5497).Binary; + +var utils = __webpack_require__(2863); + +var deserialize = function(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + + // Ensure buffer is valid size + if (size < 5 || buffer.length < size || size + index > buffer.length) { + throw new Error('corrupt bson message'); + } + + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +}; + +var deserializeObject = function(buffer, index, options, isArray) { + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = + options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + + if (!cacheFunctionsCrc32) var crc32 = null; + + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Set the start index + var startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); + + // Read the document size + var size = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); + + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + + var done = false; + + // While we have more left data left keep parsing + // while (buffer[index + 1] !== 0) { + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) break; + + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + + index = i + 1; + + if (elementType === BSON.BSON_DATA_STRING) { + var stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_OID) { + var oid = utils.allocBuffer(12); + buffer.copy(oid, 0, index, index + 12); + object[name] = new ObjectID(oid); + index = index + 12; + } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { + object[name] = new Int32( + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) + ); + } else if (elementType === BSON.BSON_DATA_INT) { + object[name] = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { + object[name] = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_DATE) { + var lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === BSON.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); + object[name] = buffer[index++] === 1; + } else if (elementType === BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new Error('bad embedded document length in bson'); + + // We have a raw value + if (raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if (elementType === BSON.BSON_DATA_ARRAY) { + _index = index; + objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + var arrayOptions = options; + + // Stop index + var stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); + if (index !== stopIndex) throw new Error('corrupted array bson'); + } else if (elementType === BSON.BSON_DATA_UNDEFINED) { + object[name] = undefined; + } else if (elementType === BSON.BSON_DATA_NULL) { + object[name] = null; + } else if (elementType === BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + object[name] = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } else { + object[name] = long; + } + } else if (elementType === BSON.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = utils.allocBuffer(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; + } else if (elementType === BSON.BSON_DATA_BINARY) { + var binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var totalBinarySize = binarySize; + var subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new Error('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + if (promoteBuffers && promoteValues) { + object[name] = buffer.slice(index, index + binarySize); + } else { + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + var _buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(binarySize)) + : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if (promoteBuffers && promoteValues) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if (elementType === BSON.BSON_DATA_SYMBOL) { + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { + lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + object[name] = new Timestamp(lowBits, highBits); + } else if (elementType === BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if (elementType === BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if (elementType === BSON.BSON_DATA_CODE) { + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { + var totalSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new Error('code_w_scope total size shorter minimum expected length'); + } + + // Get the code string size + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + + // Javascript function + functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + _index = index; + // Decode the size of the object document + objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is to short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to short, truncating scope'); + } + + // Check if totalSize field is to long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to long, clips outer document'); + } + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } else if (elementType === BSON.BSON_DATA_DBPOINTER) { + // Get the code string size + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + // Namespace + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + var oidBuffer = utils.allocBuffer(12); + buffer.copy(oidBuffer, 0, index, index + 12); + oid = new ObjectID(oidBuffer); + + // Update the index + index = index + 12; + + // Split the namespace + var parts = namespace.split('.'); + var db = parts.shift(); + var collection = parts.join('.'); + // Upgrade to DBRef type + object[name] = new DBRef(collection, oid, db); + } else { + throw new Error( + 'Detected unknown BSON type ' + + elementType.toString(16) + + ' for fieldname "' + + name + + '", are you using the latest BSON parser' + ); + } + } + + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) throw new Error('corrupt array bson'); + throw new Error('corrupt object bson'); + } + + // Check if we have a db ref object + if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; +}; + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if (functionCache[hash] == null) { + eval('value = ' + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +}; + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval('value = ' + functionString); + return value; +}; + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = (BSON.functionCache = {}); + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_DBPOINTER + **/ +BSON.BSON_DATA_DBPOINTER = 12; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ +BSON.BSON_DATA_DECIMAL128 = 19; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = deserialize; + + +/***/ }), + +/***/ 9290: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var writeIEEE754 = __webpack_require__(7281)/* .writeIEEE754 */ .P, + Long = __webpack_require__(8522).Long, + Map = __webpack_require__(3639), + Binary = __webpack_require__(5497).Binary; + +var normalizedFunctionString = __webpack_require__(2863).normalizedFunctionString; + +// try { +// var _Buffer = Uint8Array; +// } catch (e) { +// _Buffer = Buffer; +// } + +var regexp = /\x00/; // eslint-disable-line no-control-regex +var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +}; + +var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +}; + +var serializeString = function(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +}; + +var serializeNumber = function(buffer, key, value, index, isArray) { + // We have an integer value + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; +}; + +var serializeNull = function(buffer, key, value, index, isArray) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +}; + +var serializeBoolean = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +}; + +var serializeDate = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +}; + +var serializeRegExp = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.global) buffer[index++] = 0x73; // s + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +}; + +var serializeBSONRegExp = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = + index + + buffer.write( + value.options + .split('') + .sort() + .join(''), + index, + 'utf8' + ); + // Add ending zero + buffer[index++] = 0x00; + return index; +}; + +var serializeMinMax = function(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +}; + +var serializeObjectId = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, 'binary'); + } else if (value.id && value.id.copy) { + value.id.copy(buffer, index, 0, 12); + } else { + throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Ajust index + return index + 12; +}; + +var serializeBuffer = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; +}; + +var serializeObject = function( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + isArray, + path +) { + for (var i = 0; i < path.length; i++) { + if (path[i] === value) throw new Error('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto( + buffer, + value, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined, + path + ); + // Pop stack + path.pop(); + // Write size + return endIndex; +}; + +var serializeDecimal128 = function(buffer, key, value, index, isArray) { + buffer[index++] = BSON.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + value.bytes.copy(buffer, index, 0, 16); + return index + 16; +}; + +var serializeLong = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +}; + +var serializeInt32 = function(buffer, key, value, index, isArray) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; +}; + +var serializeDouble = function(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; +}; + +var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +}; + +var serializeCode = function( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + isArray +) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto( + buffer, + value.scope, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined + ); + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +}; + +var serializeBinary = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; +}; + +var serializeSymbol = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +}; + +var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if (null != value.db) { + endIndex = serializeInto( + buffer, + { + $ref: value.namespace, + $id: value.oid, + $db: value.db + }, + false, + index, + depth + 1, + serializeFunctions + ); + } else { + endIndex = serializeInto( + buffer, + { + $ref: value.namespace, + $id: value.oid + }, + false, + index, + depth + 1, + serializeFunctions + ); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +}; + +var serializeInto = function serializeInto( + buffer, + object, + checkKeys, + startingIndex, + depth, + serializeFunctions, + ignoreUndefined, + path +) { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + var index = startingIndex + 4; + // var self = this; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + var type = typeof value; + if (type === 'string') { + index = serializeString(buffer, key, value, index, true); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index, true); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + true + ); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true + ); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } else if (typeof value['_bsontype'] !== 'undefined') { + throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } else if (object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + key = entry.value[0]; + value = entry.value[1]; + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + // } else if (value === undefined && ignoreUndefined === true) { + } else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } else if (typeof value['_bsontype'] !== 'undefined') { + throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') + throw new Error('toBSON function did not return an object'); + } + + // Iterate over all the keys + for (key in object) { + value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } else if (typeof value['_bsontype'] !== 'undefined') { + throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +}; + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +// var functionCache = (BSON.functionCache = {}); + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type, deprecated + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ +BSON.BSON_DATA_DECIMAL128 = 19; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = serializeInto; + + +/***/ }), + +/***/ 2863: +/***/ ((module) => { + +"use strict"; + + +/** + * Normalizes our expected stringified form of a function across versions of node + * @param {Function} fn The function to stringify + */ +function normalizedFunctionString(fn) { + return fn.toString().replace(/function *\(/, 'function ('); +} + +function newBuffer(item, encoding) { + return new Buffer(item, encoding); +} + +function allocBuffer() { + return Buffer.alloc.apply(Buffer, arguments); +} + +function toBuffer() { + return Buffer.from.apply(Buffer, arguments); +} + +module.exports = { + normalizedFunctionString: normalizedFunctionString, + allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, + toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer +}; + + + +/***/ }), + +/***/ 4636: +/***/ ((module) => { + +/** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ +function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern || ''; + this.options = options || ''; + + // Validate options + for (var i = 0; i < this.options.length; i++) { + if ( + !( + this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u' + ) + ) { + throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); + } + } +} + +module.exports = BSONRegExp; +module.exports.BSONRegExp = BSONRegExp; + + +/***/ }), + +/***/ 2259: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// Custom inspect property name / symbol. +var inspect = Buffer ? __webpack_require__(1669).inspect.custom || 'inspect' : 'inspect'; + +/** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ +function Symbol(value) { + if (!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; +} + +/** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toString = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype[inspect] = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Symbol; +module.exports.Symbol = Symbol; + + +/***/ }), + +/***/ 1031: +/***/ ((module) => { + +// 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. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ +function Timestamp(low, high) { + if (!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +} + +/** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +}; + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Timestamp.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Timestamp.prototype.getLowBitsUnsigned = function() { + return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ +Timestamp.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Timestamp.prototype.isZero = function() { + return this.high_ === 0 && this.low_ === 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) === 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ +Timestamp.prototype.equals = function(other) { + return this.high_ === other.high_ && this.low_ === other.low_; +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ +Timestamp.prototype.notEquals = function(other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Timestamp.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ +Timestamp.prototype.negate = function() { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } +}; + +/** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ +Timestamp.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ +Timestamp.prototype.multiply = function(other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate() + .multiply(other) + .negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ +Timestamp.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate() + .div(other) + .negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ +Timestamp.prototype.and = function(other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ +Timestamp.prototype.or = function(other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ +Timestamp.prototype.xor = function(other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ +Timestamp.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); + } else { + return Timestamp.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ +Timestamp.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); + } else { + return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Timestamp.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); + } else if (numBits === 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp( + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0 + ); + } +}; + +/** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromString = function(str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + +/** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ +Timestamp.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + +/** @type {Timestamp} */ +Timestamp.ZERO = Timestamp.fromInt(0); + +/** @type {Timestamp} */ +Timestamp.ONE = Timestamp.fromInt(1); + +/** @type {Timestamp} */ +Timestamp.NEG_ONE = Timestamp.fromInt(-1); + +/** @type {Timestamp} */ +Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); + +/** @type {Timestamp} */ +Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + +/** + * @type {Timestamp} + * @ignore + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Timestamp; +module.exports.Timestamp = Timestamp; + + +/***/ }), + +/***/ 1362: +/***/ ((module) => { + +"use strict"; + + +const preserveCamelCase = string => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + + for (let i = 0; i < string.length; i++) { + const character = string[i]; + + if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) { + string = string.slice(0, i) + '-' + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) { + string = string.slice(0, i - 1) + '-' + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character; + } + } + + return string; +}; + +const camelCase = (input, options) => { + if (!(typeof input === 'string' || Array.isArray(input))) { + throw new TypeError('Expected the input to be `string | string[]`'); + } + + options = Object.assign({ + pascalCase: false + }, options); + + const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x; + + if (Array.isArray(input)) { + input = input.map(x => x.trim()) + .filter(x => x.length) + .join('-'); + } else { + input = input.trim(); + } + + if (input.length === 0) { + return ''; + } + + if (input.length === 1) { + return options.pascalCase ? input.toUpperCase() : input.toLowerCase(); + } + + const hasUpperCase = input !== input.toLowerCase(); + + if (hasUpperCase) { + input = preserveCamelCase(input); + } + + input = input + .replace(/^[_.\- ]+/, '') + .toLowerCase() + .replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase()) + .replace(/\d+(\w|$)/g, m => m.toUpperCase()); + + return postProcess(input); +}; + +module.exports = camelCase; +// TODO [$5f5fbe42fcabad09c1c24198]: Remove this for the next major release +module.exports.default = camelCase; + + +/***/ }), + +/***/ 5898: +/***/ ((__unused_webpack_module, exports) => { + +// 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()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +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'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +/***/ }), + +/***/ 1512: +/***/ (function(module) { + +/* + * Date Format 1.2.3 + * (c) 2007-2009 Steven Levithan + * MIT license + * + * Includes enhancements by Scott Trenda + * and Kris Kowal + * + * Accepts a date, a mask, or a date and a mask. + * Returns a formatted version of the given date. + * The date defaults to the current date/time. + * The mask defaults to dateFormat.masks.default. + */ + +(function(global) { + 'use strict'; + + var dateFormat = (function() { + var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZWN]|"[^"]*"|'[^']*'/g; + var timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g; + var timezoneClip = /[^-+\dA-Z]/g; + + // Regexes and supporting functions are cached through closure + return function (date, mask, utc, gmt) { + + // You can't provide utc if you skip other args (use the 'UTC:' mask prefix) + if (arguments.length === 1 && kindOf(date) === 'string' && !/\d/.test(date)) { + mask = date; + date = undefined; + } + + date = date || new Date; + + if(!(date instanceof Date)) { + date = new Date(date); + } + + if (isNaN(date)) { + throw TypeError('Invalid date'); + } + + mask = String(dateFormat.masks[mask] || mask || dateFormat.masks['default']); + + // Allow setting the utc/gmt argument via the mask + var maskSlice = mask.slice(0, 4); + if (maskSlice === 'UTC:' || maskSlice === 'GMT:') { + mask = mask.slice(4); + utc = true; + if (maskSlice === 'GMT:') { + gmt = true; + } + } + + var _ = utc ? 'getUTC' : 'get'; + var d = date[_ + 'Date'](); + var D = date[_ + 'Day'](); + var m = date[_ + 'Month'](); + var y = date[_ + 'FullYear'](); + var H = date[_ + 'Hours'](); + var M = date[_ + 'Minutes'](); + var s = date[_ + 'Seconds'](); + var L = date[_ + 'Milliseconds'](); + var o = utc ? 0 : date.getTimezoneOffset(); + var W = getWeek(date); + var N = getDayOfWeek(date); + var flags = { + d: d, + dd: pad(d), + ddd: dateFormat.i18n.dayNames[D], + dddd: dateFormat.i18n.dayNames[D + 7], + m: m + 1, + mm: pad(m + 1), + mmm: dateFormat.i18n.monthNames[m], + mmmm: dateFormat.i18n.monthNames[m + 12], + yy: String(y).slice(2), + yyyy: y, + h: H % 12 || 12, + hh: pad(H % 12 || 12), + H: H, + HH: pad(H), + M: M, + MM: pad(M), + s: s, + ss: pad(s), + l: pad(L, 3), + L: pad(Math.round(L / 10)), + t: H < 12 ? dateFormat.i18n.timeNames[0] : dateFormat.i18n.timeNames[1], + tt: H < 12 ? dateFormat.i18n.timeNames[2] : dateFormat.i18n.timeNames[3], + T: H < 12 ? dateFormat.i18n.timeNames[4] : dateFormat.i18n.timeNames[5], + TT: H < 12 ? dateFormat.i18n.timeNames[6] : dateFormat.i18n.timeNames[7], + Z: gmt ? 'GMT' : utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''), + o: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), + S: ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10], + W: W, + N: N + }; + + return mask.replace(token, function (match) { + if (match in flags) { + return flags[match]; + } + return match.slice(1, match.length - 1); + }); + }; + })(); + + dateFormat.masks = { + 'default': 'ddd mmm dd yyyy HH:MM:ss', + 'shortDate': 'm/d/yy', + 'mediumDate': 'mmm d, yyyy', + 'longDate': 'mmmm d, yyyy', + 'fullDate': 'dddd, mmmm d, yyyy', + 'shortTime': 'h:MM TT', + 'mediumTime': 'h:MM:ss TT', + 'longTime': 'h:MM:ss TT Z', + 'isoDate': 'yyyy-mm-dd', + 'isoTime': 'HH:MM:ss', + 'isoDateTime': 'yyyy-mm-dd\'T\'HH:MM:sso', + 'isoUtcDateTime': 'UTC:yyyy-mm-dd\'T\'HH:MM:ss\'Z\'', + 'expiresHeaderFormat': 'ddd, dd mmm yyyy HH:MM:ss Z' + }; + + // Internationalization strings + dateFormat.i18n = { + dayNames: [ + 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', + 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' + ], + monthNames: [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', + 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' + ], + timeNames: [ + 'a', 'p', 'am', 'pm', 'A', 'P', 'AM', 'PM' + ] + }; + +function pad(val, len) { + val = String(val); + len = len || 2; + while (val.length < len) { + val = '0' + val; + } + return val; +} + +/** + * Get the ISO 8601 week number + * Based on comments from + * http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html + * + * @param {Object} `date` + * @return {Number} + */ +function getWeek(date) { + // Remove time components of date + var targetThursday = new Date(date.getFullYear(), date.getMonth(), date.getDate()); + + // Change date to Thursday same week + targetThursday.setDate(targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3); + + // Take January 4th as it is always in week 1 (see ISO 8601) + var firstThursday = new Date(targetThursday.getFullYear(), 0, 4); + + // Change date to Thursday same week + firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3); + + // Check if daylight-saving-time-switch occurred and correct for it + var ds = targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset(); + targetThursday.setHours(targetThursday.getHours() - ds); + + // Number of weeks between target Thursday and first Thursday + var weekDiff = (targetThursday - firstThursday) / (86400000*7); + return 1 + Math.floor(weekDiff); +} + +/** + * Get ISO-8601 numeric representation of the day of the week + * 1 (for Monday) through 7 (for Sunday) + * + * @param {Object} `date` + * @return {Number} + */ +function getDayOfWeek(date) { + var dow = date.getDay(); + if(dow === 0) { + dow = 7; + } + return dow; +} + +/** + * kind-of shortcut + * @param {*} val + * @return {String} + */ +function kindOf(val) { + if (val === null) { + return 'null'; + } + + if (val === undefined) { + return 'undefined'; + } + + if (typeof val !== 'object') { + return typeof val; + } + + if (Array.isArray(val)) { + return 'array'; + } + + return {}.toString.call(val) + .slice(8, -1).toLowerCase(); +}; + + + + if (typeof define === 'function' && define.amd) { + define(function () { + return dateFormat; + }); + } else if (true) { + module.exports = dateFormat; + } else {} +})(this); + + +/***/ }), + +/***/ 159: +/***/ ((module) => { + +"use strict"; + +module.exports = function (str, sep) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + sep = typeof sep === 'undefined' ? '_' : sep; + + return str + .replace(/([a-z\d])([A-Z])/g, '$1' + sep + '$2') + .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + sep + '$2') + .toLowerCase(); +}; + + +/***/ }), + +/***/ 2342: +/***/ ((module) => { + +"use strict"; + + +/** + * Custom implementation of a double ended queue. + */ +function Denque(array) { + this._head = 0; + this._tail = 0; + this._capacityMask = 0x3; + this._list = new Array(4); + if (Array.isArray(array)) { + this._fromArray(array); + } +} + +/** + * ------------- + * PUBLIC API + * ------------- + */ + +/** + * Returns the item at the specified index from the list. + * 0 is the first element, 1 is the second, and so on... + * Elements at negative values are that many from the end: -1 is one before the end + * (the last element), -2 is two before the end (one before last), etc. + * @param index + * @returns {*} + */ +Denque.prototype.peekAt = function peekAt(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var len = this.size(); + if (i >= len || i < -len) return undefined; + if (i < 0) i += len; + i = (this._head + i) & this._capacityMask; + return this._list[i]; +}; + +/** + * Alias for peakAt() + * @param i + * @returns {*} + */ +Denque.prototype.get = function get(i) { + return this.peekAt(i); +}; + +/** + * Returns the first item in the list without removing it. + * @returns {*} + */ +Denque.prototype.peek = function peek() { + if (this._head === this._tail) return undefined; + return this._list[this._head]; +}; + +/** + * Alias for peek() + * @returns {*} + */ +Denque.prototype.peekFront = function peekFront() { + return this.peek(); +}; + +/** + * Returns the item that is at the back of the queue without removing it. + * Uses peekAt(-1) + */ +Denque.prototype.peekBack = function peekBack() { + return this.peekAt(-1); +}; + +/** + * Returns the current length of the queue + * @return {Number} + */ +Object.defineProperty(Denque.prototype, 'length', { + get: function length() { + return this.size(); + } +}); + +/** + * Return the number of items on the list, or 0 if empty. + * @returns {number} + */ +Denque.prototype.size = function size() { + if (this._head === this._tail) return 0; + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + +/** + * Add an item at the beginning of the list. + * @param item + */ +Denque.prototype.unshift = function unshift(item) { + if (item === undefined) return this.size(); + var len = this._list.length; + this._head = (this._head - 1 + len) & this._capacityMask; + this._list[this._head] = item; + if (this._tail === this._head) this._growArray(); + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + +/** + * Remove and return the first item on the list, + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.shift = function shift() { + var head = this._head; + if (head === this._tail) return undefined; + var item = this._list[head]; + this._list[head] = undefined; + this._head = (head + 1) & this._capacityMask; + if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); + return item; +}; + +/** + * Add an item to the bottom of the list. + * @param item + */ +Denque.prototype.push = function push(item) { + if (item === undefined) return this.size(); + var tail = this._tail; + this._list[tail] = item; + this._tail = (tail + 1) & this._capacityMask; + if (this._tail === this._head) { + this._growArray(); + } + + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + +/** + * Remove and return the last item on the list. + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.pop = function pop() { + var tail = this._tail; + if (tail === this._head) return undefined; + var len = this._list.length; + this._tail = (tail - 1 + len) & this._capacityMask; + var item = this._list[this._tail]; + this._list[this._tail] = undefined; + if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); + return item; +}; + +/** + * Remove and return the item at the specified index from the list. + * Returns undefined if the list is empty. + * @param index + * @returns {*} + */ +Denque.prototype.removeOne = function removeOne(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size) return void 0; + if (i < 0) i += size; + i = (this._head + i) & this._capacityMask; + var item = this._list[i]; + var k; + if (index < size / 2) { + for (k = index; k > 0; k--) { + this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._head = (this._head + 1 + len) & this._capacityMask; + } else { + for (k = size - 1 - index; k > 0; k--) { + this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._tail = (this._tail - 1 + len) & this._capacityMask; + } + return item; +}; + +/** + * Remove number of items from the specified index from the list. + * Returns array of removed items. + * Returns undefined if the list is empty. + * @param index + * @param count + * @returns {array} + */ +Denque.prototype.remove = function remove(index, count) { + var i = index; + var removed; + var del_count = count; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size || count < 1) return void 0; + if (i < 0) i += size; + if (count === 1 || !count) { + removed = new Array(1); + removed[0] = this.removeOne(i); + return removed; + } + if (i === 0 && i + count >= size) { + removed = this.toArray(); + this.clear(); + return removed; + } + if (i + count > size) count = size - i; + var k; + removed = new Array(count); + for (k = 0; k < count; k++) { + removed[k] = this._list[(this._head + i + k) & this._capacityMask]; + } + i = (this._head + i) & this._capacityMask; + if (index + count === size) { + this._tail = (this._tail - count + len) & this._capacityMask; + for (k = count; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (index === 0) { + this._head = (this._head + count + len) & this._capacityMask; + for (k = count - 1; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (i < size / 2) { + this._head = (this._head + index + count + len) & this._capacityMask; + for (k = index; k > 0; k--) { + this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); + } + i = (this._head - 1 + len) & this._capacityMask; + while (del_count > 0) { + this._list[i = (i - 1 + len) & this._capacityMask] = void 0; + del_count--; + } + if (index < 0) this._tail = i; + } else { + this._tail = i; + i = (i + count + len) & this._capacityMask; + for (k = size - (count + index); k > 0; k--) { + this.push(this._list[i++]); + } + i = this._tail; + while (del_count > 0) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + del_count--; + } + } + if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); + return removed; +}; + +/** + * Native splice implementation. + * Remove number of items from the specified index from the list and/or add new elements. + * Returns array of removed items or empty array if count == 0. + * Returns undefined if the list is empty. + * + * @param index + * @param count + * @param {...*} [elements] + * @returns {array} + */ +Denque.prototype.splice = function splice(index, count) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var size = this.size(); + if (i < 0) i += size; + if (i > size) return void 0; + if (arguments.length > 2) { + var k; + var temp; + var removed; + var arg_len = arguments.length; + var len = this._list.length; + var arguments_index = 2; + if (!size || i < size / 2) { + temp = new Array(i); + for (k = 0; k < i; k++) { + temp[k] = this._list[(this._head + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i > 0) { + this._head = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._head = (this._head + i + len) & this._capacityMask; + } + while (arg_len > arguments_index) { + this.unshift(arguments[--arg_len]); + } + for (k = i; k > 0; k--) { + this.unshift(temp[k - 1]); + } + } else { + temp = new Array(size - (i + count)); + var leng = temp.length; + for (k = 0; k < leng; k++) { + temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i != size) { + this._tail = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._tail = (this._tail - leng + len) & this._capacityMask; + } + while (arguments_index < arg_len) { + this.push(arguments[arguments_index++]); + } + for (k = 0; k < leng; k++) { + this.push(temp[k]); + } + } + return removed; + } else { + return this.remove(i, count); + } +}; + +/** + * Soft clear - does not reset capacity. + */ +Denque.prototype.clear = function clear() { + this._head = 0; + this._tail = 0; +}; + +/** + * Returns true or false whether the list is empty. + * @returns {boolean} + */ +Denque.prototype.isEmpty = function isEmpty() { + return this._head === this._tail; +}; + +/** + * Returns an array of all queue items. + * @returns {Array} + */ +Denque.prototype.toArray = function toArray() { + return this._copyArray(false); +}; + +/** + * ------------- + * INTERNALS + * ------------- + */ + +/** + * Fills the queue with items from an array + * For use in the constructor + * @param array + * @private + */ +Denque.prototype._fromArray = function _fromArray(array) { + for (var i = 0; i < array.length; i++) this.push(array[i]); +}; + +/** + * + * @param fullCopy + * @returns {Array} + * @private + */ +Denque.prototype._copyArray = function _copyArray(fullCopy) { + var newArray = []; + var list = this._list; + var len = list.length; + var i; + if (fullCopy || this._head > this._tail) { + for (i = this._head; i < len; i++) newArray.push(list[i]); + for (i = 0; i < this._tail; i++) newArray.push(list[i]); + } else { + for (i = this._head; i < this._tail; i++) newArray.push(list[i]); + } + return newArray; +}; + +/** + * Grows the internal list array. + * @private + */ +Denque.prototype._growArray = function _growArray() { + if (this._head) { + // copy existing data, head to end, then beginning to tail. + this._list = this._copyArray(true); + this._head = 0; + } + + // head is at 0 and array is now full, safe to extend + this._tail = this._list.length; + + this._list.length *= 2; + this._capacityMask = (this._capacityMask << 1) | 1; +}; + +/** + * Shrinks the internal list array. + * @private + */ +Denque.prototype._shrinkArray = function _shrinkArray() { + this._list.length >>>= 1; + this._capacityMask >>>= 1; +}; + + +module.exports = Denque; + + +/***/ }), + +/***/ 8932: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'Deprecation'; + } + +} + +exports.Deprecation = Deprecation; + + +/***/ }), + +/***/ 8212: +/***/ ((module) => { + +"use strict"; + + +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4(?:\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74)\uDB40\uDC7F|\u200D\u2620\uFE0F)|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC68(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3]))|\uD83D\uDC69\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\uD83D\uDC68(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83D\uDC69\u200D[\u2695\u2696\u2708])\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC68(?:\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDD1-\uDDDD])/g; +}; + + +/***/ }), + +/***/ 8691: +/***/ ((module) => { + +"use strict"; + + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); +}; + + +/***/ }), + +/***/ 4826: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const validator = __webpack_require__(4174) +const parse = __webpack_require__(6214) +const redactor = __webpack_require__(7333) +const restorer = __webpack_require__(8806) +const { groupRedact, nestedRedact } = __webpack_require__(4865) +const state = __webpack_require__(1012) +const rx = __webpack_require__(9158) +const validate = validator() +const noop = (o) => o +noop.restore = noop + +const DEFAULT_CENSOR = '[REDACTED]' +fastRedact.rx = rx +fastRedact.validator = validator + +module.exports = fastRedact + +function fastRedact (opts = {}) { + const paths = Array.from(new Set(opts.paths || [])) + const serialize = 'serialize' in opts ? ( + opts.serialize === false ? opts.serialize + : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify) + ) : JSON.stringify + const remove = opts.remove + if (remove === true && serialize !== JSON.stringify) { + throw Error('fast-redact – remove option may only be set when serializer is JSON.stringify') + } + const censor = remove === true + ? undefined + : 'censor' in opts ? opts.censor : DEFAULT_CENSOR + + const isCensorFct = typeof censor === 'function' + + if (paths.length === 0) return serialize || noop + + validate({ paths, serialize, censor }) + + const { wildcards, wcLen, secret } = parse({ paths, censor }) + + const compileRestore = restorer({ secret, wcLen }) + const strict = 'strict' in opts ? opts.strict : true + + return redactor({ secret, wcLen, serialize, strict, isCensorFct }, state({ + secret, + censor, + compileRestore, + serialize, + groupRedact, + nestedRedact, + wildcards, + wcLen + })) +} + + +/***/ }), + +/***/ 4865: +/***/ ((module) => { + +"use strict"; + + +module.exports = { + groupRedact, + groupRestore, + nestedRedact, + nestedRestore +} + +function groupRestore ({ keys, values, target }) { + if (target == null) return + const length = keys.length + for (var i = 0; i < length; i++) { + const k = keys[i] + target[k] = values[i] + } +} + +function groupRedact (o, path, censor, isCensorFct) { + const target = get(o, path) + if (target == null) return { keys: null, values: null, target: null, flat: true } + const keys = Object.keys(target) + const length = keys.length + const values = new Array(length) + for (var i = 0; i < length; i++) { + const k = keys[i] + values[i] = target[k] + target[k] = isCensorFct ? censor(target[k]) : censor + } + return { keys, values, target, flat: true } +} + +function nestedRestore (arr) { + const length = arr.length + for (var i = 0; i < length; i++) { + const { key, target, value } = arr[i] + target[key] = value + } +} + +function nestedRedact (store, o, path, ns, censor, isCensorFct) { + const target = get(o, path) + if (target == null) return + const keys = Object.keys(target) + const length = keys.length + for (var i = 0; i < length; i++) { + const key = keys[i] + const { value, parent, exists } = specialSet(target, key, ns, censor, isCensorFct) + + if (exists === true && parent !== null) { + store.push({ key: ns[ns.length - 1], target: parent, value }) + } + } + return store +} + +function has (obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop) +} + +function specialSet (o, k, p, v, f) { + var i = -1 + var l = p.length + var li = l - 1 + var n + var nv + var ov + var oov = null + var exists = true + ov = n = o[k] + if (typeof n !== 'object') return { value: null, parent: null, exists } + while (n != null && ++i < l) { + k = p[i] + oov = ov + if (!(k in n)) { + exists = false + break + } + ov = n[k] + nv = f ? v(ov) : v + nv = (i !== li) ? ov : nv + n[k] = (has(n, k) && nv === ov) || (nv === undefined && v !== undefined) ? n[k] : nv + n = n[k] + if (typeof n !== 'object') break + } + return { value: ov, parent: oov, exists } +} +function get (o, p) { + var i = -1 + var l = p.length + var n = o + while (n != null && ++i < l) { + n = n[p[i]] + } + return n +} + + +/***/ }), + +/***/ 6214: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const rx = __webpack_require__(9158) + +module.exports = parse + +function parse ({ paths }) { + const wildcards = [] + var wcLen = 0 + const secret = paths.reduce(function (o, strPath, ix) { + var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, '')) + const leadingBracket = strPath[0] === '[' + path = path.map((p) => { + if (p[0] === '[') return p.substr(1, p.length - 2) + else return p + }) + const star = path.indexOf('*') + if (star > -1) { + const before = path.slice(0, star) + const beforeStr = before.join('.') + const after = path.slice(star + 1, path.length) + if (after.indexOf('*') > -1) throw Error('fast-redact – Only one wildcard per path is supported') + const nested = after.length > 0 + wcLen++ + wildcards.push({ + before, + beforeStr, + after, + nested + }) + } else { + o[strPath] = { + path: path, + val: undefined, + precensored: false, + circle: '', + escPath: JSON.stringify(strPath), + leadingBracket: leadingBracket + } + } + return o + }, {}) + + return { wildcards, wcLen, secret } +} + + +/***/ }), + +/***/ 7333: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const rx = __webpack_require__(9158) + +module.exports = redactor + +function redactor ({ secret, serialize, wcLen, strict, isCensorFct }, state) { + /* eslint-disable-next-line */ + const redact = Function('o', ` + if (typeof o !== 'object' || o == null) { + ${strictImpl(strict, serialize)} + } + const { censor, secret } = this + ${redactTmpl(secret, isCensorFct)} + this.compileRestore() + ${dynamicRedactTmpl(wcLen > 0, isCensorFct)} + ${resultTmpl(serialize)} + `).bind(state) + + if (serialize === false) { + redact.restore = (o) => state.restore(o) + } + + return redact +} + +function redactTmpl (secret, isCensorFct) { + return Object.keys(secret).map((path) => { + const { escPath, leadingBracket } = secret[path] + const skip = leadingBracket ? 1 : 0 + const delim = leadingBracket ? '' : '.' + const hops = [] + var match + while ((match = rx.exec(path)) !== null) { + const [ , ix ] = match + const { index, input } = match + if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1))) + } + var existence = hops.map((p) => `o${delim}${p}`).join(' && ') + if (existence.length === 0) existence += `o${delim}${path} != null` + else existence += ` && o${delim}${path} != null` + + const circularDetection = ` + switch (true) { + ${hops.reverse().map((p) => ` + case o${delim}${p} === censor: + secret[${escPath}].circle = ${JSON.stringify(p)} + break + `).join('\n')} + } + ` + return ` + if (${existence}) { + const val = o${delim}${path} + if (val === censor) { + secret[${escPath}].precensored = true + } else { + secret[${escPath}].val = val + o${delim}${path} = ${isCensorFct ? 'censor(val)' : 'censor'} + ${circularDetection} + } + } + ` + }).join('\n') +} + +function dynamicRedactTmpl (hasWildcards, isCensorFct) { + return hasWildcards === true ? ` + { + const { wildcards, wcLen, groupRedact, nestedRedact } = this + for (var i = 0; i < wcLen; i++) { + const { before, beforeStr, after, nested } = wildcards[i] + if (nested === true) { + secret[beforeStr] = secret[beforeStr] || [] + nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}) + } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}) + } + } + ` : '' +} + +function resultTmpl (serialize) { + return serialize === false ? `return o` : ` + var s = this.serialize(o) + this.restore(o) + return s + ` +} + +function strictImpl (strict, serialize) { + return strict === true + ? `throw Error('fast-redact: primitives cannot be redacted')` + : serialize === false ? `return o` : `return this.serialize(o)` +} + + +/***/ }), + +/***/ 8806: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const { groupRestore, nestedRestore } = __webpack_require__(4865) + +module.exports = restorer + +function restorer ({ secret, wcLen }) { + return function compileRestore () { + if (this.restore) return + const paths = Object.keys(secret) + .filter((path) => secret[path].precensored === false) + const resetters = resetTmpl(secret, paths) + const hasWildcards = wcLen > 0 + const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret } + /* eslint-disable-next-line */ + this.restore = Function( + 'o', + restoreTmpl(resetters, paths, hasWildcards) + ).bind(state) + } +} + +/** + * Mutates the original object to be censored by restoring its original values + * prior to censoring. + * + * @param {object} secret Compiled object describing which target fields should + * be censored and the field states. + * @param {string[]} paths The list of paths to censor as provided at + * initialization time. + * + * @returns {string} String of JavaScript to be used by `Function()`. The + * string compiles to the function that does the work in the description. + */ +function resetTmpl (secret, paths) { + return paths.map((path) => { + const { circle, escPath, leadingBracket } = secret[path] + const delim = leadingBracket ? '' : '.' + const reset = circle + ? `o.${circle} = secret[${escPath}].val` + : `o${delim}${path} = secret[${escPath}].val` + const clear = `secret[${escPath}].val = undefined` + return ` + if (secret[${escPath}].val !== undefined) { + try { ${reset} } catch (e) {} + ${clear} + } + ` + }).join('') +} + +function restoreTmpl (resetters, paths, hasWildcards) { + const dynamicReset = hasWildcards === true ? ` + const keys = Object.keys(secret) + const len = keys.length + for (var i = ${paths.length}; i < len; i++) { + const k = keys[i] + const o = secret[k] + if (o.flat === true) this.groupRestore(o) + else this.nestedRestore(o) + secret[k] = null + } + ` : '' + + return ` + const secret = this.secret + ${resetters} + ${dynamicReset} + return o + ` +} + + +/***/ }), + +/***/ 9158: +/***/ ((module) => { + +"use strict"; + + +module.exports = /[^.[\]]+|\[((?:.)*?)\]/g + + +/***/ }), + +/***/ 1012: +/***/ ((module) => { + +"use strict"; + + +module.exports = state + +function state (o) { + const { + secret, + censor, + isCensorFct, + compileRestore, + serialize, + groupRedact, + nestedRedact, + wildcards, + wcLen + } = o + const builder = [{ secret, censor, isCensorFct, compileRestore }] + builder.push({ secret }) + if (serialize !== false) builder.push({ serialize }) + if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen }) + return Object.assign(...builder) +} + + +/***/ }), + +/***/ 4174: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const { createContext, runInContext } = __webpack_require__(2184) + +module.exports = validator + +function validator (opts = {}) { + const { + ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be strings', + ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})` + } = opts + + return function validate ({ paths }) { + paths.forEach((s) => { + if (typeof s !== 'string') { + throw Error(ERR_PATHS_MUST_BE_STRINGS()) + } + try { + if (/〇/.test(s)) throw Error() + const proxy = new Proxy({}, { get: () => proxy, set: () => { throw Error() } }) + const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\*/, '〇').replace(/\.\*/g, '.〇').replace(/\[\*\]/g, '[〇]') + if (/\n|\r|;/.test(expr)) throw Error() + if (/\/\*/.test(expr)) throw Error() + runInContext(` + (function () { + 'use strict' + o${expr} + if ([o${expr}].length !== 1) throw Error() + })() + `, createContext({ o: proxy, 〇: null }), { + codeGeneration: { strings: false, wasm: false } + }) + } catch (e) { + throw Error(ERR_INVALID_PATH(s)) + } + }) + } +} + + +/***/ }), + +/***/ 7676: +/***/ ((module) => { + +module.exports = stringify +stringify.default = stringify +stringify.stable = deterministicStringify +stringify.stableStringify = deterministicStringify + +var arr = [] +var replacerStack = [] + +// Regular stringify +function stringify (obj, replacer, spacer) { + decirc(obj, '', [], undefined) + var res + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer) + } else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) + } + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } + return res +} +function decirc (val, k, stack, parent) { + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: '[Circular]' }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k]) + } + } else { + parent[k] = '[Circular]' + arr.push([parent, k, val]) + } + return + } + } + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, stack, val) + } + } else { + var keys = Object.keys(val) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + decirc(val[key], key, stack, val) + } + } + stack.pop() + } +} + +// Stable-stringify +function compareFunction (a, b) { + if (a < b) { + return -1 + } + if (a > b) { + return 1 + } + return 0 +} + +function deterministicStringify (obj, replacer, spacer) { + var tmp = deterministicDecirc(obj, '', [], undefined) || obj + var res + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer) + } else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) + } + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } + return res +} + +function deterministicDecirc (val, k, stack, parent) { + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: '[Circular]' }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k]) + } + } else { + parent[k] = '[Circular]' + arr.push([parent, k, val]) + } + return + } + } + if (typeof val.toJSON === 'function') { + return + } + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, stack, val) + } + } else { + // Create a temporary object in the required way + var tmp = {} + var keys = Object.keys(val).sort(compareFunction) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + deterministicDecirc(val[key], key, stack, val) + tmp[key] = val[key] + } + if (parent !== undefined) { + arr.push([parent, k, val]) + parent[k] = tmp + } else { + return tmp + } + } + stack.pop() + } +} + +// wraps replacer function to handle values we couldn't replace +// and mark them as [Circular] +function replaceGetterValues (replacer) { + replacer = replacer !== undefined ? replacer : function (k, v) { return v } + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i] + if (part[1] === key && part[0] === val) { + val = '[Circular]' + replacerStack.splice(i, 1) + break + } + } + } + return replacer.call(this, key, val) + } +} + + +/***/ }), + +/***/ 5298: +/***/ ((module) => { + +"use strict"; + + +// You may be tempted to copy and paste this, +// but take a look at the commit history first, +// this is a moving target so relying on the module +// is the best way to make sure the optimization +// method is kept up to date and compatible with +// every Node version. + +function flatstr (s) { + s | 0 + return s +} + +module.exports = flatstr + +/***/ }), + +/***/ 351: +/***/ ((module) => { + +"use strict"; + +// Call this function in a another function to find out the file from +// which that function was called from. (Inspects the v8 stack trace) +// +// Inspired by http://stackoverflow.com/questions/13227489 +module.exports = function getCallerFile(position) { + if (position === void 0) { position = 2; } + if (position >= Error.stackTraceLimit) { + throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`'); + } + var oldPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = function (_, stack) { return stack; }; + var stack = new Error().stack; + Error.prepareStackTrace = oldPrepareStackTrace; + if (stack !== null && typeof stack === 'object') { + // stack[0] holds this file + // stack[1] holds where this function was called + // stack[2] holds the file we're interested in + return stack[position] ? stack[position].getFileName() : undefined; + } +}; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 1621: +/***/ ((module) => { + +"use strict"; + +module.exports = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; + + +/***/ }), + +/***/ 4124: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +try { + var util = __webpack_require__(1669); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __webpack_require__(8544); +} + + +/***/ }), + +/***/ 8544: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (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) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 6799: +/***/ ((module) => { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +/** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + +var NODE_ENV = process.env.NODE_ENV; + +var invariant = function(condition, format, a, b, c, d, e, f) { + if (NODE_ENV !== 'production') { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } +}; + +module.exports = invariant; + + +/***/ }), + +/***/ 4882: +/***/ ((module) => { + +"use strict"; + +/* eslint-disable yoda */ +module.exports = x => { + if (Number.isNaN(x)) { + return false; + } + + // code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + x >= 0x1100 && ( + x <= 0x115f || // Hangul Jamo + x === 0x2329 || // LEFT-POINTING ANGLE BRACKET + x === 0x232a || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= x && x <= 0x4dbf) || + // CJK Unified Ideographs .. Yi Radicals + (0x4e00 <= x && x <= 0xa4c6) || + // Hangul Jamo Extended-A + (0xa960 <= x && x <= 0xa97c) || + // Hangul Syllables + (0xac00 <= x && x <= 0xd7a3) || + // CJK Compatibility Ideographs + (0xf900 <= x && x <= 0xfaff) || + // Vertical Forms + (0xfe10 <= x && x <= 0xfe19) || + // CJK Compatibility Forms .. Small Form Variants + (0xfe30 <= x && x <= 0xfe6b) || + // Halfwidth and Fullwidth Forms + (0xff01 <= x && x <= 0xff60) || + (0xffe0 <= x && x <= 0xffe6) || + // Kana Supplement + (0x1b000 <= x && x <= 0x1b001) || + // Enclosed Ideographic Supplement + (0x1f200 <= x && x <= 0x1f251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= x && x <= 0x3fffd) + ) + ) { + return true; + } + + return false; +}; + + +/***/ }), + +/***/ 893: +/***/ ((module) => { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), + +/***/ 7783: +/***/ ((__unused_webpack_module, exports) => { + +(function(exports) { + "use strict"; + + function isArray(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Array]"; + } else { + return false; + } + } + + function isObject(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Object]"; + } else { + return false; + } + } + + function strictDeepEqual(first, second) { + // Check the scalar case first. + if (first === second) { + return true; + } + + // Check if they are the same type. + var firstType = Object.prototype.toString.call(first); + if (firstType !== Object.prototype.toString.call(second)) { + return false; + } + // We know that first and second have the same type so we can just check the + // first type from now on. + if (isArray(first) === true) { + // Short circuit if they're not the same length; + if (first.length !== second.length) { + return false; + } + for (var i = 0; i < first.length; i++) { + if (strictDeepEqual(first[i], second[i]) === false) { + return false; + } + } + return true; + } + if (isObject(first) === true) { + // An object is equal if it has the same key/value pairs. + var keysSeen = {}; + for (var key in first) { + if (hasOwnProperty.call(first, key)) { + if (strictDeepEqual(first[key], second[key]) === false) { + return false; + } + keysSeen[key] = true; + } + } + // Now check that there aren't any keys in second that weren't + // in first. + for (var key2 in second) { + if (hasOwnProperty.call(second, key2)) { + if (keysSeen[key2] !== true) { + return false; + } + } + } + return true; + } + return false; + } + + function isFalse(obj) { + // From the spec: + // A false value corresponds to the following values: + // Empty list + // Empty object + // Empty string + // False boolean + // null value + + // First check the scalar values. + if (obj === "" || obj === false || obj === null) { + return true; + } else if (isArray(obj) && obj.length === 0) { + // Check for an empty array. + return true; + } else if (isObject(obj)) { + // Check for an empty object. + for (var key in obj) { + // If there are any keys, then + // the object is not empty so the object + // is not false. + if (obj.hasOwnProperty(key)) { + return false; + } + } + return true; + } else { + return false; + } + } + + function objValues(obj) { + var keys = Object.keys(obj); + var values = []; + for (var i = 0; i < keys.length; i++) { + values.push(obj[keys[i]]); + } + return values; + } + + function merge(a, b) { + var merged = {}; + for (var key in a) { + merged[key] = a[key]; + } + for (var key2 in b) { + merged[key2] = b[key2]; + } + return merged; + } + + var trimLeft; + if (typeof String.prototype.trimLeft === "function") { + trimLeft = function(str) { + return str.trimLeft(); + }; + } else { + trimLeft = function(str) { + return str.match(/^\s*(.*)/)[1]; + }; + } + + // Type constants used to define functions. + var TYPE_NUMBER = 0; + var TYPE_ANY = 1; + var TYPE_STRING = 2; + var TYPE_ARRAY = 3; + var TYPE_OBJECT = 4; + var TYPE_BOOLEAN = 5; + var TYPE_EXPREF = 6; + var TYPE_NULL = 7; + var TYPE_ARRAY_NUMBER = 8; + var TYPE_ARRAY_STRING = 9; + + var TOK_EOF = "EOF"; + var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier"; + var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier"; + var TOK_RBRACKET = "Rbracket"; + var TOK_RPAREN = "Rparen"; + var TOK_COMMA = "Comma"; + var TOK_COLON = "Colon"; + var TOK_RBRACE = "Rbrace"; + var TOK_NUMBER = "Number"; + var TOK_CURRENT = "Current"; + var TOK_EXPREF = "Expref"; + var TOK_PIPE = "Pipe"; + var TOK_OR = "Or"; + var TOK_AND = "And"; + var TOK_EQ = "EQ"; + var TOK_GT = "GT"; + var TOK_LT = "LT"; + var TOK_GTE = "GTE"; + var TOK_LTE = "LTE"; + var TOK_NE = "NE"; + var TOK_FLATTEN = "Flatten"; + var TOK_STAR = "Star"; + var TOK_FILTER = "Filter"; + var TOK_DOT = "Dot"; + var TOK_NOT = "Not"; + var TOK_LBRACE = "Lbrace"; + var TOK_LBRACKET = "Lbracket"; + var TOK_LPAREN= "Lparen"; + var TOK_LITERAL= "Literal"; + + // The "&", "[", "<", ">" tokens + // are not in basicToken because + // there are two token variants + // ("&&", "[?", "<=", ">="). This is specially handled + // below. + + var basicTokens = { + ".": TOK_DOT, + "*": TOK_STAR, + ",": TOK_COMMA, + ":": TOK_COLON, + "{": TOK_LBRACE, + "}": TOK_RBRACE, + "]": TOK_RBRACKET, + "(": TOK_LPAREN, + ")": TOK_RPAREN, + "@": TOK_CURRENT + }; + + var operatorStartToken = { + "<": true, + ">": true, + "=": true, + "!": true + }; + + var skipChars = { + " ": true, + "\t": true, + "\n": true + }; + + + function isAlpha(ch) { + return (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + ch === "_"; + } + + function isNum(ch) { + return (ch >= "0" && ch <= "9") || + ch === "-"; + } + function isAlphaNum(ch) { + return (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + (ch >= "0" && ch <= "9") || + ch === "_"; + } + + function Lexer() { + } + Lexer.prototype = { + tokenize: function(stream) { + var tokens = []; + this._current = 0; + var start; + var identifier; + var token; + while (this._current < stream.length) { + if (isAlpha(stream[this._current])) { + start = this._current; + identifier = this._consumeUnquotedIdentifier(stream); + tokens.push({type: TOK_UNQUOTEDIDENTIFIER, + value: identifier, + start: start}); + } else if (basicTokens[stream[this._current]] !== undefined) { + tokens.push({type: basicTokens[stream[this._current]], + value: stream[this._current], + start: this._current}); + this._current++; + } else if (isNum(stream[this._current])) { + token = this._consumeNumber(stream); + tokens.push(token); + } else if (stream[this._current] === "[") { + // No need to increment this._current. This happens + // in _consumeLBracket + token = this._consumeLBracket(stream); + tokens.push(token); + } else if (stream[this._current] === "\"") { + start = this._current; + identifier = this._consumeQuotedIdentifier(stream); + tokens.push({type: TOK_QUOTEDIDENTIFIER, + value: identifier, + start: start}); + } else if (stream[this._current] === "'") { + start = this._current; + identifier = this._consumeRawStringLiteral(stream); + tokens.push({type: TOK_LITERAL, + value: identifier, + start: start}); + } else if (stream[this._current] === "`") { + start = this._current; + var literal = this._consumeLiteral(stream); + tokens.push({type: TOK_LITERAL, + value: literal, + start: start}); + } else if (operatorStartToken[stream[this._current]] !== undefined) { + tokens.push(this._consumeOperator(stream)); + } else if (skipChars[stream[this._current]] !== undefined) { + // Ignore whitespace. + this._current++; + } else if (stream[this._current] === "&") { + start = this._current; + this._current++; + if (stream[this._current] === "&") { + this._current++; + tokens.push({type: TOK_AND, value: "&&", start: start}); + } else { + tokens.push({type: TOK_EXPREF, value: "&", start: start}); + } + } else if (stream[this._current] === "|") { + start = this._current; + this._current++; + if (stream[this._current] === "|") { + this._current++; + tokens.push({type: TOK_OR, value: "||", start: start}); + } else { + tokens.push({type: TOK_PIPE, value: "|", start: start}); + } + } else { + var error = new Error("Unknown character:" + stream[this._current]); + error.name = "LexerError"; + throw error; + } + } + return tokens; + }, + + _consumeUnquotedIdentifier: function(stream) { + var start = this._current; + this._current++; + while (this._current < stream.length && isAlphaNum(stream[this._current])) { + this._current++; + } + return stream.slice(start, this._current); + }, + + _consumeQuotedIdentifier: function(stream) { + var start = this._current; + this._current++; + var maxLength = stream.length; + while (stream[this._current] !== "\"" && this._current < maxLength) { + // You can escape a double quote and you can escape an escape. + var current = this._current; + if (stream[current] === "\\" && (stream[current + 1] === "\\" || + stream[current + 1] === "\"")) { + current += 2; + } else { + current++; + } + this._current = current; + } + this._current++; + return JSON.parse(stream.slice(start, this._current)); + }, + + _consumeRawStringLiteral: function(stream) { + var start = this._current; + this._current++; + var maxLength = stream.length; + while (stream[this._current] !== "'" && this._current < maxLength) { + // You can escape a single quote and you can escape an escape. + var current = this._current; + if (stream[current] === "\\" && (stream[current + 1] === "\\" || + stream[current + 1] === "'")) { + current += 2; + } else { + current++; + } + this._current = current; + } + this._current++; + var literal = stream.slice(start + 1, this._current - 1); + return literal.replace("\\'", "'"); + }, + + _consumeNumber: function(stream) { + var start = this._current; + this._current++; + var maxLength = stream.length; + while (isNum(stream[this._current]) && this._current < maxLength) { + this._current++; + } + var value = parseInt(stream.slice(start, this._current)); + return {type: TOK_NUMBER, value: value, start: start}; + }, + + _consumeLBracket: function(stream) { + var start = this._current; + this._current++; + if (stream[this._current] === "?") { + this._current++; + return {type: TOK_FILTER, value: "[?", start: start}; + } else if (stream[this._current] === "]") { + this._current++; + return {type: TOK_FLATTEN, value: "[]", start: start}; + } else { + return {type: TOK_LBRACKET, value: "[", start: start}; + } + }, + + _consumeOperator: function(stream) { + var start = this._current; + var startingChar = stream[start]; + this._current++; + if (startingChar === "!") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_NE, value: "!=", start: start}; + } else { + return {type: TOK_NOT, value: "!", start: start}; + } + } else if (startingChar === "<") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_LTE, value: "<=", start: start}; + } else { + return {type: TOK_LT, value: "<", start: start}; + } + } else if (startingChar === ">") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_GTE, value: ">=", start: start}; + } else { + return {type: TOK_GT, value: ">", start: start}; + } + } else if (startingChar === "=") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_EQ, value: "==", start: start}; + } + } + }, + + _consumeLiteral: function(stream) { + this._current++; + var start = this._current; + var maxLength = stream.length; + var literal; + while(stream[this._current] !== "`" && this._current < maxLength) { + // You can escape a literal char or you can escape the escape. + var current = this._current; + if (stream[current] === "\\" && (stream[current + 1] === "\\" || + stream[current + 1] === "`")) { + current += 2; + } else { + current++; + } + this._current = current; + } + var literalString = trimLeft(stream.slice(start, this._current)); + literalString = literalString.replace("\\`", "`"); + if (this._looksLikeJSON(literalString)) { + literal = JSON.parse(literalString); + } else { + // Try to JSON parse it as "" + literal = JSON.parse("\"" + literalString + "\""); + } + // +1 gets us to the ending "`", +1 to move on to the next char. + this._current++; + return literal; + }, + + _looksLikeJSON: function(literalString) { + var startingChars = "[{\""; + var jsonLiterals = ["true", "false", "null"]; + var numberLooking = "-0123456789"; + + if (literalString === "") { + return false; + } else if (startingChars.indexOf(literalString[0]) >= 0) { + return true; + } else if (jsonLiterals.indexOf(literalString) >= 0) { + return true; + } else if (numberLooking.indexOf(literalString[0]) >= 0) { + try { + JSON.parse(literalString); + return true; + } catch (ex) { + return false; + } + } else { + return false; + } + } + }; + + var bindingPower = {}; + bindingPower[TOK_EOF] = 0; + bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0; + bindingPower[TOK_QUOTEDIDENTIFIER] = 0; + bindingPower[TOK_RBRACKET] = 0; + bindingPower[TOK_RPAREN] = 0; + bindingPower[TOK_COMMA] = 0; + bindingPower[TOK_RBRACE] = 0; + bindingPower[TOK_NUMBER] = 0; + bindingPower[TOK_CURRENT] = 0; + bindingPower[TOK_EXPREF] = 0; + bindingPower[TOK_PIPE] = 1; + bindingPower[TOK_OR] = 2; + bindingPower[TOK_AND] = 3; + bindingPower[TOK_EQ] = 5; + bindingPower[TOK_GT] = 5; + bindingPower[TOK_LT] = 5; + bindingPower[TOK_GTE] = 5; + bindingPower[TOK_LTE] = 5; + bindingPower[TOK_NE] = 5; + bindingPower[TOK_FLATTEN] = 9; + bindingPower[TOK_STAR] = 20; + bindingPower[TOK_FILTER] = 21; + bindingPower[TOK_DOT] = 40; + bindingPower[TOK_NOT] = 45; + bindingPower[TOK_LBRACE] = 50; + bindingPower[TOK_LBRACKET] = 55; + bindingPower[TOK_LPAREN] = 60; + + function Parser() { + } + + Parser.prototype = { + parse: function(expression) { + this._loadTokens(expression); + this.index = 0; + var ast = this.expression(0); + if (this._lookahead(0) !== TOK_EOF) { + var t = this._lookaheadToken(0); + var error = new Error( + "Unexpected token type: " + t.type + ", value: " + t.value); + error.name = "ParserError"; + throw error; + } + return ast; + }, + + _loadTokens: function(expression) { + var lexer = new Lexer(); + var tokens = lexer.tokenize(expression); + tokens.push({type: TOK_EOF, value: "", start: expression.length}); + this.tokens = tokens; + }, + + expression: function(rbp) { + var leftToken = this._lookaheadToken(0); + this._advance(); + var left = this.nud(leftToken); + var currentToken = this._lookahead(0); + while (rbp < bindingPower[currentToken]) { + this._advance(); + left = this.led(currentToken, left); + currentToken = this._lookahead(0); + } + return left; + }, + + _lookahead: function(number) { + return this.tokens[this.index + number].type; + }, + + _lookaheadToken: function(number) { + return this.tokens[this.index + number]; + }, + + _advance: function() { + this.index++; + }, + + nud: function(token) { + var left; + var right; + var expression; + switch (token.type) { + case TOK_LITERAL: + return {type: "Literal", value: token.value}; + case TOK_UNQUOTEDIDENTIFIER: + return {type: "Field", name: token.value}; + case TOK_QUOTEDIDENTIFIER: + var node = {type: "Field", name: token.value}; + if (this._lookahead(0) === TOK_LPAREN) { + throw new Error("Quoted identifier not allowed for function names."); + } else { + return node; + } + break; + case TOK_NOT: + right = this.expression(bindingPower.Not); + return {type: "NotExpression", children: [right]}; + case TOK_STAR: + left = {type: "Identity"}; + right = null; + if (this._lookahead(0) === TOK_RBRACKET) { + // This can happen in a multiselect, + // [a, b, *] + right = {type: "Identity"}; + } else { + right = this._parseProjectionRHS(bindingPower.Star); + } + return {type: "ValueProjection", children: [left, right]}; + case TOK_FILTER: + return this.led(token.type, {type: "Identity"}); + case TOK_LBRACE: + return this._parseMultiselectHash(); + case TOK_FLATTEN: + left = {type: TOK_FLATTEN, children: [{type: "Identity"}]}; + right = this._parseProjectionRHS(bindingPower.Flatten); + return {type: "Projection", children: [left, right]}; + case TOK_LBRACKET: + if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) { + right = this._parseIndexExpression(); + return this._projectIfSlice({type: "Identity"}, right); + } else if (this._lookahead(0) === TOK_STAR && + this._lookahead(1) === TOK_RBRACKET) { + this._advance(); + this._advance(); + right = this._parseProjectionRHS(bindingPower.Star); + return {type: "Projection", + children: [{type: "Identity"}, right]}; + } else { + return this._parseMultiselectList(); + } + break; + case TOK_CURRENT: + return {type: TOK_CURRENT}; + case TOK_EXPREF: + expression = this.expression(bindingPower.Expref); + return {type: "ExpressionReference", children: [expression]}; + case TOK_LPAREN: + var args = []; + while (this._lookahead(0) !== TOK_RPAREN) { + if (this._lookahead(0) === TOK_CURRENT) { + expression = {type: TOK_CURRENT}; + this._advance(); + } else { + expression = this.expression(0); + } + args.push(expression); + } + this._match(TOK_RPAREN); + return args[0]; + default: + this._errorToken(token); + } + }, + + led: function(tokenName, left) { + var right; + switch(tokenName) { + case TOK_DOT: + var rbp = bindingPower.Dot; + if (this._lookahead(0) !== TOK_STAR) { + right = this._parseDotRHS(rbp); + return {type: "Subexpression", children: [left, right]}; + } else { + // Creating a projection. + this._advance(); + right = this._parseProjectionRHS(rbp); + return {type: "ValueProjection", children: [left, right]}; + } + break; + case TOK_PIPE: + right = this.expression(bindingPower.Pipe); + return {type: TOK_PIPE, children: [left, right]}; + case TOK_OR: + right = this.expression(bindingPower.Or); + return {type: "OrExpression", children: [left, right]}; + case TOK_AND: + right = this.expression(bindingPower.And); + return {type: "AndExpression", children: [left, right]}; + case TOK_LPAREN: + var name = left.name; + var args = []; + var expression, node; + while (this._lookahead(0) !== TOK_RPAREN) { + if (this._lookahead(0) === TOK_CURRENT) { + expression = {type: TOK_CURRENT}; + this._advance(); + } else { + expression = this.expression(0); + } + if (this._lookahead(0) === TOK_COMMA) { + this._match(TOK_COMMA); + } + args.push(expression); + } + this._match(TOK_RPAREN); + node = {type: "Function", name: name, children: args}; + return node; + case TOK_FILTER: + var condition = this.expression(0); + this._match(TOK_RBRACKET); + if (this._lookahead(0) === TOK_FLATTEN) { + right = {type: "Identity"}; + } else { + right = this._parseProjectionRHS(bindingPower.Filter); + } + return {type: "FilterProjection", children: [left, right, condition]}; + case TOK_FLATTEN: + var leftNode = {type: TOK_FLATTEN, children: [left]}; + var rightNode = this._parseProjectionRHS(bindingPower.Flatten); + return {type: "Projection", children: [leftNode, rightNode]}; + case TOK_EQ: + case TOK_NE: + case TOK_GT: + case TOK_GTE: + case TOK_LT: + case TOK_LTE: + return this._parseComparator(left, tokenName); + case TOK_LBRACKET: + var token = this._lookaheadToken(0); + if (token.type === TOK_NUMBER || token.type === TOK_COLON) { + right = this._parseIndexExpression(); + return this._projectIfSlice(left, right); + } else { + this._match(TOK_STAR); + this._match(TOK_RBRACKET); + right = this._parseProjectionRHS(bindingPower.Star); + return {type: "Projection", children: [left, right]}; + } + break; + default: + this._errorToken(this._lookaheadToken(0)); + } + }, + + _match: function(tokenType) { + if (this._lookahead(0) === tokenType) { + this._advance(); + } else { + var t = this._lookaheadToken(0); + var error = new Error("Expected " + tokenType + ", got: " + t.type); + error.name = "ParserError"; + throw error; + } + }, + + _errorToken: function(token) { + var error = new Error("Invalid token (" + + token.type + "): \"" + + token.value + "\""); + error.name = "ParserError"; + throw error; + }, + + + _parseIndexExpression: function() { + if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) { + return this._parseSliceExpression(); + } else { + var node = { + type: "Index", + value: this._lookaheadToken(0).value}; + this._advance(); + this._match(TOK_RBRACKET); + return node; + } + }, + + _projectIfSlice: function(left, right) { + var indexExpr = {type: "IndexExpression", children: [left, right]}; + if (right.type === "Slice") { + return { + type: "Projection", + children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)] + }; + } else { + return indexExpr; + } + }, + + _parseSliceExpression: function() { + // [start:end:step] where each part is optional, as well as the last + // colon. + var parts = [null, null, null]; + var index = 0; + var currentToken = this._lookahead(0); + while (currentToken !== TOK_RBRACKET && index < 3) { + if (currentToken === TOK_COLON) { + index++; + this._advance(); + } else if (currentToken === TOK_NUMBER) { + parts[index] = this._lookaheadToken(0).value; + this._advance(); + } else { + var t = this._lookahead(0); + var error = new Error("Syntax error, unexpected token: " + + t.value + "(" + t.type + ")"); + error.name = "Parsererror"; + throw error; + } + currentToken = this._lookahead(0); + } + this._match(TOK_RBRACKET); + return { + type: "Slice", + children: parts + }; + }, + + _parseComparator: function(left, comparator) { + var right = this.expression(bindingPower[comparator]); + return {type: "Comparator", name: comparator, children: [left, right]}; + }, + + _parseDotRHS: function(rbp) { + var lookahead = this._lookahead(0); + var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR]; + if (exprTokens.indexOf(lookahead) >= 0) { + return this.expression(rbp); + } else if (lookahead === TOK_LBRACKET) { + this._match(TOK_LBRACKET); + return this._parseMultiselectList(); + } else if (lookahead === TOK_LBRACE) { + this._match(TOK_LBRACE); + return this._parseMultiselectHash(); + } + }, + + _parseProjectionRHS: function(rbp) { + var right; + if (bindingPower[this._lookahead(0)] < 10) { + right = {type: "Identity"}; + } else if (this._lookahead(0) === TOK_LBRACKET) { + right = this.expression(rbp); + } else if (this._lookahead(0) === TOK_FILTER) { + right = this.expression(rbp); + } else if (this._lookahead(0) === TOK_DOT) { + this._match(TOK_DOT); + right = this._parseDotRHS(rbp); + } else { + var t = this._lookaheadToken(0); + var error = new Error("Sytanx error, unexpected token: " + + t.value + "(" + t.type + ")"); + error.name = "ParserError"; + throw error; + } + return right; + }, + + _parseMultiselectList: function() { + var expressions = []; + while (this._lookahead(0) !== TOK_RBRACKET) { + var expression = this.expression(0); + expressions.push(expression); + if (this._lookahead(0) === TOK_COMMA) { + this._match(TOK_COMMA); + if (this._lookahead(0) === TOK_RBRACKET) { + throw new Error("Unexpected token Rbracket"); + } + } + } + this._match(TOK_RBRACKET); + return {type: "MultiSelectList", children: expressions}; + }, + + _parseMultiselectHash: function() { + var pairs = []; + var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER]; + var keyToken, keyName, value, node; + for (;;) { + keyToken = this._lookaheadToken(0); + if (identifierTypes.indexOf(keyToken.type) < 0) { + throw new Error("Expecting an identifier token, got: " + + keyToken.type); + } + keyName = keyToken.value; + this._advance(); + this._match(TOK_COLON); + value = this.expression(0); + node = {type: "KeyValuePair", name: keyName, value: value}; + pairs.push(node); + if (this._lookahead(0) === TOK_COMMA) { + this._match(TOK_COMMA); + } else if (this._lookahead(0) === TOK_RBRACE) { + this._match(TOK_RBRACE); + break; + } + } + return {type: "MultiSelectHash", children: pairs}; + } + }; + + + function TreeInterpreter(runtime) { + this.runtime = runtime; + } + + TreeInterpreter.prototype = { + search: function(node, value) { + return this.visit(node, value); + }, + + visit: function(node, value) { + var matched, current, result, first, second, field, left, right, collected, i; + switch (node.type) { + case "Field": + if (value === null ) { + return null; + } else if (isObject(value)) { + field = value[node.name]; + if (field === undefined) { + return null; + } else { + return field; + } + } else { + return null; + } + break; + case "Subexpression": + result = this.visit(node.children[0], value); + for (i = 1; i < node.children.length; i++) { + result = this.visit(node.children[1], result); + if (result === null) { + return null; + } + } + return result; + case "IndexExpression": + left = this.visit(node.children[0], value); + right = this.visit(node.children[1], left); + return right; + case "Index": + if (!isArray(value)) { + return null; + } + var index = node.value; + if (index < 0) { + index = value.length + index; + } + result = value[index]; + if (result === undefined) { + result = null; + } + return result; + case "Slice": + if (!isArray(value)) { + return null; + } + var sliceParams = node.children.slice(0); + var computed = this.computeSliceParams(value.length, sliceParams); + var start = computed[0]; + var stop = computed[1]; + var step = computed[2]; + result = []; + if (step > 0) { + for (i = start; i < stop; i += step) { + result.push(value[i]); + } + } else { + for (i = start; i > stop; i += step) { + result.push(value[i]); + } + } + return result; + case "Projection": + // Evaluate left child. + var base = this.visit(node.children[0], value); + if (!isArray(base)) { + return null; + } + collected = []; + for (i = 0; i < base.length; i++) { + current = this.visit(node.children[1], base[i]); + if (current !== null) { + collected.push(current); + } + } + return collected; + case "ValueProjection": + // Evaluate left child. + base = this.visit(node.children[0], value); + if (!isObject(base)) { + return null; + } + collected = []; + var values = objValues(base); + for (i = 0; i < values.length; i++) { + current = this.visit(node.children[1], values[i]); + if (current !== null) { + collected.push(current); + } + } + return collected; + case "FilterProjection": + base = this.visit(node.children[0], value); + if (!isArray(base)) { + return null; + } + var filtered = []; + var finalResults = []; + for (i = 0; i < base.length; i++) { + matched = this.visit(node.children[2], base[i]); + if (!isFalse(matched)) { + filtered.push(base[i]); + } + } + for (var j = 0; j < filtered.length; j++) { + current = this.visit(node.children[1], filtered[j]); + if (current !== null) { + finalResults.push(current); + } + } + return finalResults; + case "Comparator": + first = this.visit(node.children[0], value); + second = this.visit(node.children[1], value); + switch(node.name) { + case TOK_EQ: + result = strictDeepEqual(first, second); + break; + case TOK_NE: + result = !strictDeepEqual(first, second); + break; + case TOK_GT: + result = first > second; + break; + case TOK_GTE: + result = first >= second; + break; + case TOK_LT: + result = first < second; + break; + case TOK_LTE: + result = first <= second; + break; + default: + throw new Error("Unknown comparator: " + node.name); + } + return result; + case TOK_FLATTEN: + var original = this.visit(node.children[0], value); + if (!isArray(original)) { + return null; + } + var merged = []; + for (i = 0; i < original.length; i++) { + current = original[i]; + if (isArray(current)) { + merged.push.apply(merged, current); + } else { + merged.push(current); + } + } + return merged; + case "Identity": + return value; + case "MultiSelectList": + if (value === null) { + return null; + } + collected = []; + for (i = 0; i < node.children.length; i++) { + collected.push(this.visit(node.children[i], value)); + } + return collected; + case "MultiSelectHash": + if (value === null) { + return null; + } + collected = {}; + var child; + for (i = 0; i < node.children.length; i++) { + child = node.children[i]; + collected[child.name] = this.visit(child.value, value); + } + return collected; + case "OrExpression": + matched = this.visit(node.children[0], value); + if (isFalse(matched)) { + matched = this.visit(node.children[1], value); + } + return matched; + case "AndExpression": + first = this.visit(node.children[0], value); + + if (isFalse(first) === true) { + return first; + } + return this.visit(node.children[1], value); + case "NotExpression": + first = this.visit(node.children[0], value); + return isFalse(first); + case "Literal": + return node.value; + case TOK_PIPE: + left = this.visit(node.children[0], value); + return this.visit(node.children[1], left); + case TOK_CURRENT: + return value; + case "Function": + var resolvedArgs = []; + for (i = 0; i < node.children.length; i++) { + resolvedArgs.push(this.visit(node.children[i], value)); + } + return this.runtime.callFunction(node.name, resolvedArgs); + case "ExpressionReference": + var refNode = node.children[0]; + // Tag the node with a specific attribute so the type + // checker verify the type. + refNode.jmespathType = TOK_EXPREF; + return refNode; + default: + throw new Error("Unknown node type: " + node.type); + } + }, + + computeSliceParams: function(arrayLength, sliceParams) { + var start = sliceParams[0]; + var stop = sliceParams[1]; + var step = sliceParams[2]; + var computed = [null, null, null]; + if (step === null) { + step = 1; + } else if (step === 0) { + var error = new Error("Invalid slice, step cannot be 0"); + error.name = "RuntimeError"; + throw error; + } + var stepValueNegative = step < 0 ? true : false; + + if (start === null) { + start = stepValueNegative ? arrayLength - 1 : 0; + } else { + start = this.capSliceRange(arrayLength, start, step); + } + + if (stop === null) { + stop = stepValueNegative ? -1 : arrayLength; + } else { + stop = this.capSliceRange(arrayLength, stop, step); + } + computed[0] = start; + computed[1] = stop; + computed[2] = step; + return computed; + }, + + capSliceRange: function(arrayLength, actualValue, step) { + if (actualValue < 0) { + actualValue += arrayLength; + if (actualValue < 0) { + actualValue = step < 0 ? -1 : 0; + } + } else if (actualValue >= arrayLength) { + actualValue = step < 0 ? arrayLength - 1 : arrayLength; + } + return actualValue; + } + + }; + + function Runtime(interpreter) { + this._interpreter = interpreter; + this.functionTable = { + // name: [function, ] + // The can be: + // + // { + // args: [[type1, type2], [type1, type2]], + // variadic: true|false + // } + // + // Each arg in the arg list is a list of valid types + // (if the function is overloaded and supports multiple + // types. If the type is "any" then no type checking + // occurs on the argument. Variadic is optional + // and if not provided is assumed to be false. + abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]}, + avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, + ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]}, + contains: { + _func: this._functionContains, + _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}, + {types: [TYPE_ANY]}]}, + "ends_with": { + _func: this._functionEndsWith, + _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, + floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]}, + length: { + _func: this._functionLength, + _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]}, + map: { + _func: this._functionMap, + _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]}, + max: { + _func: this._functionMax, + _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, + "merge": { + _func: this._functionMerge, + _signature: [{types: [TYPE_OBJECT], variadic: true}] + }, + "max_by": { + _func: this._functionMaxBy, + _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] + }, + sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, + "starts_with": { + _func: this._functionStartsWith, + _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, + min: { + _func: this._functionMin, + _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, + "min_by": { + _func: this._functionMinBy, + _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] + }, + type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]}, + keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]}, + values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]}, + sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]}, + "sort_by": { + _func: this._functionSortBy, + _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] + }, + join: { + _func: this._functionJoin, + _signature: [ + {types: [TYPE_STRING]}, + {types: [TYPE_ARRAY_STRING]} + ] + }, + reverse: { + _func: this._functionReverse, + _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]}, + "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]}, + "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]}, + "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]}, + "not_null": { + _func: this._functionNotNull, + _signature: [{types: [TYPE_ANY], variadic: true}] + } + }; + } + + Runtime.prototype = { + callFunction: function(name, resolvedArgs) { + var functionEntry = this.functionTable[name]; + if (functionEntry === undefined) { + throw new Error("Unknown function: " + name + "()"); + } + this._validateArgs(name, resolvedArgs, functionEntry._signature); + return functionEntry._func.call(this, resolvedArgs); + }, + + _validateArgs: function(name, args, signature) { + // Validating the args requires validating + // the correct arity and the correct type of each arg. + // If the last argument is declared as variadic, then we need + // a minimum number of args to be required. Otherwise it has to + // be an exact amount. + var pluralized; + if (signature[signature.length - 1].variadic) { + if (args.length < signature.length) { + pluralized = signature.length === 1 ? " argument" : " arguments"; + throw new Error("ArgumentError: " + name + "() " + + "takes at least" + signature.length + pluralized + + " but received " + args.length); + } + } else if (args.length !== signature.length) { + pluralized = signature.length === 1 ? " argument" : " arguments"; + throw new Error("ArgumentError: " + name + "() " + + "takes " + signature.length + pluralized + + " but received " + args.length); + } + var currentSpec; + var actualType; + var typeMatched; + for (var i = 0; i < signature.length; i++) { + typeMatched = false; + currentSpec = signature[i].types; + actualType = this._getTypeName(args[i]); + for (var j = 0; j < currentSpec.length; j++) { + if (this._typeMatches(actualType, currentSpec[j], args[i])) { + typeMatched = true; + break; + } + } + if (!typeMatched) { + throw new Error("TypeError: " + name + "() " + + "expected argument " + (i + 1) + + " to be type " + currentSpec + + " but received type " + actualType + + " instead."); + } + } + }, + + _typeMatches: function(actual, expected, argValue) { + if (expected === TYPE_ANY) { + return true; + } + if (expected === TYPE_ARRAY_STRING || + expected === TYPE_ARRAY_NUMBER || + expected === TYPE_ARRAY) { + // The expected type can either just be array, + // or it can require a specific subtype (array of numbers). + // + // The simplest case is if "array" with no subtype is specified. + if (expected === TYPE_ARRAY) { + return actual === TYPE_ARRAY; + } else if (actual === TYPE_ARRAY) { + // Otherwise we need to check subtypes. + // I think this has potential to be improved. + var subtype; + if (expected === TYPE_ARRAY_NUMBER) { + subtype = TYPE_NUMBER; + } else if (expected === TYPE_ARRAY_STRING) { + subtype = TYPE_STRING; + } + for (var i = 0; i < argValue.length; i++) { + if (!this._typeMatches( + this._getTypeName(argValue[i]), subtype, + argValue[i])) { + return false; + } + } + return true; + } + } else { + return actual === expected; + } + }, + _getTypeName: function(obj) { + switch (Object.prototype.toString.call(obj)) { + case "[object String]": + return TYPE_STRING; + case "[object Number]": + return TYPE_NUMBER; + case "[object Array]": + return TYPE_ARRAY; + case "[object Boolean]": + return TYPE_BOOLEAN; + case "[object Null]": + return TYPE_NULL; + case "[object Object]": + // Check if it's an expref. If it has, it's been + // tagged with a jmespathType attr of 'Expref'; + if (obj.jmespathType === TOK_EXPREF) { + return TYPE_EXPREF; + } else { + return TYPE_OBJECT; + } + } + }, + + _functionStartsWith: function(resolvedArgs) { + return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; + }, + + _functionEndsWith: function(resolvedArgs) { + var searchStr = resolvedArgs[0]; + var suffix = resolvedArgs[1]; + return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; + }, + + _functionReverse: function(resolvedArgs) { + var typeName = this._getTypeName(resolvedArgs[0]); + if (typeName === TYPE_STRING) { + var originalStr = resolvedArgs[0]; + var reversedStr = ""; + for (var i = originalStr.length - 1; i >= 0; i--) { + reversedStr += originalStr[i]; + } + return reversedStr; + } else { + var reversedArray = resolvedArgs[0].slice(0); + reversedArray.reverse(); + return reversedArray; + } + }, + + _functionAbs: function(resolvedArgs) { + return Math.abs(resolvedArgs[0]); + }, + + _functionCeil: function(resolvedArgs) { + return Math.ceil(resolvedArgs[0]); + }, + + _functionAvg: function(resolvedArgs) { + var sum = 0; + var inputArray = resolvedArgs[0]; + for (var i = 0; i < inputArray.length; i++) { + sum += inputArray[i]; + } + return sum / inputArray.length; + }, + + _functionContains: function(resolvedArgs) { + return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; + }, + + _functionFloor: function(resolvedArgs) { + return Math.floor(resolvedArgs[0]); + }, + + _functionLength: function(resolvedArgs) { + if (!isObject(resolvedArgs[0])) { + return resolvedArgs[0].length; + } else { + // As far as I can tell, there's no way to get the length + // of an object without O(n) iteration through the object. + return Object.keys(resolvedArgs[0]).length; + } + }, + + _functionMap: function(resolvedArgs) { + var mapped = []; + var interpreter = this._interpreter; + var exprefNode = resolvedArgs[0]; + var elements = resolvedArgs[1]; + for (var i = 0; i < elements.length; i++) { + mapped.push(interpreter.visit(exprefNode, elements[i])); + } + return mapped; + }, + + _functionMerge: function(resolvedArgs) { + var merged = {}; + for (var i = 0; i < resolvedArgs.length; i++) { + var current = resolvedArgs[i]; + for (var key in current) { + merged[key] = current[key]; + } + } + return merged; + }, + + _functionMax: function(resolvedArgs) { + if (resolvedArgs[0].length > 0) { + var typeName = this._getTypeName(resolvedArgs[0][0]); + if (typeName === TYPE_NUMBER) { + return Math.max.apply(Math, resolvedArgs[0]); + } else { + var elements = resolvedArgs[0]; + var maxElement = elements[0]; + for (var i = 1; i < elements.length; i++) { + if (maxElement.localeCompare(elements[i]) < 0) { + maxElement = elements[i]; + } + } + return maxElement; + } + } else { + return null; + } + }, + + _functionMin: function(resolvedArgs) { + if (resolvedArgs[0].length > 0) { + var typeName = this._getTypeName(resolvedArgs[0][0]); + if (typeName === TYPE_NUMBER) { + return Math.min.apply(Math, resolvedArgs[0]); + } else { + var elements = resolvedArgs[0]; + var minElement = elements[0]; + for (var i = 1; i < elements.length; i++) { + if (elements[i].localeCompare(minElement) < 0) { + minElement = elements[i]; + } + } + return minElement; + } + } else { + return null; + } + }, + + _functionSum: function(resolvedArgs) { + var sum = 0; + var listToSum = resolvedArgs[0]; + for (var i = 0; i < listToSum.length; i++) { + sum += listToSum[i]; + } + return sum; + }, + + _functionType: function(resolvedArgs) { + switch (this._getTypeName(resolvedArgs[0])) { + case TYPE_NUMBER: + return "number"; + case TYPE_STRING: + return "string"; + case TYPE_ARRAY: + return "array"; + case TYPE_OBJECT: + return "object"; + case TYPE_BOOLEAN: + return "boolean"; + case TYPE_EXPREF: + return "expref"; + case TYPE_NULL: + return "null"; + } + }, + + _functionKeys: function(resolvedArgs) { + return Object.keys(resolvedArgs[0]); + }, + + _functionValues: function(resolvedArgs) { + var obj = resolvedArgs[0]; + var keys = Object.keys(obj); + var values = []; + for (var i = 0; i < keys.length; i++) { + values.push(obj[keys[i]]); + } + return values; + }, + + _functionJoin: function(resolvedArgs) { + var joinChar = resolvedArgs[0]; + var listJoin = resolvedArgs[1]; + return listJoin.join(joinChar); + }, + + _functionToArray: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { + return resolvedArgs[0]; + } else { + return [resolvedArgs[0]]; + } + }, + + _functionToString: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { + return resolvedArgs[0]; + } else { + return JSON.stringify(resolvedArgs[0]); + } + }, + + _functionToNumber: function(resolvedArgs) { + var typeName = this._getTypeName(resolvedArgs[0]); + var convertedValue; + if (typeName === TYPE_NUMBER) { + return resolvedArgs[0]; + } else if (typeName === TYPE_STRING) { + convertedValue = +resolvedArgs[0]; + if (!isNaN(convertedValue)) { + return convertedValue; + } + } + return null; + }, + + _functionNotNull: function(resolvedArgs) { + for (var i = 0; i < resolvedArgs.length; i++) { + if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { + return resolvedArgs[i]; + } + } + return null; + }, + + _functionSort: function(resolvedArgs) { + var sortedArray = resolvedArgs[0].slice(0); + sortedArray.sort(); + return sortedArray; + }, + + _functionSortBy: function(resolvedArgs) { + var sortedArray = resolvedArgs[0].slice(0); + if (sortedArray.length === 0) { + return sortedArray; + } + var interpreter = this._interpreter; + var exprefNode = resolvedArgs[1]; + var requiredType = this._getTypeName( + interpreter.visit(exprefNode, sortedArray[0])); + if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) { + throw new Error("TypeError"); + } + var that = this; + // In order to get a stable sort out of an unstable + // sort algorithm, we decorate/sort/undecorate (DSU) + // by creating a new list of [index, element] pairs. + // In the cmp function, if the evaluated elements are + // equal, then the index will be used as the tiebreaker. + // After the decorated list has been sorted, it will be + // undecorated to extract the original elements. + var decorated = []; + for (var i = 0; i < sortedArray.length; i++) { + decorated.push([i, sortedArray[i]]); + } + decorated.sort(function(a, b) { + var exprA = interpreter.visit(exprefNode, a[1]); + var exprB = interpreter.visit(exprefNode, b[1]); + if (that._getTypeName(exprA) !== requiredType) { + throw new Error( + "TypeError: expected " + requiredType + ", received " + + that._getTypeName(exprA)); + } else if (that._getTypeName(exprB) !== requiredType) { + throw new Error( + "TypeError: expected " + requiredType + ", received " + + that._getTypeName(exprB)); + } + if (exprA > exprB) { + return 1; + } else if (exprA < exprB) { + return -1; + } else { + // If they're equal compare the items by their + // order to maintain relative order of equal keys + // (i.e. to get a stable sort). + return a[0] - b[0]; + } + }); + // Undecorate: extract out the original list elements. + for (var j = 0; j < decorated.length; j++) { + sortedArray[j] = decorated[j][1]; + } + return sortedArray; + }, + + _functionMaxBy: function(resolvedArgs) { + var exprefNode = resolvedArgs[1]; + var resolvedArray = resolvedArgs[0]; + var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); + var maxNumber = -Infinity; + var maxRecord; + var current; + for (var i = 0; i < resolvedArray.length; i++) { + current = keyFunction(resolvedArray[i]); + if (current > maxNumber) { + maxNumber = current; + maxRecord = resolvedArray[i]; + } + } + return maxRecord; + }, + + _functionMinBy: function(resolvedArgs) { + var exprefNode = resolvedArgs[1]; + var resolvedArray = resolvedArgs[0]; + var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); + var minNumber = Infinity; + var minRecord; + var current; + for (var i = 0; i < resolvedArray.length; i++) { + current = keyFunction(resolvedArray[i]); + if (current < minNumber) { + minNumber = current; + minRecord = resolvedArray[i]; + } + } + return minRecord; + }, + + createKeyFunction: function(exprefNode, allowedTypes) { + var that = this; + var interpreter = this._interpreter; + var keyFunc = function(x) { + var current = interpreter.visit(exprefNode, x); + if (allowedTypes.indexOf(that._getTypeName(current)) < 0) { + var msg = "TypeError: expected one of " + allowedTypes + + ", received " + that._getTypeName(current); + throw new Error(msg); + } + return current; + }; + return keyFunc; + } + + }; + + function compile(stream) { + var parser = new Parser(); + var ast = parser.parse(stream); + return ast; + } + + function tokenize(stream) { + var lexer = new Lexer(); + return lexer.tokenize(stream); + } + + function search(data, expression) { + var parser = new Parser(); + // This needs to be improved. Both the interpreter and runtime depend on + // each other. The runtime needs the interpreter to support exprefs. + // There's likely a clean way to avoid the cyclic dependency. + var runtime = new Runtime(); + var interpreter = new TreeInterpreter(runtime); + runtime._interpreter = interpreter; + var node = parser.parse(expression); + return interpreter.search(node, data); + } + + exports.tokenize = tokenize; + exports.compile = compile; + exports.search = search; + exports.strictDeepEqual = strictDeepEqual; +})( false ? 0 : exports); + + +/***/ }), + +/***/ 7147: +/***/ ((module) => { + +module.exports = Pager + +function Pager (pageSize, opts) { + if (!(this instanceof Pager)) return new Pager(pageSize, opts) + + this.length = 0 + this.updates = [] + this.path = new Uint16Array(4) + this.pages = new Array(32768) + this.maxPages = this.pages.length + this.level = 0 + this.pageSize = pageSize || 1024 + this.deduplicate = opts ? opts.deduplicate : null + this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null +} + +Pager.prototype.updated = function (page) { + while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) { + page.deduplicate++ + if (page.deduplicate === this.deduplicate.length) { + page.deduplicate = 0 + if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate + break + } + } + if (page.updated || !this.updates) return + page.updated = true + this.updates.push(page) +} + +Pager.prototype.lastUpdate = function () { + if (!this.updates || !this.updates.length) return null + var page = this.updates.pop() + page.updated = false + return page +} + +Pager.prototype._array = function (i, noAllocate) { + if (i >= this.maxPages) { + if (noAllocate) return + grow(this, i) + } + + factor(i, this.path) + + var arr = this.pages + + for (var j = this.level; j > 0; j--) { + var p = this.path[j] + var next = arr[p] + + if (!next) { + if (noAllocate) return + next = arr[p] = new Array(32768) + } + + arr = next + } + + return arr +} + +Pager.prototype.get = function (i, noAllocate) { + var arr = this._array(i, noAllocate) + var first = this.path[0] + var page = arr && arr[first] + + if (!page && !noAllocate) { + page = arr[first] = new Page(i, alloc(this.pageSize)) + if (i >= this.length) this.length = i + 1 + } + + if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { + page.buffer = copy(page.buffer) + page.deduplicate = 0 + } + + return page +} + +Pager.prototype.set = function (i, buf) { + var arr = this._array(i, false) + var first = this.path[0] + + if (i >= this.length) this.length = i + 1 + + if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { + arr[first] = undefined + return + } + + if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { + buf = this.deduplicate + } + + var page = arr[first] + var b = truncate(buf, this.pageSize) + + if (page) page.buffer = b + else arr[first] = new Page(i, b) +} + +Pager.prototype.toBuffer = function () { + var list = new Array(this.length) + var empty = alloc(this.pageSize) + var ptr = 0 + + while (ptr < list.length) { + var arr = this._array(ptr, true) + for (var i = 0; i < 32768 && ptr < list.length; i++) { + list[ptr++] = (arr && arr[i]) ? arr[i].buffer : empty + } + } + + return Buffer.concat(list) +} + +function grow (pager, index) { + while (pager.maxPages < index) { + var old = pager.pages + pager.pages = new Array(32768) + pager.pages[0] = old + pager.level++ + pager.maxPages *= 32768 + } +} + +function truncate (buf, len) { + if (buf.length === len) return buf + if (buf.length > len) return buf.slice(0, len) + var cpy = alloc(len) + buf.copy(cpy) + return cpy +} + +function alloc (size) { + if (Buffer.alloc) return Buffer.alloc(size) + var buf = new Buffer(size) + buf.fill(0) + return buf +} + +function copy (buf) { + var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length) + buf.copy(cpy) + return cpy +} + +function Page (i, buf) { + this.offset = i * buf.length + this.buffer = buf + this.updated = false + this.deduplicate = 0 +} + +function factor (n, out) { + n = (n - (out[0] = (n & 32767))) / 32768 + n = (n - (out[1] = (n & 32767))) / 32768 + out[3] = ((n - (out[2] = (n & 32767))) / 32768) & 32767 +} + + +/***/ }), + +/***/ 5517: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// Core module +const core = __webpack_require__(3994); +const Instrumentation = __webpack_require__(2138); + +// Set up the connect function +const connect = __webpack_require__(1545).connect; + +// Expose error class +connect.MongoError = core.MongoError; +connect.MongoNetworkError = core.MongoNetworkError; +connect.MongoTimeoutError = core.MongoTimeoutError; +connect.MongoServerSelectionError = core.MongoServerSelectionError; +connect.MongoParseError = core.MongoParseError; +connect.MongoWriteConcernError = core.MongoWriteConcernError; +connect.MongoBulkWriteError = __webpack_require__(4239).BulkWriteError; +connect.BulkWriteError = connect.MongoBulkWriteError; + +// Actual driver classes exported +connect.Admin = __webpack_require__(3238); +connect.MongoClient = __webpack_require__(1545); +connect.Db = __webpack_require__(6662); +connect.Collection = __webpack_require__(5193); +connect.Server = __webpack_require__(8421); +connect.ReplSet = __webpack_require__(382); +connect.Mongos = __webpack_require__(2048); +connect.ReadPreference = core.ReadPreference; +connect.GridStore = __webpack_require__(9406); +connect.Chunk = __webpack_require__(3890); +connect.Logger = core.Logger; +connect.AggregationCursor = __webpack_require__(7429); +connect.CommandCursor = __webpack_require__(538); +connect.Cursor = __webpack_require__(7159); +connect.GridFSBucket = __webpack_require__(2573); +// Exported to be used in tests not to be used anywhere else +connect.CoreServer = core.Server; +connect.CoreConnection = core.Connection; + +// BSON types exported +connect.Binary = core.BSON.Binary; +connect.Code = core.BSON.Code; +connect.Map = core.BSON.Map; +connect.DBRef = core.BSON.DBRef; +connect.Double = core.BSON.Double; +connect.Int32 = core.BSON.Int32; +connect.Long = core.BSON.Long; +connect.MinKey = core.BSON.MinKey; +connect.MaxKey = core.BSON.MaxKey; +connect.ObjectID = core.BSON.ObjectID; +connect.ObjectId = core.BSON.ObjectID; +connect.Symbol = core.BSON.Symbol; +connect.Timestamp = core.BSON.Timestamp; +connect.BSONRegExp = core.BSON.BSONRegExp; +connect.Decimal128 = core.BSON.Decimal128; + +// Add connect method +connect.connect = connect; + +// Set up the instrumentation method +connect.instrument = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + const instrumentation = new Instrumentation(); + instrumentation.instrument(connect.MongoClient, callback); + return instrumentation; +}; + +// Set our exports to be the connect function +module.exports = connect; + + +/***/ }), + +/***/ 3238: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const applyWriteConcern = __webpack_require__(1371).applyWriteConcern; + +const AddUserOperation = __webpack_require__(7057); +const ExecuteDbAdminCommandOperation = __webpack_require__(1681); +const RemoveUserOperation = __webpack_require__(1969); +const ValidateCollectionOperation = __webpack_require__(9263); +const ListDatabasesOperation = __webpack_require__(9929); + +const executeOperation = __webpack_require__(2548); + +/** + * @fileOverview The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Use the admin database for the operation + * const adminDb = client.db(dbName).admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * test.equal(null, err); + * test.ok(dbs.databases.length > 0); + * client.close(); + * }); + * }); + */ + +/** + * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {Admin} a collection instance. + */ +function Admin(db, topology, promiseLibrary) { + if (!(this instanceof Admin)) return new Admin(db, topology); + + // Internal state + this.s = { + db: db, + topology: topology, + promiseLibrary: promiseLibrary + }; +} + +/** + * The callback format for results + * @callback Admin~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.command = function(command, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : {}; + + const commandOperation = new ExecuteDbAdminCommandOperation(this.s.db, command, options); + + return executeOperation(this.s.db.s.topology, commandOperation, callback); +}; + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.buildInfo = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { buildinfo: 1 }; + + const buildInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); + + return executeOperation(this.s.db.s.topology, buildInfoOperation, callback); +}; + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverInfo = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { buildinfo: 1 }; + + const serverInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); + + return executeOperation(this.s.db.s.topology, serverInfoOperation, callback); +}; + +/** + * Retrieve this db's server status. + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverStatus = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const serverStatusOperation = new ExecuteDbAdminCommandOperation( + this.s.db, + { serverStatus: 1 }, + options + ); + + return executeOperation(this.s.db.s.topology, serverStatusOperation, callback); +}; + +/** + * Ping the MongoDB server and retrieve results + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.ping = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { ping: 1 }; + + const pingOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); + + return executeOperation(this.s.db.s.topology, pingOperation, callback); +}; + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.addUser = function(username, password, options, callback) { + const args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + // Special case where there is no password ($external users) + if (typeof username === 'string' && password != null && typeof password === 'object') { + options = password; + password = null; + } + + options = args.length ? args.shift() : {}; + options = Object.assign({}, options); + // Get the options + options = applyWriteConcern(options, { db: this.s.db }); + // Set the db name to admin + options.dbName = 'admin'; + + const addUserOperation = new AddUserOperation(this.s.db, username, password, options); + + return executeOperation(this.s.db.s.topology, addUserOperation, callback); +}; + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.removeUser = function(username, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + options = args.length ? args.shift() : {}; + options = Object.assign({}, options); + // Get the options + options = applyWriteConcern(options, { db: this.s.db }); + // Set the db name + options.dbName = 'admin'; + + const removeUserOperation = new RemoveUserOperation(this.s.db, username, options); + + return executeOperation(this.s.db.s.topology, removeUserOperation, callback); +}; + +/** + * Validate an existing collection + * + * @param {string} collectionName The name of the collection to validate. + * @param {object} [options] Optional settings. + * @param {boolean} [options.background] Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.validateCollection = function(collectionName, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const validateCollectionOperation = new ValidateCollectionOperation( + this, + collectionName, + options + ); + + return executeOperation(this.s.db.s.topology, validateCollectionOperation, callback); +}; + +/** + * List the available databases + * + * @param {object} [options] Optional settings. + * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.listDatabases = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation( + this.s.db.s.topology, + new ListDatabasesOperation(this.s.db, options), + callback + ); +}; + +/** + * Get ReplicaSet status + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.replSetGetStatus = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const replSetGetStatusOperation = new ExecuteDbAdminCommandOperation( + this.s.db, + { replSetGetStatus: 1 }, + options + ); + + return executeOperation(this.s.db.s.topology, replSetGetStatusOperation, callback); +}; + +module.exports = Admin; + + +/***/ }), + +/***/ 7429: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const MongoError = __webpack_require__(3994).MongoError; +const Cursor = __webpack_require__(7159); +const CursorState = __webpack_require__(4847).CursorState; +const deprecate = __webpack_require__(1669).deprecate; + +/** + * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * + * **AGGREGATIONCURSOR Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class AggregationCursor + * @extends external:Readable + * @fires AggregationCursor#data + * @fires AggregationCursor#end + * @fires AggregationCursor#close + * @fires AggregationCursor#readable + * @return {AggregationCursor} an AggregationCursor instance. + */ +class AggregationCursor extends Cursor { + constructor(topology, operation, options) { + super(topology, operation, options); + } + + /** + * Set the batch size for the cursor. + * @method + * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @throws {MongoError} + * @return {AggregationCursor} + */ + batchSize(value) { + if (this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + } + + this.operation.options.batchSize = value; + this.setCursorBatchSize(value); + return this; + } + + /** + * Add a geoNear stage to the aggregation pipeline + * @method + * @param {object} document The geoNear stage document. + * @return {AggregationCursor} + */ + geoNear(document) { + this.operation.addToPipeline({ $geoNear: document }); + return this; + } + + /** + * Add a group stage to the aggregation pipeline + * @method + * @param {object} document The group stage document. + * @return {AggregationCursor} + */ + group(document) { + this.operation.addToPipeline({ $group: document }); + return this; + } + + /** + * Add a limit stage to the aggregation pipeline + * @method + * @param {number} value The state limit value. + * @return {AggregationCursor} + */ + limit(value) { + this.operation.addToPipeline({ $limit: value }); + return this; + } + + /** + * Add a match stage to the aggregation pipeline + * @method + * @param {object} document The match stage document. + * @return {AggregationCursor} + */ + match(document) { + this.operation.addToPipeline({ $match: document }); + return this; + } + + /** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {AggregationCursor} + */ + maxTimeMS(value) { + this.operation.options.maxTimeMS = value; + return this; + } + + /** + * Add a out stage to the aggregation pipeline + * @method + * @param {number} destination The destination name. + * @return {AggregationCursor} + */ + out(destination) { + this.operation.addToPipeline({ $out: destination }); + return this; + } + + /** + * Add a project stage to the aggregation pipeline + * @method + * @param {object} document The project stage document. + * @return {AggregationCursor} + */ + project(document) { + this.operation.addToPipeline({ $project: document }); + return this; + } + + /** + * Add a lookup stage to the aggregation pipeline + * @method + * @param {object} document The lookup stage document. + * @return {AggregationCursor} + */ + lookup(document) { + this.operation.addToPipeline({ $lookup: document }); + return this; + } + + /** + * Add a redact stage to the aggregation pipeline + * @method + * @param {object} document The redact stage document. + * @return {AggregationCursor} + */ + redact(document) { + this.operation.addToPipeline({ $redact: document }); + return this; + } + + /** + * Add a skip stage to the aggregation pipeline + * @method + * @param {number} value The state skip value. + * @return {AggregationCursor} + */ + skip(value) { + this.operation.addToPipeline({ $skip: value }); + return this; + } + + /** + * Add a sort stage to the aggregation pipeline + * @method + * @param {object} document The sort stage document. + * @return {AggregationCursor} + */ + sort(document) { + this.operation.addToPipeline({ $sort: document }); + return this; + } + + /** + * Add a unwind stage to the aggregation pipeline + * @method + * @param {number} field The unwind field name. + * @return {AggregationCursor} + */ + unwind(field) { + this.operation.addToPipeline({ $unwind: field }); + return this; + } + + /** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ + getLogger() { + return this.logger; + } +} + +// aliases +AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; + +// deprecated methods +deprecate( + AggregationCursor.prototype.geoNear, + 'The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2.' +); + +/** + * AggregationCursor stream data event, fired for each document in the cursor. + * + * @event AggregationCursor#data + * @type {object} + */ + +/** + * AggregationCursor stream end event + * + * @event AggregationCursor#end + * @type {null} + */ + +/** + * AggregationCursor stream close event + * + * @event AggregationCursor#close + * @type {null} + */ + +/** + * AggregationCursor stream readable event + * + * @event AggregationCursor#readable + * @type {null} + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function AggregationCursor.prototype.next + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Check if there is any document still available in the cursor + * @function AggregationCursor.prototype.hasNext + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method AggregationCursor.prototype.toArray + * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previously accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method AggregationCursor.prototype.each + * @deprecated + * @param {AggregationCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a AggregationCursor command and emitting close. + * @method AggregationCursor.prototype.close + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method AggregationCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Execute the explain for the cursor + * @method AggregationCursor.prototype.explain + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Clone the cursor + * @function AggregationCursor.prototype.clone + * @return {AggregationCursor} + */ + +/** + * Resets the cursor + * @function AggregationCursor.prototype.rewind + * @return {AggregationCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback AggregationCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback AggregationCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method AggregationCursor.prototype.forEach + * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. + * @param {AggregationCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +module.exports = AggregationCursor; + + +/***/ }), + +/***/ 2138: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const EventEmitter = __webpack_require__(8614).EventEmitter; + +class Instrumentation extends EventEmitter { + constructor() { + super(); + } + + instrument(MongoClient, callback) { + // store a reference to the original functions + this.$MongoClient = MongoClient; + const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect); + + const instrumentation = this; + MongoClient.prototype.connect = function(callback) { + this.s.options.monitorCommands = true; + this.on('commandStarted', event => instrumentation.emit('started', event)); + this.on('commandSucceeded', event => instrumentation.emit('succeeded', event)); + this.on('commandFailed', event => instrumentation.emit('failed', event)); + return $prototypeConnect.call(this, callback); + }; + + if (typeof callback === 'function') callback(null, this); + } + + uninstrument() { + this.$MongoClient.prototype.connect = this.$prototypeConnect; + } +} + +module.exports = Instrumentation; + + +/***/ }), + +/***/ 1749: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +// async function* asyncIterator() { +// while (true) { +// const value = await this.next(); +// if (!value) { +// await this.close(); +// return; +// } + +// yield value; +// } +// } + +// TODO [$5f5fbe42fcabad09c1c24199]: change this to the async generator function above +function asyncIterator() { + const cursor = this; + + return { + next: function() { + return Promise.resolve() + .then(() => cursor.next()) + .then(value => { + if (!value) { + return cursor.close().then(() => ({ value, done: true })); + } + return { value, done: false }; + }); + } + }; +} + +exports.asyncIterator = asyncIterator; + + +/***/ }), + +/***/ 4239: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Long = __webpack_require__(3994).BSON.Long; +const MongoError = __webpack_require__(3994).MongoError; +const ObjectID = __webpack_require__(3994).BSON.ObjectID; +const BSON = __webpack_require__(3994).BSON; +const MongoWriteConcernError = __webpack_require__(3994).MongoWriteConcernError; +const toError = __webpack_require__(1371).toError; +const handleCallback = __webpack_require__(1371).handleCallback; +const applyRetryableWrites = __webpack_require__(1371).applyRetryableWrites; +const applyWriteConcern = __webpack_require__(1371).applyWriteConcern; +const executeLegacyOperation = __webpack_require__(1371).executeLegacyOperation; +const isPromiseLike = __webpack_require__(1371).isPromiseLike; +const hasAtomicOperators = __webpack_require__(1371).hasAtomicOperators; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; + +// Error codes +const WRITE_CONCERN_ERROR = 64; + +// Insert types +const INSERT = 1; +const UPDATE = 2; +const REMOVE = 3; + +const bson = new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp +]); + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * @ignore + */ +class Batch { + constructor(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; + } +} + +/** + * @classdesc + * The result of a bulk write. + */ +class BulkWriteResult { + /** + * Create a new BulkWriteResult instance + * + * **NOTE:** Internal Type, do not instantiate directly + */ + constructor(bulkResult) { + this.result = bulkResult; + } + + /** + * Evaluates to true if the bulk operation correctly executes + * @type {boolean} + */ + get ok() { + return this.result.ok; + } + + /** + * The number of inserted documents + * @type {number} + */ + get nInserted() { + return this.result.nInserted; + } + + /** + * Number of upserted documents + * @type {number} + */ + get nUpserted() { + return this.result.nUpserted; + } + + /** + * Number of matched documents + * @type {number} + */ + get nMatched() { + return this.result.nMatched; + } + + /** + * Number of documents updated physically on disk + * @type {number} + */ + get nModified() { + return this.result.nModified; + } + + /** + * Number of removed documents + * @type {number} + */ + get nRemoved() { + return this.result.nRemoved; + } + + /** + * Returns an array of all inserted ids + * + * @return {object[]} + */ + getInsertedIds() { + return this.result.insertedIds; + } + + /** + * Returns an array of all upserted ids + * + * @return {object[]} + */ + getUpsertedIds() { + return this.result.upserted; + } + + /** + * Returns the upserted id at the given index + * + * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index + * @return {object} + */ + getUpsertedIdAt(index) { + return this.result.upserted[index]; + } + + /** + * Returns raw internal result + * + * @return {object} + */ + getRawResponse() { + return this.result; + } + + /** + * Returns true if the bulk operation contains a write error + * + * @return {boolean} + */ + hasWriteErrors() { + return this.result.writeErrors.length > 0; + } + + /** + * Returns the number of write errors off the bulk operation + * + * @return {number} + */ + getWriteErrorCount() { + return this.result.writeErrors.length; + } + + /** + * Returns a specific write error object + * + * @param {number} index of the write error to return, returns null if there is no result for passed in index + * @return {WriteError} + */ + getWriteErrorAt(index) { + if (index < this.result.writeErrors.length) { + return this.result.writeErrors[index]; + } + return null; + } + + /** + * Retrieve all write errors + * + * @return {WriteError[]} + */ + getWriteErrors() { + return this.result.writeErrors; + } + + /** + * Retrieve lastOp if available + * + * @return {object} + */ + getLastOp() { + return this.result.lastOp; + } + + /** + * Retrieve the write concern error if any + * + * @return {WriteConcernError} + */ + getWriteConcernError() { + if (this.result.writeConcernErrors.length === 0) { + return null; + } else if (this.result.writeConcernErrors.length === 1) { + // Return the error + return this.result.writeConcernErrors[0]; + } else { + // Combine the errors + let errmsg = ''; + for (let i = 0; i < this.result.writeConcernErrors.length; i++) { + const err = this.result.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + + // TODO [$5f5fbe42fcabad09c1c2419a]: Something better + if (i === 0) errmsg = errmsg + ' and '; + } + + return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR }); + } + } + + /** + * @return {object} + */ + toJSON() { + return this.result; + } + + /** + * @return {string} + */ + toString() { + return `BulkWriteResult(${this.toJSON(this.result)})`; + } + + /** + * @return {boolean} + */ + isOk() { + return this.result.ok === 1; + } +} + +/** + * @classdesc An error representing a failure by the server to apply the requested write concern to the bulk operation. + */ +class WriteConcernError { + /** + * Create a new WriteConcernError instance + * + * **NOTE:** Internal Type, do not instantiate directly + */ + constructor(err) { + this.err = err; + } + + /** + * Write concern error code. + * @type {number} + */ + get code() { + return this.err.code; + } + + /** + * Write concern error message. + * @type {string} + */ + get errmsg() { + return this.err.errmsg; + } + + /** + * @return {object} + */ + toJSON() { + return { code: this.err.code, errmsg: this.err.errmsg }; + } + + /** + * @return {string} + */ + toString() { + return `WriteConcernError(${this.err.errmsg})`; + } +} + +/** + * @classdesc An error that occurred during a BulkWrite on the server. + */ +class WriteError { + /** + * Create a new WriteError instance + * + * **NOTE:** Internal Type, do not instantiate directly + */ + constructor(err) { + this.err = err; + } + + /** + * WriteError code. + * @type {number} + */ + get code() { + return this.err.code; + } + + /** + * WriteError original bulk operation index. + * @type {number} + */ + get index() { + return this.err.index; + } + + /** + * WriteError message. + * @type {string} + */ + get errmsg() { + return this.err.errmsg; + } + + /** + * Returns the underlying operation that caused the error + * @return {object} + */ + getOperation() { + return this.err.op; + } + + /** + * @return {object} + */ + toJSON() { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + } + + /** + * @return {string} + */ + toString() { + return `WriteError(${JSON.stringify(this.toJSON())})`; + } +} + +/** + * Merges results into shared data structure + * @ignore + */ +function mergeBatchResults(batch, bulkResult, err, result) { + // If we have an error set the result to be the err object + if (err) { + result = err; + } else if (result && result.result) { + result = result.result; + } else if (result == null) { + return; + } + + // Do we have a top level error stop processing and return + if (result.ok === 0 && bulkResult.ok === 1) { + bulkResult.ok = 0; + + const writeError = { + index: 0, + code: result.code || 0, + errmsg: result.message, + op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if (result.ok === 0 && bulkResult.ok === 0) { + return; + } + + // Deal with opTime if available + if (result.opTime || result.lastOp) { + const opTime = result.lastOp || result.opTime; + let lastOpTS = null; + let lastOpT = null; + + // We have a time stamp + if (opTime && opTime._bsontype === 'Timestamp') { + if (bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if (opTime.greaterThan(bulkResult.lastOp)) { + bulkResult.lastOp = opTime; + } + } else { + // Existing TS + if (bulkResult.lastOp) { + lastOpTS = + typeof bulkResult.lastOp.ts === 'number' + ? Long.fromNumber(bulkResult.lastOp.ts) + : bulkResult.lastOp.ts; + lastOpT = + typeof bulkResult.lastOp.t === 'number' + ? Long.fromNumber(bulkResult.lastOp.t) + : bulkResult.lastOp.t; + } + + // Current OpTime TS + const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts; + const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t; + + // Compare the opTime's + if (bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if (opTimeTS.greaterThan(lastOpTS)) { + bulkResult.lastOp = opTime; + } else if (opTimeTS.equals(lastOpTS)) { + if (opTimeT.greaterThan(lastOpT)) { + bulkResult.lastOp = opTime; + } + } + } + } + + // If we have an insert Batch type + if (batch.batchType === INSERT && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + + // If we have an insert Batch type + if (batch.batchType === REMOVE && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + + let nUpserted = 0; + + // We have an array of upserted values, we need to rewrite the indexes + if (Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + + for (let i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex, + _id: result.upserted[i]._id + }); + } + } else if (result.upserted) { + nUpserted = 1; + + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); + } + + // If we have an update Batch type + if (batch.batchType === UPDATE && result.n) { + const nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + + if (typeof nModified === 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = null; + } + } + + if (Array.isArray(result.writeErrors)) { + for (let i = 0; i < result.writeErrors.length; i++) { + const writeError = { + index: batch.originalIndexes[result.writeErrors[i].index], + code: result.writeErrors[i].code, + errmsg: result.writeErrors[i].errmsg, + op: batch.operations[result.writeErrors[i].index] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} + +function executeCommands(bulkOperation, options, callback) { + if (bulkOperation.s.batches.length === 0) { + return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); + } + + const batch = bulkOperation.s.batches.shift(); + + function resultHandler(err, result) { + // Error is a driver related error not a bulk op error, terminate + if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { + return handleCallback(callback, err); + } + + // If we have and error + if (err) err.ok = 0; + if (err instanceof MongoWriteConcernError) { + return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback); + } + + // Merge the results together + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + if (mergeResult != null) { + return handleCallback(callback, null, writeResult); + } + + if (bulkOperation.handleWriteError(callback, writeResult)) return; + + // Execute the next command in line + executeCommands(bulkOperation, options, callback); + } + + bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); +} + +/** + * handles write concern error + * + * @ignore + * @param {object} batch + * @param {object} bulkResult + * @param {boolean} ordered + * @param {WriteConcernError} err + * @param {function} callback + */ +function handleMongoWriteConcernError(batch, bulkResult, err, callback) { + mergeBatchResults(batch, bulkResult, null, err.result); + + const wrappedWriteConcernError = new WriteConcernError({ + errmsg: err.result.writeConcernError.errmsg, + code: err.result.writeConcernError.result + }); + return handleCallback( + callback, + new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), + null + ); +} + +/** + * @classdesc An error indicating an unsuccessful Bulk Write + */ +class BulkWriteError extends MongoError { + /** + * Creates a new BulkWriteError + * + * @param {Error|string|object} message The error message + * @param {BulkWriteResult} result The result of the bulk write operation + * @extends {MongoError} + */ + constructor(error, result) { + const message = error.err || error.errmsg || error.errMessage || error; + super(message); + + Object.assign(this, error); + + this.name = 'BulkWriteError'; + this.result = result; + } +} + +/** + * @classdesc A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + */ +class FindOperators { + /** + * Creates a new FindOperators object. + * + * **NOTE:** Internal Type, do not instantiate directly + * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation + */ + constructor(bulkOperation) { + this.s = bulkOperation.s; + } + + /** + * Add a multiple update operation to the bulk operation + * + * @method + * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} + * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + update(updateDocument) { + // Perform upsert + const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + const document = { + q: this.s.currentOp.selector, + u: updateDocument, + multi: true, + upsert: upsert + }; + + if (updateDocument.hint) { + document.hint = updateDocument.hint; + } + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, UPDATE, document); + } + + /** + * Add a single update operation to the bulk operation + * + * @method + * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} + * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + updateOne(updateDocument) { + // Perform upsert + const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + const document = { + q: this.s.currentOp.selector, + u: updateDocument, + multi: false, + upsert: upsert + }; + + if (updateDocument.hint) { + document.hint = updateDocument.hint; + } + + if (!hasAtomicOperators(updateDocument)) { + throw new TypeError('Update document requires atomic operators'); + } + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, UPDATE, document); + } + + /** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} replacement the new document to replace the existing one with + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + replaceOne(replacement) { + // Perform upsert + const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + const document = { + q: this.s.currentOp.selector, + u: replacement, + multi: false, + upsert: upsert + }; + + if (replacement.hint) { + document.hint = replacement.hint; + } + + if (hasAtomicOperators(replacement)) { + throw new TypeError('Replacement document must not use atomic operators'); + } + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, UPDATE, document); + } + + /** + * Upsert modifier for update bulk operation, noting that this operation is an upsert. + * + * @method + * @throws {MongoError} If operation cannot be added to bulk write + * @return {FindOperators} reference to self + */ + upsert() { + this.s.currentOp.upsert = true; + return this; + } + + /** + * Add a delete one operation to the bulk operation + * + * @method + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + deleteOne() { + // Establish the update command + const document = { + q: this.s.currentOp.selector, + limit: 1 + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, REMOVE, document); + } + + /** + * Add a delete many operation to the bulk operation + * + * @method + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + delete() { + // Establish the update command + const document = { + q: this.s.currentOp.selector, + limit: 0 + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, REMOVE, document); + } + + /** + * backwards compatability for deleteOne + */ + removeOne() { + return this.deleteOne(); + } + + /** + * backwards compatability for delete + */ + remove() { + return this.delete(); + } +} + +/** + * @classdesc Parent class to OrderedBulkOperation and UnorderedBulkOperation + * + * **NOTE:** Internal Type, do not instantiate directly + */ +class BulkOperationBase { + /** + * Create a new OrderedBulkOperation or UnorderedBulkOperation instance + * @property {number} length Get the number of operations in the bulk. + */ + constructor(topology, collection, options, isOrdered) { + // determine whether bulkOperation is ordered or unordered + this.isOrdered = isOrdered; + + options = options == null ? {} : options; + // TODO Bring from driver information in isMaster + // Get the namespace for the write operations + const namespace = collection.s.namespace; + // Used to mark operation as executed + const executed = false; + + // Current item + const currentOp = null; + + // Handle to the bson serializer, used to calculate running sizes + const bson = topology.bson; + // Set max byte size + const isMaster = topology.lastIsMaster(); + + // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents + // over 2mb are still allowed + const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); + const maxBsonObjectSize = + isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; + const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; + const maxWriteBatchSize = + isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; + + // Calculates the largest possible size of an Array key, represented as a BSON string + // element. This calculation: + // 1 byte for BSON type + // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) + // + 1 bytes for null terminator + const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, collection.s.db); + finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options); + const writeConcern = finalOptions.writeConcern; + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Final results + const bulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult, + // Current batch state + currentBatch: null, + currentIndex: 0, + // ordered specific + currentBatchSize: 0, + currentBatchSizeBytes: 0, + // unordered specific + currentInsertBatch: null, + currentUpdateBatch: null, + currentRemoveBatch: null, + batches: [], + // Write concern + writeConcern: writeConcern, + // Max batch size options + maxBsonObjectSize, + maxBatchSizeBytes, + maxWriteBatchSize, + maxKeySize, + // Namespace + namespace: namespace, + // BSON + bson: bson, + // Topology + topology: topology, + // Options + options: finalOptions, + // Current operation + currentOp: currentOp, + // Executed + executed: executed, + // Collection + collection: collection, + // Promise Library + promiseLibrary: promiseLibrary, + // Fundamental error + err: null, + // check keys + checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true + }; + + // bypass Validation + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } + } + + /** + * Add a single insert document to the bulk operation + * + * @param {object} document the document to insert + * @throws {MongoError} + * @return {BulkOperationBase} A reference to self + * + * @example + * const bulkOp = collection.initializeOrderedBulkOp(); + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + */ + insert(document) { + if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) + document._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, document); + } + + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @method + * @param {object} selector The selector for the bulk operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-q q documentation} + * @throws {MongoError} if a selector is not specified + * @return {FindOperators} A helper object with which the write operation can be defined. + * + * @example + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({ j: 10 }); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + */ + find(selector) { + if (!selector) { + throw toError('Bulk find operation must specify a selector'); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + }; + + return new FindOperators(this); + } + + /** + * Specifies a raw operation to perform in the bulk write. + * + * @method + * @param {object} op The raw operation to perform. + * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. + * @return {BulkOperationBase} A reference to self + */ + raw(op) { + const key = Object.keys(op)[0]; + + // Set up the force server object id + const forceServerObjectId = + typeof this.s.options.forceServerObjectId === 'boolean' + ? this.s.options.forceServerObjectId + : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if ( + (op.updateOne && op.updateOne.q) || + (op.updateMany && op.updateMany.q) || + (op.replaceOne && op.replaceOne.q) + ) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return this.s.options.addToOperationsList(this, UPDATE, op[key]); + } + + // Crud spec update format + if (op.updateOne || op.updateMany || op.replaceOne) { + if (op.replaceOne && hasAtomicOperators(op[key].replacement)) { + throw new TypeError('Replacement document must not use atomic operators'); + } else if ((op.updateOne || op.updateMany) && !hasAtomicOperators(op[key].update)) { + throw new TypeError('Update document requires atomic operators'); + } + + const multi = op.updateOne || op.replaceOne ? false : true; + const operation = { + q: op[key].filter, + u: op[key].update || op[key].replacement, + multi: multi + }; + + if (op[key].hint) { + operation.hint = op[key].hint; + } + + if (this.isOrdered) { + operation.upsert = op[key].upsert ? true : false; + if (op.collation) operation.collation = op.collation; + } else { + if (op[key].upsert) operation.upsert = true; + } + if (op[key].arrayFilters) { + // TODO [$5f5fbe42fcabad09c1c2419b]: this check should be done at command construction against a connection, not a topology + if (maxWireVersion(this.s.topology) < 6) { + throw new TypeError('arrayFilters are only supported on MongoDB 3.6+'); + } + + operation.arrayFilters = op[key].arrayFilters; + } + + return this.s.options.addToOperationsList(this, UPDATE, operation); + } + + // Remove operations + if ( + op.removeOne || + op.removeMany || + (op.deleteOne && op.deleteOne.q) || + (op.deleteMany && op.deleteMany.q) + ) { + op[key].limit = op.removeOne ? 1 : 0; + return this.s.options.addToOperationsList(this, REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if (op.deleteOne || op.deleteMany) { + const limit = op.deleteOne ? 1 : 0; + const operation = { q: op[key].filter, limit: limit }; + if (op[key].hint) { + operation.hint = op[key].hint; + } + if (this.isOrdered) { + if (op.collation) operation.collation = op.collation; + } + return this.s.options.addToOperationsList(this, REMOVE, operation); + } + + // Insert operations + if (op.insertOne && op.insertOne.document == null) { + if (forceServerObjectId !== true && op.insertOne._id == null) + op.insertOne._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, op.insertOne); + } else if (op.insertOne && op.insertOne.document) { + if (forceServerObjectId !== true && op.insertOne.document._id == null) + op.insertOne.document._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document); + } + + if (op.insertMany) { + for (let i = 0; i < op.insertMany.length; i++) { + if (forceServerObjectId !== true && op.insertMany[i]._id == null) + op.insertMany[i]._id = new ObjectID(); + this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError( + 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' + ); + } + + /** + * helper function to assist with promiseOrCallback behavior + * @ignore + * @param {*} err + * @param {*} callback + */ + _handleEarlyError(err, callback) { + if (typeof callback === 'function') { + callback(err, null); + return; + } + + return this.s.promiseLibrary.reject(err); + } + + /** + * An internal helper method. Do not invoke directly. Will be going away in the future + * + * @ignore + * @method + * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation + * @param {object} writeConcern + * @param {object} options + * @param {function} callback + */ + bulkExecute(_writeConcern, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (typeof _writeConcern === 'function') { + callback = _writeConcern; + } else if (_writeConcern && typeof _writeConcern === 'object') { + this.s.writeConcern = _writeConcern; + } + + if (this.s.executed) { + const executedError = toError('batch cannot be re-executed'); + return this._handleEarlyError(executedError, callback); + } + + // If we have current batch + if (this.isOrdered) { + if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + } + // If we have no operations in the bulk raise an error + if (this.s.batches.length === 0) { + const emptyBatchError = toError('Invalid Operation, no operations specified'); + return this._handleEarlyError(emptyBatchError, callback); + } + return { options, callback }; + } + + /** + * The callback format for results + * @callback BulkOperationBase~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + + /** + * Execute the bulk operation + * + * @method + * @param {WriteConcern} [_writeConcern] Optional write concern. Can also be specified through options. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {BulkOperationBase~resultCallback} [callback] A callback that will be invoked when bulkWrite finishes/errors + * @throws {MongoError} Throws error if the bulk object has already been executed + * @throws {MongoError} Throws error if the bulk object does not have any operations + * @return {Promise|void} returns Promise if no callback passed + */ + execute(_writeConcern, options, callback) { + const ret = this.bulkExecute(_writeConcern, options, callback); + if (!ret || isPromiseLike(ret)) { + return ret; + } + + options = ret.options; + callback = ret.callback; + + return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]); + } + + /** + * Handles final options before executing command + * + * An internal method. Do not invoke. Will not be accessible in the future + * + * @ignore + * @param {object} config + * @param {object} config.options + * @param {number} config.batch + * @param {function} config.resultHandler + * @param {function} callback + */ + finalOptionsHandler(config, callback) { + const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options); + if (this.s.writeConcern != null) { + finalOptions.writeConcern = this.s.writeConcern; + } + + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + + // Set an operationIf if provided + if (this.operationId) { + config.resultHandler.operationId = this.operationId; + } + + // Serialize functions + if (this.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true; + } + + // Ignore undefined + if (this.s.options.ignoreUndefined) { + finalOptions.ignoreUndefined = true; + } + + // Is the bypassDocumentValidation options specific + if (this.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + + // Is the checkKeys option disabled + if (this.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + + if (finalOptions.retryWrites) { + if (config.batch.batchType === UPDATE) { + finalOptions.retryWrites = + finalOptions.retryWrites && !config.batch.operations.some(op => op.multi); + } + + if (config.batch.batchType === REMOVE) { + finalOptions.retryWrites = + finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0); + } + } + + try { + if (config.batch.batchType === INSERT) { + this.s.topology.insert( + this.s.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } else if (config.batch.batchType === UPDATE) { + this.s.topology.update( + this.s.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } else if (config.batch.batchType === REMOVE) { + this.s.topology.remove( + this.s.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } + } catch (err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + handleCallback(callback, null, mergeBatchResults(config.batch, this.s.bulkResult, err, null)); + } + } + + /** + * Handles the write error before executing commands + * + * An internal helper method. Do not invoke directly. Will be going away in the future + * + * @ignore + * @param {function} callback + * @param {BulkWriteResult} writeResult + * @param {class} self either OrderedBulkOperation or UnorderedBulkOperation + */ + handleWriteError(callback, writeResult) { + if (this.s.bulkResult.writeErrors.length > 0) { + const msg = this.s.bulkResult.writeErrors[0].errmsg + ? this.s.bulkResult.writeErrors[0].errmsg + : 'write operation failed'; + + handleCallback( + callback, + new BulkWriteError( + toError({ + message: msg, + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }), + writeResult + ), + null + ); + return true; + } + + if (writeResult.getWriteConcernError()) { + handleCallback( + callback, + new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), + null + ); + return true; + } + } +} + +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +// Exports symbols +module.exports = { + Batch, + BulkOperationBase, + bson, + INSERT: INSERT, + UPDATE: UPDATE, + REMOVE: REMOVE, + BulkWriteError +}; + + +/***/ }), + +/***/ 5035: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const common = __webpack_require__(4239); +const BulkOperationBase = common.BulkOperationBase; +const Batch = common.Batch; +const bson = common.bson; +const utils = __webpack_require__(1371); +const toError = utils.toError; + +/** + * Add to internal list of Operations + * + * @ignore + * @param {OrderedBulkOperation} bulkOperation + * @param {number} docType number indicating the document type + * @param {object} document + * @return {OrderedBulkOperation} + */ +function addToOperationsList(bulkOperation, docType, document) { + // Get the bsonSize + const bsonSize = bson.calculateObjectSize(document, { + checkKeys: false, + + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + }); + + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= bulkOperation.s.maxBsonObjectSize) + throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBsonObjectSize); + + // Create a new batch object if we don't have a current one + if (bulkOperation.s.currentBatch == null) + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + const maxKeySize = bulkOperation.s.maxKeySize; + + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (bulkOperation.s.currentBatchSize > 0 && + bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >= + bulkOperation.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + bulkOperation.s.currentBatch.batchType !== docType + ) { + // Save the batch to the execution stack + bulkOperation.s.batches.push(bulkOperation.s.currentBatch); + + // Create a new batch + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + // Reset the current size trackers + bulkOperation.s.currentBatchSize = 0; + bulkOperation.s.currentBatchSizeBytes = 0; + } + + if (docType === common.INSERT) { + bulkOperation.s.bulkResult.insertedIds.push({ + index: bulkOperation.s.currentIndex, + _id: document._id + }); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw toError('operation passed in cannot be an Array'); + } + + bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); + bulkOperation.s.currentBatch.operations.push(document); + bulkOperation.s.currentBatchSize += 1; + bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize; + bulkOperation.s.currentIndex += 1; + + // Return bulkOperation + return bulkOperation; +} + +/** + * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @extends BulkOperationBase + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation} a OrderedBulkOperation instance. + */ +class OrderedBulkOperation extends BulkOperationBase { + constructor(topology, collection, options) { + options = options || {}; + options = Object.assign(options, { addToOperationsList }); + + super(topology, collection, options, true); + } +} + +/** + * Returns an unordered batch object + * @ignore + */ +function initializeOrderedBulkOp(topology, collection, options) { + return new OrderedBulkOperation(topology, collection, options); +} + +initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; +module.exports = initializeOrderedBulkOp; +module.exports.Bulk = OrderedBulkOperation; + + +/***/ }), + +/***/ 325: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const common = __webpack_require__(4239); +const BulkOperationBase = common.BulkOperationBase; +const Batch = common.Batch; +const bson = common.bson; +const utils = __webpack_require__(1371); +const toError = utils.toError; + +/** + * Add to internal list of Operations + * + * @ignore + * @param {UnorderedBulkOperation} bulkOperation + * @param {number} docType number indicating the document type + * @param {object} document + * @return {UnorderedBulkOperation} + */ +function addToOperationsList(bulkOperation, docType, document) { + // Get the bsonSize + const bsonSize = bson.calculateObjectSize(document, { + checkKeys: false, + + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + }); + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= bulkOperation.s.maxBsonObjectSize) + throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBsonObjectSize); + // Holds the current batch + bulkOperation.s.currentBatch = null; + // Get the right type of batch + if (docType === common.INSERT) { + bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch; + } else if (docType === common.UPDATE) { + bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch; + } else if (docType === common.REMOVE) { + bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch; + } + + const maxKeySize = bulkOperation.s.maxKeySize; + + // Create a new batch object if we don't have a current one + if (bulkOperation.s.currentBatch == null) + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (bulkOperation.s.currentBatch.size > 0 && + bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= + bulkOperation.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + bulkOperation.s.currentBatch.batchType !== docType + ) { + // Save the batch to the execution stack + bulkOperation.s.batches.push(bulkOperation.s.currentBatch); + + // Create a new batch + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw toError('operation passed in cannot be an Array'); + } + + bulkOperation.s.currentBatch.operations.push(document); + bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); + bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; + + // Save back the current Batch to the right type + if (docType === common.INSERT) { + bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch; + bulkOperation.s.bulkResult.insertedIds.push({ + index: bulkOperation.s.bulkResult.insertedIds.length, + _id: document._id + }); + } else if (docType === common.UPDATE) { + bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch; + } else if (docType === common.REMOVE) { + bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch; + } + + // Update current batch size + bulkOperation.s.currentBatch.size += 1; + bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize; + + // Return bulkOperation + return bulkOperation; +} + +/** + * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @extends BulkOperationBase + * @property {number} length Get the number of operations in the bulk. + * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. + */ +class UnorderedBulkOperation extends BulkOperationBase { + constructor(topology, collection, options) { + options = options || {}; + options = Object.assign(options, { addToOperationsList }); + + super(topology, collection, options, false); + } + + handleWriteError(callback, writeResult) { + if (this.s.batches.length) { + return false; + } + + return super.handleWriteError(callback, writeResult); + } +} + +/** + * Returns an unordered batch object + * @ignore + */ +function initializeUnorderedBulkOp(topology, collection, options) { + return new UnorderedBulkOperation(topology, collection, options); +} + +initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; +module.exports = initializeUnorderedBulkOp; +module.exports.Bulk = UnorderedBulkOperation; + + +/***/ }), + +/***/ 1117: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Denque = __webpack_require__(2342); +const EventEmitter = __webpack_require__(8614); +const isResumableError = __webpack_require__(9386).isResumableError; +const MongoError = __webpack_require__(3994).MongoError; +const Cursor = __webpack_require__(7159); +const relayEvents = __webpack_require__(1178).relayEvents; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const maybePromise = __webpack_require__(1371).maybePromise; +const now = __webpack_require__(1371).now; +const calculateDurationInMs = __webpack_require__(1371).calculateDurationInMs; +const AggregateOperation = __webpack_require__(1554); + +const kResumeQueue = Symbol('resumeQueue'); + +const CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument']; +const CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat( + CHANGE_STREAM_OPTIONS +); + +const CHANGE_DOMAIN_TYPES = { + COLLECTION: Symbol('Collection'), + DATABASE: Symbol('Database'), + CLUSTER: Symbol('Cluster') +}; + +/** + * @typedef ResumeToken + * @description Represents the logical starting point for a new or resuming {@link ChangeStream} on the server. + * @see https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token + */ + +/** + * @typedef OperationTime + * @description Represents a specific point in time on a server. Can be retrieved by using {@link Db#command} + * @see https://docs.mongodb.com/manual/reference/method/db.runCommand/#response + */ + +/** + * @typedef ChangeStreamOptions + * @description Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. + * @property {string} [fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @property {number} [maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query. + * @property {ResumeToken} [resumeAfter] Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}. + * @property {ResumeToken} [startAfter] Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}. + * @property {OperationTime} [startAtOperationTime] Will start the changeStream after the specified operationTime. + * @property {number} [batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @property {object} [collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @property {ReadPreference} [readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + */ + +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @class ChangeStream + * @since 3.0.0 + * @param {(MongoClient|Db|Collection)} parent The parent object that created this change stream + * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents + * @param {ChangeStreamOptions} [options] Optional settings + * @fires ChangeStream#close + * @fires ChangeStream#change + * @fires ChangeStream#end + * @fires ChangeStream#error + * @fires ChangeStream#resumeTokenChanged + * @return {ChangeStream} a ChangeStream instance. + */ +class ChangeStream extends EventEmitter { + constructor(parent, pipeline, options) { + super(); + const Collection = __webpack_require__(5193); + const Db = __webpack_require__(6662); + const MongoClient = __webpack_require__(1545); + + this.pipeline = pipeline || []; + this.options = options || {}; + + this.parent = parent; + this.namespace = parent.s.namespace; + if (parent instanceof Collection) { + this.type = CHANGE_DOMAIN_TYPES.COLLECTION; + this.topology = parent.s.db.serverConfig; + } else if (parent instanceof Db) { + this.type = CHANGE_DOMAIN_TYPES.DATABASE; + this.topology = parent.serverConfig; + } else if (parent instanceof MongoClient) { + this.type = CHANGE_DOMAIN_TYPES.CLUSTER; + this.topology = parent.topology; + } else { + throw new TypeError( + 'parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient' + ); + } + + this.promiseLibrary = parent.s.promiseLibrary; + if (!this.options.readPreference && parent.s.readPreference) { + this.options.readPreference = parent.s.readPreference; + } + + this[kResumeQueue] = new Denque(); + + // Create contained Change Stream cursor + this.cursor = createChangeStreamCursor(this, options); + + this.closed = false; + + // Listen for any `change` listeners being added to ChangeStream + this.on('newListener', eventName => { + if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { + this.cursor.on('data', change => processNewChange(this, change)); + } + }); + + // Listen for all `change` listeners being removed from ChangeStream + this.on('removeListener', eventName => { + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + this.cursor.removeAllListeners('data'); + } + }); + } + + /** + * @property {ResumeToken} resumeToken + * The cached resume token that will be used to resume + * after the most recently returned change. + */ + get resumeToken() { + return this.cursor.resumeToken; + } + + /** + * Check if there is any document still available in the Change Stream + * @function ChangeStream.prototype.hasNext + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @returns {Promise|void} returns Promise if no callback passed + */ + hasNext(callback) { + return maybePromise(this.parent, callback, cb => { + getCursor(this, (err, cursor) => { + if (err) return cb(err); // failed to resume, raise an error + cursor.hasNext(cb); + }); + }); + } + + /** + * Get the next available document from the Change Stream, returns null if no more documents are available. + * @function ChangeStream.prototype.next + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @returns {Promise|void} returns Promise if no callback passed + */ + next(callback) { + return maybePromise(this.parent, callback, cb => { + getCursor(this, (err, cursor) => { + if (err) return cb(err); // failed to resume, raise an error + cursor.next((error, change) => { + if (error) { + this[kResumeQueue].push(() => this.next(cb)); + processError(this, error, cb); + return; + } + processNewChange(this, change, cb); + }); + }); + }); + } + + /** + * Is the change stream closed + * @method ChangeStream.prototype.isClosed + * @return {boolean} + */ + isClosed() { + return this.closed || (this.cursor && this.cursor.isClosed()); + } + + /** + * Close the Change Stream + * @method ChangeStream.prototype.close + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + close(callback) { + return maybePromise(this.parent, callback, cb => { + if (this.closed) return cb(); + + // flag the change stream as explicitly closed + this.closed = true; + + if (!this.cursor) return cb(); + + // Tidy up the existing cursor + const cursor = this.cursor; + + return cursor.close(err => { + ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); + this.cursor = undefined; + + return cb(err); + }); + }); + } + + /** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @method + * @param {Writable} destination The destination for writing data + * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} + * @return {null} + */ + pipe(destination, options) { + if (!this.pipeDestinations) { + this.pipeDestinations = []; + } + this.pipeDestinations.push(destination); + return this.cursor.pipe(destination, options); + } + + /** + * This method will remove the hooks set up for a previous pipe() call. + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + unpipe(destination) { + if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { + this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); + } + return this.cursor.unpipe(destination); + } + + /** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + */ + stream(options) { + this.streamOptions = options; + return this.cursor.stream(options); + } + + /** + * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @return {null} + */ + pause() { + return this.cursor.pause(); + } + + /** + * This method will cause the readable stream to resume emitting data events. + * @return {null} + */ + resume() { + return this.cursor.resume(); + } +} + +class ChangeStreamCursor extends Cursor { + constructor(topology, operation, options) { + super(topology, operation, options); + + options = options || {}; + this._resumeToken = null; + this.startAtOperationTime = options.startAtOperationTime; + + if (options.startAfter) { + this.resumeToken = options.startAfter; + } else if (options.resumeAfter) { + this.resumeToken = options.resumeAfter; + } + } + + set resumeToken(token) { + this._resumeToken = token; + this.emit('resumeTokenChanged', token); + } + + get resumeToken() { + return this._resumeToken; + } + + get resumeOptions() { + const result = {}; + for (const optionName of CURSOR_OPTIONS) { + if (this.options[optionName]) result[optionName] = this.options[optionName]; + } + + if (this.resumeToken || this.startAtOperationTime) { + ['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => delete result[key]); + + if (this.resumeToken) { + const resumeKey = + this.options.startAfter && !this.hasReceived ? 'startAfter' : 'resumeAfter'; + result[resumeKey] = this.resumeToken; + } else if (this.startAtOperationTime && maxWireVersion(this.server) >= 7) { + result.startAtOperationTime = this.startAtOperationTime; + } + } + + return result; + } + + cacheResumeToken(resumeToken) { + if (this.bufferedCount() === 0 && this.cursorState.postBatchResumeToken) { + this.resumeToken = this.cursorState.postBatchResumeToken; + } else { + this.resumeToken = resumeToken; + } + this.hasReceived = true; + } + + _processBatch(batchName, response) { + const cursor = response.cursor; + if (cursor.postBatchResumeToken) { + this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; + + if (cursor[batchName].length === 0) { + this.resumeToken = cursor.postBatchResumeToken; + } + } + } + + _initializeCursor(callback) { + super._initializeCursor((err, result) => { + if (err || result == null) { + callback(err, result); + return; + } + + const response = result.documents[0]; + + if ( + this.startAtOperationTime == null && + this.resumeAfter == null && + this.startAfter == null && + maxWireVersion(this.server) >= 7 + ) { + this.startAtOperationTime = response.operationTime; + } + + this._processBatch('firstBatch', response); + + this.emit('init', result); + this.emit('response'); + callback(err, result); + }); + } + + _getMore(callback) { + super._getMore((err, response) => { + if (err) { + callback(err); + return; + } + + this._processBatch('nextBatch', response); + + this.emit('more', response); + this.emit('response'); + callback(err, response); + }); + } +} + +/** + * @event ChangeStreamCursor#response + * internal event DO NOT USE + * @ignore + */ + +// Create a new change stream cursor based on self's configuration +function createChangeStreamCursor(self, options) { + const changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' }; + applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS); + if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) { + changeStreamStageOptions.allChangesForCluster = true; + } + + const pipeline = [{ $changeStream: changeStreamStageOptions }].concat(self.pipeline); + const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS); + + const changeStreamCursor = new ChangeStreamCursor( + self.topology, + new AggregateOperation(self.parent, pipeline, options), + cursorOptions + ); + + relayEvents(changeStreamCursor, self, ['resumeTokenChanged', 'end', 'close']); + + /** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * + * @event ChangeStream#change + * @type {object} + */ + if (self.listenerCount('change') > 0) { + changeStreamCursor.on('data', function(change) { + processNewChange(self, change); + }); + } + + /** + * Change stream close event + * + * @event ChangeStream#close + * @type {null} + */ + + /** + * Change stream end event + * + * @event ChangeStream#end + * @type {null} + */ + + /** + * Emitted each time the change stream stores a new resume token. + * + * @event ChangeStream#resumeTokenChanged + * @type {ResumeToken} + */ + + /** + * Fired when the stream encounters an error. + * + * @event ChangeStream#error + * @type {Error} + */ + changeStreamCursor.on('error', function(error) { + processError(self, error); + }); + + if (self.pipeDestinations) { + const cursorStream = changeStreamCursor.stream(self.streamOptions); + for (let pipeDestination in self.pipeDestinations) { + cursorStream.pipe(pipeDestination); + } + } + + return changeStreamCursor; +} + +function applyKnownOptions(target, source, optionNames) { + optionNames.forEach(name => { + if (source[name]) { + target[name] = source[name]; + } + }); + + return target; +} + +// This method performs a basic server selection loop, satisfying the requirements of +// ChangeStream resumability until the new SDAM layer can be used. +const SELECTION_TIMEOUT = 30000; +function waitForTopologyConnected(topology, options, callback) { + setTimeout(() => { + if (options && options.start == null) { + options.start = now(); + } + + const start = options.start || now(); + const timeout = options.timeout || SELECTION_TIMEOUT; + const readPreference = options.readPreference; + if (topology.isConnected({ readPreference })) { + return callback(); + } + + if (calculateDurationInMs(start) > timeout) { + return callback(new MongoError('Timed out waiting for connection')); + } + + waitForTopologyConnected(topology, options, callback); + }, 500); // this is an arbitrary wait time to allow SDAM to transition +} + +function processNewChange(changeStream, change, callback) { + const cursor = changeStream.cursor; + + // a null change means the cursor has been notified, implicitly closing the change stream + if (change == null) { + changeStream.closed = true; + } + + if (changeStream.closed) { + if (callback) callback(new MongoError('ChangeStream is closed')); + return; + } + + if (change && !change._id) { + const noResumeTokenError = new Error( + 'A change stream document has been received that lacks a resume token (_id).' + ); + + if (!callback) return changeStream.emit('error', noResumeTokenError); + return callback(noResumeTokenError); + } + + // cache the resume token + cursor.cacheResumeToken(change._id); + + // wipe the startAtOperationTime if there was one so that there won't be a conflict + // between resumeToken and startAtOperationTime if we need to reconnect the cursor + changeStream.options.startAtOperationTime = undefined; + + // Return the change + if (!callback) return changeStream.emit('change', change); + return callback(undefined, change); +} + +function processError(changeStream, error, callback) { + const topology = changeStream.topology; + const cursor = changeStream.cursor; + + // If the change stream has been closed explictly, do not process error. + if (changeStream.closed) { + if (callback) callback(new MongoError('ChangeStream is closed')); + return; + } + + // if the resume succeeds, continue with the new cursor + function resumeWithCursor(newCursor) { + changeStream.cursor = newCursor; + processResumeQueue(changeStream); + } + + // otherwise, raise an error and close the change stream + function unresumableError(err) { + if (!callback) { + changeStream.emit('error', err); + changeStream.emit('close'); + } + processResumeQueue(changeStream, err); + changeStream.closed = true; + } + + if (cursor && isResumableError(error, maxWireVersion(cursor.server))) { + changeStream.cursor = undefined; + + // stop listening to all events from old cursor + ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); + + // close internal cursor, ignore errors + cursor.close(); + + waitForTopologyConnected(topology, { readPreference: cursor.options.readPreference }, err => { + // if the topology can't reconnect, close the stream + if (err) return unresumableError(err); + + // create a new cursor, preserving the old cursor's options + const newCursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); + + // attempt to continue in emitter mode + if (!callback) return resumeWithCursor(newCursor); + + // attempt to continue in iterator mode + newCursor.hasNext(err => { + // if there's an error immediately after resuming, close the stream + if (err) return unresumableError(err); + resumeWithCursor(newCursor); + }); + }); + return; + } + + if (!callback) return changeStream.emit('error', error); + return callback(error); +} + +/** + * Safely provides a cursor across resume attempts + * + * @param {ChangeStream} changeStream the parent ChangeStream + * @param {function} callback gets the cursor or error + * @param {ChangeStreamCursor} [oldCursor] when resuming from an error, carry over options from previous cursor + */ +function getCursor(changeStream, callback) { + if (changeStream.isClosed()) { + callback(new MongoError('ChangeStream is closed.')); + return; + } + + // if a cursor exists and it is open, return it + if (changeStream.cursor) { + callback(undefined, changeStream.cursor); + return; + } + + // no cursor, queue callback until topology reconnects + changeStream[kResumeQueue].push(callback); +} + +/** + * Drain the resume queue when a new has become available + * + * @param {ChangeStream} changeStream the parent ChangeStream + * @param {ChangeStreamCursor?} changeStream.cursor the new cursor + * @param {Error} [err] error getting a new cursor + */ +function processResumeQueue(changeStream, err) { + while (changeStream[kResumeQueue].length) { + const request = changeStream[kResumeQueue].pop(); + if (changeStream.isClosed() && !err) { + request(new MongoError('Change Stream is not open.')); + return; + } + request(err, changeStream.cursor); + } +} + +/** + * The callback format for results + * @callback ChangeStream~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +module.exports = ChangeStream; + + +/***/ }), + +/***/ 9820: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const EventEmitter = __webpack_require__(8614); +const MessageStream = __webpack_require__(2425); +const MongoError = __webpack_require__(3111).MongoError; +const MongoNetworkError = __webpack_require__(3111).MongoNetworkError; +const MongoNetworkTimeoutError = __webpack_require__(3111).MongoNetworkTimeoutError; +const MongoWriteConcernError = __webpack_require__(3111).MongoWriteConcernError; +const CommandResult = __webpack_require__(2337); +const StreamDescription = __webpack_require__(6292).StreamDescription; +const wp = __webpack_require__(9206); +const apm = __webpack_require__(9815); +const updateSessionFromResponse = __webpack_require__(5474).updateSessionFromResponse; +const uuidV4 = __webpack_require__(1178).uuidV4; +const now = __webpack_require__(1371).now; +const calculateDurationInMs = __webpack_require__(1371).calculateDurationInMs; + +const kStream = Symbol('stream'); +const kQueue = Symbol('queue'); +const kMessageStream = Symbol('messageStream'); +const kGeneration = Symbol('generation'); +const kLastUseTime = Symbol('lastUseTime'); +const kClusterTime = Symbol('clusterTime'); +const kDescription = Symbol('description'); +const kIsMaster = Symbol('ismaster'); +const kAutoEncrypter = Symbol('autoEncrypter'); + +class Connection extends EventEmitter { + constructor(stream, options) { + super(options); + + this.id = options.id; + this.address = streamIdentifier(stream); + this.bson = options.bson; + this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; + this.host = options.host || 'localhost'; + this.port = options.port || 27017; + this.monitorCommands = + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false; + this.closed = false; + this.destroyed = false; + + this[kDescription] = new StreamDescription(this.address, options); + this[kGeneration] = options.generation; + this[kLastUseTime] = now(); + + // retain a reference to an `AutoEncrypter` if present + if (options.autoEncrypter) { + this[kAutoEncrypter] = options.autoEncrypter; + } + + // setup parser stream and message handling + this[kQueue] = new Map(); + this[kMessageStream] = new MessageStream(options); + this[kMessageStream].on('message', messageHandler(this)); + this[kStream] = stream; + stream.on('error', () => { + /* ignore errors, listen to `close` instead */ + }); + + stream.on('close', () => { + if (this.closed) { + return; + } + + this.closed = true; + this[kQueue].forEach(op => + op.cb(new MongoNetworkError(`connection ${this.id} to ${this.address} closed`)) + ); + this[kQueue].clear(); + + this.emit('close'); + }); + + stream.on('timeout', () => { + if (this.closed) { + return; + } + + stream.destroy(); + this.closed = true; + this[kQueue].forEach(op => + op.cb( + new MongoNetworkTimeoutError(`connection ${this.id} to ${this.address} timed out`, { + beforeHandshake: this[kIsMaster] == null + }) + ) + ); + + this[kQueue].clear(); + this.emit('close'); + }); + + // hook the message stream up to the passed in stream + stream.pipe(this[kMessageStream]); + this[kMessageStream].pipe(stream); + } + + get description() { + return this[kDescription]; + } + + get ismaster() { + return this[kIsMaster]; + } + + // the `connect` method stores the result of the handshake ismaster on the connection + set ismaster(response) { + this[kDescription].receiveResponse(response); + + // TODO [$5f5fbe42fcabad09c1c2419c]: remove this, and only use the `StreamDescription` in the future + this[kIsMaster] = response; + } + + get generation() { + return this[kGeneration] || 0; + } + + get idleTime() { + return calculateDurationInMs(this[kLastUseTime]); + } + + get clusterTime() { + return this[kClusterTime]; + } + + get stream() { + return this[kStream]; + } + + markAvailable() { + this[kLastUseTime] = now(); + } + + destroy(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = Object.assign({ force: false }, options); + if (this[kStream] == null || this.destroyed) { + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + + return; + } + + if (options.force) { + this[kStream].destroy(); + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + + return; + } + + this[kStream].end(err => { + this.destroyed = true; + if (typeof callback === 'function') { + callback(err); + } + }); + } + + // Wire protocol methods + command(ns, cmd, options, callback) { + wp.command(makeServerTrampoline(this), ns, cmd, options, callback); + } + + query(ns, cmd, cursorState, options, callback) { + wp.query(makeServerTrampoline(this), ns, cmd, cursorState, options, callback); + } + + getMore(ns, cursorState, batchSize, options, callback) { + wp.getMore(makeServerTrampoline(this), ns, cursorState, batchSize, options, callback); + } + + killCursors(ns, cursorState, callback) { + wp.killCursors(makeServerTrampoline(this), ns, cursorState, callback); + } + + insert(ns, ops, options, callback) { + wp.insert(makeServerTrampoline(this), ns, ops, options, callback); + } + + update(ns, ops, options, callback) { + wp.update(makeServerTrampoline(this), ns, ops, options, callback); + } + + remove(ns, ops, options, callback) { + wp.remove(makeServerTrampoline(this), ns, ops, options, callback); + } +} + +/// This lets us emulate a legacy `Server` instance so we can work with the existing wire +/// protocol methods. Eventually, the operation executor will return a `Connection` to execute +/// against. +function makeServerTrampoline(connection) { + const server = { + description: connection.description, + clusterTime: connection[kClusterTime], + s: { + bson: connection.bson, + pool: { write: write.bind(connection), isConnected: () => true } + } + }; + + if (connection[kAutoEncrypter]) { + server.autoEncrypter = connection[kAutoEncrypter]; + } + + return server; +} + +function messageHandler(conn) { + return function messageHandler(message) { + // always emit the message, in case we are streaming + conn.emit('message', message); + if (!conn[kQueue].has(message.responseTo)) { + return; + } + + const operationDescription = conn[kQueue].get(message.responseTo); + const callback = operationDescription.cb; + + // SERVER-45775: For exhaust responses we should be able to use the same requestId to + // track response, however the server currently synthetically produces remote requests + // making the `responseTo` change on each response + conn[kQueue].delete(message.responseTo); + if (message.moreToCome) { + // requeue the callback for next synthetic request + conn[kQueue].set(message.requestId, operationDescription); + } else if (operationDescription.socketTimeoutOverride) { + conn[kStream].setTimeout(conn.socketTimeout); + } + + try { + // Pass in the entire description because it has BSON parsing options + message.parse(operationDescription); + } catch (err) { + callback(new MongoError(err)); + return; + } + + if (message.documents[0]) { + const document = message.documents[0]; + const session = operationDescription.session; + if (session) { + updateSessionFromResponse(session, document); + } + + if (document.$clusterTime) { + conn[kClusterTime] = document.$clusterTime; + conn.emit('clusterTimeReceived', document.$clusterTime); + } + + if (operationDescription.command) { + if (document.writeConcernError) { + callback(new MongoWriteConcernError(document.writeConcernError, document)); + return; + } + + if (document.ok === 0 || document.$err || document.errmsg || document.code) { + callback(new MongoError(document)); + return; + } + } + } + + // NODE-2382: reenable in our glorious non-leaky abstraction future + // callback(null, operationDescription.fullResult ? message : message.documents[0]); + + callback( + undefined, + new CommandResult( + operationDescription.fullResult ? message : message.documents[0], + conn, + message + ) + ); + }; +} + +function streamIdentifier(stream) { + if (typeof stream.address === 'function') { + return `${stream.remoteAddress}:${stream.remotePort}`; + } + + return uuidV4().toString('hex'); +} + +// Not meant to be called directly, the wire protocol methods call this assuming it is a `Pool` instance +function write(command, options, callback) { + if (typeof options === 'function') { + callback = options; + } + + options = options || {}; + const operationDescription = { + requestId: command.requestId, + cb: callback, + session: options.session, + fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false, + noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false, + documentsReturnedIn: options.documentsReturnedIn, + command: !!options.command, + + // for BSON parsing + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + raw: typeof options.raw === 'boolean' ? options.raw : false + }; + + if (this[kDescription] && this[kDescription].compressor) { + operationDescription.agreedCompressor = this[kDescription].compressor; + + if (this[kDescription].zlibCompressionLevel) { + operationDescription.zlibCompressionLevel = this[kDescription].zlibCompressionLevel; + } + } + + if (typeof options.socketTimeout === 'number') { + operationDescription.socketTimeoutOverride = true; + this[kStream].setTimeout(options.socketTimeout); + } + + // if command monitoring is enabled we need to modify the callback here + if (this.monitorCommands) { + this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); + + operationDescription.started = now(); + operationDescription.cb = (err, reply) => { + if (err) { + this.emit( + 'commandFailed', + new apm.CommandFailedEvent(this, command, err, operationDescription.started) + ); + } else { + if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { + this.emit( + 'commandFailed', + new apm.CommandFailedEvent(this, command, reply.result, operationDescription.started) + ); + } else { + this.emit( + 'commandSucceeded', + new apm.CommandSucceededEvent(this, command, reply, operationDescription.started) + ); + } + } + + if (typeof callback === 'function') { + callback(err, reply); + } + }; + } + + if (!operationDescription.noResponse) { + this[kQueue].set(operationDescription.requestId, operationDescription); + } + + try { + this[kMessageStream].writeCommand(command, operationDescription); + } catch (e) { + if (!operationDescription.noResponse) { + this[kQueue].delete(operationDescription.requestId); + operationDescription.cb(e); + return; + } + } + + if (operationDescription.noResponse) { + operationDescription.cb(); + } +} + +module.exports = { + Connection +}; + + +/***/ }), + +/***/ 2529: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Denque = __webpack_require__(2342); +const EventEmitter = __webpack_require__(8614).EventEmitter; +const Logger = __webpack_require__(104); +const makeCounter = __webpack_require__(1371).makeCounter; +const MongoError = __webpack_require__(3111).MongoError; +const Connection = __webpack_require__(9820).Connection; +const eachAsync = __webpack_require__(1178).eachAsync; +const connect = __webpack_require__(6573); +const relayEvents = __webpack_require__(1178).relayEvents; + +const errors = __webpack_require__(2926); +const PoolClosedError = errors.PoolClosedError; +const WaitQueueTimeoutError = errors.WaitQueueTimeoutError; + +const events = __webpack_require__(897); +const ConnectionPoolCreatedEvent = events.ConnectionPoolCreatedEvent; +const ConnectionPoolClosedEvent = events.ConnectionPoolClosedEvent; +const ConnectionCreatedEvent = events.ConnectionCreatedEvent; +const ConnectionReadyEvent = events.ConnectionReadyEvent; +const ConnectionClosedEvent = events.ConnectionClosedEvent; +const ConnectionCheckOutStartedEvent = events.ConnectionCheckOutStartedEvent; +const ConnectionCheckOutFailedEvent = events.ConnectionCheckOutFailedEvent; +const ConnectionCheckedOutEvent = events.ConnectionCheckedOutEvent; +const ConnectionCheckedInEvent = events.ConnectionCheckedInEvent; +const ConnectionPoolClearedEvent = events.ConnectionPoolClearedEvent; + +const kLogger = Symbol('logger'); +const kConnections = Symbol('connections'); +const kPermits = Symbol('permits'); +const kMinPoolSizeTimer = Symbol('minPoolSizeTimer'); +const kGeneration = Symbol('generation'); +const kConnectionCounter = Symbol('connectionCounter'); +const kCancellationToken = Symbol('cancellationToken'); +const kWaitQueue = Symbol('waitQueue'); +const kCancelled = Symbol('cancelled'); + +const VALID_POOL_OPTIONS = new Set([ + // `connect` options + 'ssl', + 'bson', + 'connectionType', + 'monitorCommands', + 'socketTimeout', + 'credentials', + 'compression', + + // node Net options + 'host', + 'port', + 'localAddress', + 'localPort', + 'family', + 'hints', + 'lookup', + 'path', + + // node TLS options + 'ca', + 'cert', + 'sigalgs', + 'ciphers', + 'clientCertEngine', + 'crl', + 'dhparam', + 'ecdhCurve', + 'honorCipherOrder', + 'key', + 'privateKeyEngine', + 'privateKeyIdentifier', + 'maxVersion', + 'minVersion', + 'passphrase', + 'pfx', + 'secureOptions', + 'secureProtocol', + 'sessionIdContext', + 'allowHalfOpen', + 'rejectUnauthorized', + 'pskCallback', + 'ALPNProtocols', + 'servername', + 'checkServerIdentity', + 'session', + 'minDHSize', + 'secureContext', + + // spec options + 'maxPoolSize', + 'minPoolSize', + 'maxIdleTimeMS', + 'waitQueueTimeoutMS' +]); + +function resolveOptions(options, defaults) { + const newOptions = Array.from(VALID_POOL_OPTIONS).reduce((obj, key) => { + if (options.hasOwnProperty(key)) { + obj[key] = options[key]; + } + + return obj; + }, {}); + + return Object.freeze(Object.assign({}, defaults, newOptions)); +} + +/** + * Configuration options for drivers wrapping the node driver. + * + * @typedef {Object} ConnectionPoolOptions + * @property + * @property {string} [host] The host to connect to + * @property {number} [port] The port to connect to + * @property {bson} [bson] The BSON instance to use for new connections + * @property {number} [maxPoolSize=100] The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. + * @property {number} [minPoolSize=0] The minimum number of connections that MUST exist at any moment in a single connection pool. + * @property {number} [maxIdleTimeMS] The maximum amount of time a connection should remain idle in the connection pool before being marked idle. + * @property {number} [waitQueueTimeoutMS=0] The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. + */ + +/** + * A pool of connections which dynamically resizes, and emit events related to pool activity + * + * @property {number} generation An integer representing the SDAM generation of the pool + * @property {number} totalConnectionCount An integer expressing how many total connections (active + in use) the pool currently has + * @property {number} availableConnectionCount An integer expressing how many connections are currently available in the pool. + * @property {string} address The address of the endpoint the pool is connected to + * + * @emits ConnectionPool#connectionPoolCreated + * @emits ConnectionPool#connectionPoolClosed + * @emits ConnectionPool#connectionCreated + * @emits ConnectionPool#connectionReady + * @emits ConnectionPool#connectionClosed + * @emits ConnectionPool#connectionCheckOutStarted + * @emits ConnectionPool#connectionCheckOutFailed + * @emits ConnectionPool#connectionCheckedOut + * @emits ConnectionPool#connectionCheckedIn + * @emits ConnectionPool#connectionPoolCleared + */ +class ConnectionPool extends EventEmitter { + /** + * Create a new Connection Pool + * + * @param {ConnectionPoolOptions} options + */ + constructor(options) { + super(); + options = options || {}; + + this.closed = false; + this.options = resolveOptions(options, { + connectionType: Connection, + maxPoolSize: typeof options.maxPoolSize === 'number' ? options.maxPoolSize : 100, + minPoolSize: typeof options.minPoolSize === 'number' ? options.minPoolSize : 0, + maxIdleTimeMS: typeof options.maxIdleTimeMS === 'number' ? options.maxIdleTimeMS : 0, + waitQueueTimeoutMS: + typeof options.waitQueueTimeoutMS === 'number' ? options.waitQueueTimeoutMS : 0, + autoEncrypter: options.autoEncrypter, + metadata: options.metadata + }); + + if (options.minSize > options.maxSize) { + throw new TypeError( + 'Connection pool minimum size must not be greater than maxiumum pool size' + ); + } + + this[kLogger] = Logger('ConnectionPool', options); + this[kConnections] = new Denque(); + this[kPermits] = this.options.maxPoolSize; + this[kMinPoolSizeTimer] = undefined; + this[kGeneration] = 0; + this[kConnectionCounter] = makeCounter(1); + this[kCancellationToken] = new EventEmitter(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kWaitQueue] = new Denque(); + + process.nextTick(() => { + this.emit('connectionPoolCreated', new ConnectionPoolCreatedEvent(this)); + ensureMinPoolSize(this); + }); + } + + get address() { + return `${this.options.host}:${this.options.port}`; + } + + get generation() { + return this[kGeneration]; + } + + get totalConnectionCount() { + return this[kConnections].length + (this.options.maxPoolSize - this[kPermits]); + } + + get availableConnectionCount() { + return this[kConnections].length; + } + + get waitQueueSize() { + return this[kWaitQueue].length; + } + + /** + * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it + * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or + * explicitly destroyed by the new owner. + * + * @param {ConnectionPool~checkOutCallback} callback + */ + checkOut(callback) { + this.emit('connectionCheckOutStarted', new ConnectionCheckOutStartedEvent(this)); + + if (this.closed) { + this.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(this, 'poolClosed')); + callback(new PoolClosedError(this)); + return; + } + + const waitQueueMember = { callback }; + + const pool = this; + const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS; + if (waitQueueTimeoutMS) { + waitQueueMember.timer = setTimeout(() => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timer = undefined; + + pool.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(pool, 'timeout')); + waitQueueMember.callback(new WaitQueueTimeoutError(pool)); + }, waitQueueTimeoutMS); + } + + this[kWaitQueue].push(waitQueueMember); + setImmediate(() => processWaitQueue(this)); + } + + /** + * Check a connection into the pool. + * + * @param {Connection} connection The connection to check in + */ + checkIn(connection) { + const poolClosed = this.closed; + const stale = connectionIsStale(this, connection); + const willDestroy = !!(poolClosed || stale || connection.closed); + + if (!willDestroy) { + connection.markAvailable(); + this[kConnections].push(connection); + } + + this.emit('connectionCheckedIn', new ConnectionCheckedInEvent(this, connection)); + + if (willDestroy) { + const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; + destroyConnection(this, connection, reason); + } + + setImmediate(() => processWaitQueue(this)); + } + + /** + * Clear the pool + * + * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a + * previous generation will eventually be pruned during subsequent checkouts. + */ + clear() { + this[kGeneration] += 1; + this.emit('connectionPoolCleared', new ConnectionPoolClearedEvent(this)); + } + + /** + * Close the pool + * + * @param {object} [options] Optional settings + * @param {boolean} [options.force] Force close connections + * @param {Function} callback + */ + close(options, callback) { + if (typeof options === 'function') { + callback = options; + } + + options = Object.assign({ force: false }, options); + if (this.closed) { + return callback(); + } + + // immediately cancel any in-flight connections + this[kCancellationToken].emit('cancel'); + + // drain the wait queue + while (this.waitQueueSize) { + const waitQueueMember = this[kWaitQueue].pop(); + clearTimeout(waitQueueMember.timer); + if (!waitQueueMember[kCancelled]) { + waitQueueMember.callback(new MongoError('connection pool closed')); + } + } + + // clear the min pool size timer + if (this[kMinPoolSizeTimer]) { + clearTimeout(this[kMinPoolSizeTimer]); + } + + // end the connection counter + if (typeof this[kConnectionCounter].return === 'function') { + this[kConnectionCounter].return(); + } + + // mark the pool as closed immediately + this.closed = true; + + eachAsync( + this[kConnections].toArray(), + (conn, cb) => { + this.emit('connectionClosed', new ConnectionClosedEvent(this, conn, 'poolClosed')); + conn.destroy(options, cb); + }, + err => { + this[kConnections].clear(); + this.emit('connectionPoolClosed', new ConnectionPoolClosedEvent(this)); + callback(err); + } + ); + } + + /** + * Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda + * has completed by calling back. + * + * NOTE: please note the required signature of `fn` + * + * @param {ConnectionPool~withConnectionCallback} fn A function which operates on a managed connection + * @param {Function} callback The original callback + * @return {Promise} + */ + withConnection(fn, callback) { + this.checkOut((err, conn) => { + // don't callback with `err` here, we might want to act upon it inside `fn` + + fn(err, conn, (fnErr, result) => { + if (typeof callback === 'function') { + if (fnErr) { + callback(fnErr); + } else { + callback(undefined, result); + } + } + + if (conn) { + this.checkIn(conn); + } + }); + }); + } +} + +function ensureMinPoolSize(pool) { + if (pool.closed || pool.options.minPoolSize === 0) { + return; + } + + const minPoolSize = pool.options.minPoolSize; + for (let i = pool.totalConnectionCount; i < minPoolSize; ++i) { + createConnection(pool); + } + + pool[kMinPoolSizeTimer] = setTimeout(() => ensureMinPoolSize(pool), 10); +} + +function connectionIsStale(pool, connection) { + return connection.generation !== pool[kGeneration]; +} + +function connectionIsIdle(pool, connection) { + return !!(pool.options.maxIdleTimeMS && connection.idleTime > pool.options.maxIdleTimeMS); +} + +function createConnection(pool, callback) { + const connectOptions = Object.assign( + { + id: pool[kConnectionCounter].next().value, + generation: pool[kGeneration] + }, + pool.options + ); + + pool[kPermits]--; + connect(connectOptions, pool[kCancellationToken], (err, connection) => { + if (err) { + pool[kPermits]++; + pool[kLogger].debug(`connection attempt failed with error [${JSON.stringify(err)}]`); + if (typeof callback === 'function') { + callback(err); + } + + return; + } + + // The pool might have closed since we started trying to create a connection + if (pool.closed) { + connection.destroy({ force: true }); + return; + } + + // forward all events from the connection to the pool + relayEvents(connection, pool, [ + 'commandStarted', + 'commandFailed', + 'commandSucceeded', + 'clusterTimeReceived' + ]); + + pool.emit('connectionCreated', new ConnectionCreatedEvent(pool, connection)); + + connection.markAvailable(); + pool.emit('connectionReady', new ConnectionReadyEvent(pool, connection)); + + // if a callback has been provided, check out the connection immediately + if (typeof callback === 'function') { + callback(undefined, connection); + return; + } + + // otherwise add it to the pool for later acquisition, and try to process the wait queue + pool[kConnections].push(connection); + setImmediate(() => processWaitQueue(pool)); + }); +} + +function destroyConnection(pool, connection, reason) { + pool.emit('connectionClosed', new ConnectionClosedEvent(pool, connection, reason)); + + // allow more connections to be created + pool[kPermits]++; + + // destroy the connection + setImmediate(() => connection.destroy()); +} + +function processWaitQueue(pool) { + if (pool.closed) { + return; + } + + while (pool.waitQueueSize) { + const waitQueueMember = pool[kWaitQueue].peekFront(); + if (waitQueueMember[kCancelled]) { + pool[kWaitQueue].shift(); + continue; + } + + if (!pool.availableConnectionCount) { + break; + } + + const connection = pool[kConnections].shift(); + const isStale = connectionIsStale(pool, connection); + const isIdle = connectionIsIdle(pool, connection); + if (!isStale && !isIdle && !connection.closed) { + pool.emit('connectionCheckedOut', new ConnectionCheckedOutEvent(pool, connection)); + clearTimeout(waitQueueMember.timer); + pool[kWaitQueue].shift(); + waitQueueMember.callback(undefined, connection); + return; + } + + const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; + destroyConnection(pool, connection, reason); + } + + const maxPoolSize = pool.options.maxPoolSize; + if (pool.waitQueueSize && (maxPoolSize <= 0 || pool.totalConnectionCount < maxPoolSize)) { + createConnection(pool, (err, connection) => { + const waitQueueMember = pool[kWaitQueue].shift(); + if (waitQueueMember == null) { + if (err == null) { + pool[kConnections].push(connection); + } + + return; + } + + if (waitQueueMember[kCancelled]) { + return; + } + + if (err) { + pool.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(pool, err)); + } else { + pool.emit('connectionCheckedOut', new ConnectionCheckedOutEvent(pool, connection)); + } + + clearTimeout(waitQueueMember.timer); + waitQueueMember.callback(err, connection); + }); + + return; + } +} + +/** + * A callback provided to `withConnection` + * + * @callback ConnectionPool~withConnectionCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Connection} connection The managed connection which was checked out of the pool. + * @param {Function} callback A function to call back after connection management is complete + */ + +/** + * A callback provided to `checkOut` + * + * @callback ConnectionPool~checkOutCallback + * @param {MongoError} error An error instance representing the error during checkout + * @param {Connection} connection A connection from the pool + */ + +/** + * Emitted once when the connection pool is created + * + * @event ConnectionPool#connectionPoolCreated + * @type {PoolCreatedEvent} + */ + +/** + * Emitted once when the connection pool is closed + * + * @event ConnectionPool#connectionPoolClosed + * @type {PoolClosedEvent} + */ + +/** + * Emitted each time a connection is created + * + * @event ConnectionPool#connectionCreated + * @type {ConnectionCreatedEvent} + */ + +/** + * Emitted when a connection becomes established, and is ready to use + * + * @event ConnectionPool#connectionReady + * @type {ConnectionReadyEvent} + */ + +/** + * Emitted when a connection is closed + * + * @event ConnectionPool#connectionClosed + * @type {ConnectionClosedEvent} + */ + +/** + * Emitted when an attempt to check out a connection begins + * + * @event ConnectionPool#connectionCheckOutStarted + * @type {ConnectionCheckOutStartedEvent} + */ + +/** + * Emitted when an attempt to check out a connection fails + * + * @event ConnectionPool#connectionCheckOutFailed + * @type {ConnectionCheckOutFailedEvent} + */ + +/** + * Emitted each time a connection is successfully checked out of the connection pool + * + * @event ConnectionPool#connectionCheckedOut + * @type {ConnectionCheckedOutEvent} + */ + +/** + * Emitted each time a connection is successfully checked into the connection pool + * + * @event ConnectionPool#connectionCheckedIn + * @type {ConnectionCheckedInEvent} + */ + +/** + * Emitted each time the connection pool is cleared and it's generation incremented + * + * @event ConnectionPool#connectionPoolCleared + * @type {PoolClearedEvent} + */ + +module.exports = { + ConnectionPool +}; + + +/***/ }), + +/***/ 2926: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const MongoError = __webpack_require__(3111).MongoError; + +/** + * An error indicating a connection pool is closed + * + * @property {string} address The address of the connection pool + * @extends MongoError + */ +class PoolClosedError extends MongoError { + constructor(pool) { + super('Attempted to check out a connection from closed connection pool'); + this.name = 'MongoPoolClosedError'; + this.address = pool.address; + } +} + +/** + * An error thrown when a request to check out a connection times out + * + * @property {string} address The address of the connection pool + * @extends MongoError + */ +class WaitQueueTimeoutError extends MongoError { + constructor(pool) { + super('Timed out while checking out a connection from connection pool'); + this.name = 'MongoWaitQueueTimeoutError'; + this.address = pool.address; + } +} + +module.exports = { + PoolClosedError, + WaitQueueTimeoutError +}; + + +/***/ }), + +/***/ 897: +/***/ ((module) => { + +"use strict"; + + +/** + * The base class for all monitoring events published from the connection pool + * + * @property {number} time A timestamp when the event was created + * @property {string} address The address (host/port pair) of the pool + */ +class ConnectionPoolMonitoringEvent { + constructor(pool) { + this.time = new Date(); + this.address = pool.address; + } +} + +/** + * An event published when a connection pool is created + * + * @property {Object} options The options used to create this connection pool + */ +class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { + constructor(pool) { + super(pool); + this.options = pool.options; + } +} + +/** + * An event published when a connection pool is closed + */ +class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { + constructor(pool) { + super(pool); + } +} + +/** + * An event published when a connection pool creates a new connection + * + * @property {number} connectionId A monotonically increasing, per-pool id for the newly created connection + */ +class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection is ready for use + * + * @property {number} connectionId The id of the connection + */ +class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection is closed + * + * @property {number} connectionId The id of the connection + * @property {string} reason The reason the connection was closed + */ +class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { + constructor(pool, connection, reason) { + super(pool); + this.connectionId = connection.id; + this.reason = reason || 'unknown'; + } +} + +/** + * An event published when a request to check a connection out begins + */ +class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { + constructor(pool) { + super(pool); + } +} + +/** + * An event published when a request to check a connection out fails + * + * @property {string} reason The reason the attempt to check out failed + */ +class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { + constructor(pool, reason) { + super(pool); + this.reason = reason; + } +} + +/** + * An event published when a connection is checked out of the connection pool + * + * @property {number} connectionId The id of the connection + */ +class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection is checked into the connection pool + * + * @property {number} connectionId The id of the connection + */ +class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection pool is cleared + */ +class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { + constructor(pool) { + super(pool); + } +} + +const CMAP_EVENT_NAMES = [ + 'connectionPoolCreated', + 'connectionPoolClosed', + 'connectionCreated', + 'connectionReady', + 'connectionClosed', + 'connectionCheckOutStarted', + 'connectionCheckOutFailed', + 'connectionCheckedOut', + 'connectionCheckedIn', + 'connectionPoolCleared' +]; + +module.exports = { + CMAP_EVENT_NAMES, + ConnectionPoolCreatedEvent, + ConnectionPoolClosedEvent, + ConnectionCreatedEvent, + ConnectionReadyEvent, + ConnectionClosedEvent, + ConnectionCheckOutStartedEvent, + ConnectionCheckOutFailedEvent, + ConnectionCheckedOutEvent, + ConnectionCheckedInEvent, + ConnectionPoolClearedEvent +}; + + +/***/ }), + +/***/ 2425: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Duplex = __webpack_require__(2413).Duplex; +const BufferList = __webpack_require__(336); +const MongoParseError = __webpack_require__(3111).MongoParseError; +const decompress = __webpack_require__(7793).decompress; +const Response = __webpack_require__(9814).Response; +const BinMsg = __webpack_require__(8988).BinMsg; +const MongoError = __webpack_require__(3111).MongoError; +const OP_COMPRESSED = __webpack_require__(7272).opcodes.OP_COMPRESSED; +const OP_MSG = __webpack_require__(7272).opcodes.OP_MSG; +const MESSAGE_HEADER_SIZE = __webpack_require__(7272).MESSAGE_HEADER_SIZE; +const COMPRESSION_DETAILS_SIZE = __webpack_require__(7272).COMPRESSION_DETAILS_SIZE; +const opcodes = __webpack_require__(7272).opcodes; +const compress = __webpack_require__(7793).compress; +const compressorIDs = __webpack_require__(7793).compressorIDs; +const uncompressibleCommands = __webpack_require__(7793).uncompressibleCommands; +const Msg = __webpack_require__(8988).Msg; + +const kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4; +const kBuffer = Symbol('buffer'); + +/** + * A duplex stream that is capable of reading and writing raw wire protocol messages, with + * support for optional compression + */ +class MessageStream extends Duplex { + constructor(options) { + options = options || {}; + super(options); + + this.bson = options.bson; + this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize; + + this[kBuffer] = new BufferList(); + } + + _write(chunk, _, callback) { + const buffer = this[kBuffer]; + buffer.append(chunk); + + processIncomingData(this, callback); + } + + _read(/* size */) { + // NOTE: This implementation is empty because we explicitly push data to be read + // when `writeMessage` is called. + return; + } + + writeCommand(command, operationDescription) { + // TODO [$5f5fbe42fcabad09c1c2419d]: agreed compressor should live in `StreamDescription` + const shouldCompress = operationDescription && !!operationDescription.agreedCompressor; + if (!shouldCompress || !canCompress(command)) { + const data = command.toBin(); + this.push(Array.isArray(data) ? Buffer.concat(data) : data); + return; + } + + // otherwise, compress the message + const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin()); + const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); + + // Extract information needed for OP_COMPRESSED from the uncompressed message + const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); + + // Compress the message body + compress({ options: operationDescription }, messageToBeCompressed, (err, compressedMessage) => { + if (err) { + operationDescription.cb(err, null); + return; + } + + // Create the msgHeader of OP_COMPRESSED + const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); + msgHeader.writeInt32LE( + MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, + 0 + ); // messageLength + msgHeader.writeInt32LE(command.requestId, 4); // requestID + msgHeader.writeInt32LE(0, 8); // responseTo (zero) + msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode + + // Create the compression details of OP_COMPRESSED + const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); + compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode + compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader + compressionDetails.writeUInt8(compressorIDs[operationDescription.agreedCompressor], 8); // compressorID + + this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); + }); + } +} + +// Return whether a command contains an uncompressible command term +// Will return true if command contains no uncompressible command terms +function canCompress(command) { + const commandDoc = command instanceof Msg ? command.command : command.query; + const commandName = Object.keys(commandDoc)[0]; + return !uncompressibleCommands.has(commandName); +} + +function processIncomingData(stream, callback) { + const buffer = stream[kBuffer]; + if (buffer.length < 4) { + callback(); + return; + } + + const sizeOfMessage = buffer.readInt32LE(0); + if (sizeOfMessage < 0) { + callback(new MongoParseError(`Invalid message size: ${sizeOfMessage}`)); + return; + } + + if (sizeOfMessage > stream.maxBsonMessageSize) { + callback( + new MongoParseError( + `Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}` + ) + ); + return; + } + + if (sizeOfMessage > buffer.length) { + callback(); + return; + } + + const message = buffer.slice(0, sizeOfMessage); + buffer.consume(sizeOfMessage); + + const messageHeader = { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; + + let ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; + const responseOptions = stream.responseOptions; + if (messageHeader.opCode !== OP_COMPRESSED) { + const messageBody = message.slice(MESSAGE_HEADER_SIZE); + stream.emit( + 'message', + new ResponseType(stream.bson, message, messageHeader, messageBody, responseOptions) + ); + + if (buffer.length >= 4) { + processIncomingData(stream, callback); + } else { + callback(); + } + + return; + } + + messageHeader.fromCompressed = true; + messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE); + messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4); + const compressorID = message[MESSAGE_HEADER_SIZE + 8]; + const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9); + + // recalculate based on wrapped opcode + ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; + + decompress(compressorID, compressedBuffer, (err, messageBody) => { + if (err) { + callback(err); + return; + } + + if (messageBody.length !== messageHeader.length) { + callback( + new MongoError( + 'Decompressing a compressed message from the server failed. The message is corrupt.' + ) + ); + + return; + } + + stream.emit( + 'message', + new ResponseType(stream.bson, message, messageHeader, messageBody, responseOptions) + ); + + if (buffer.length >= 4) { + processIncomingData(stream, callback); + } else { + callback(); + } + }); +} + +module.exports = MessageStream; + + +/***/ }), + +/***/ 6292: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const parseServerType = __webpack_require__(750).parseServerType; + +const RESPONSE_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'maxBsonObjectSize', + 'maxMessageSizeBytes', + 'maxWriteBatchSize', + '__nodejs_mock_server__' +]; + +class StreamDescription { + constructor(address, options) { + this.address = address; + this.type = parseServerType(null); + this.minWireVersion = undefined; + this.maxWireVersion = undefined; + this.maxBsonObjectSize = 16777216; + this.maxMessageSizeBytes = 48000000; + this.maxWriteBatchSize = 100000; + this.compressors = + options && options.compression && Array.isArray(options.compression.compressors) + ? options.compression.compressors + : []; + } + + receiveResponse(response) { + this.type = parseServerType(response); + + RESPONSE_FIELDS.forEach(field => { + if (typeof response[field] !== 'undefined') { + this[field] = response[field]; + } + }); + + if (response.compression) { + this.compressor = this.compressors.filter(c => response.compression.indexOf(c) !== -1)[0]; + } + } +} + +module.exports = { + StreamDescription +}; + + +/***/ }), + +/***/ 5193: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const deprecate = __webpack_require__(1669).deprecate; +const deprecateOptions = __webpack_require__(1371).deprecateOptions; +const checkCollectionName = __webpack_require__(1371).checkCollectionName; +const ObjectID = __webpack_require__(3994).BSON.ObjectID; +const MongoError = __webpack_require__(3994).MongoError; +const normalizeHintField = __webpack_require__(1371).normalizeHintField; +const decorateCommand = __webpack_require__(1371).decorateCommand; +const decorateWithCollation = __webpack_require__(1371).decorateWithCollation; +const decorateWithReadConcern = __webpack_require__(1371).decorateWithReadConcern; +const formattedOrderClause = __webpack_require__(1371).formattedOrderClause; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const unordered = __webpack_require__(325); +const ordered = __webpack_require__(5035); +const ChangeStream = __webpack_require__(1117); +const executeLegacyOperation = __webpack_require__(1371).executeLegacyOperation; +const WriteConcern = __webpack_require__(2481); +const ReadConcern = __webpack_require__(7289); +const MongoDBNamespace = __webpack_require__(1371).MongoDBNamespace; +const AggregationCursor = __webpack_require__(7429); +const CommandCursor = __webpack_require__(538); + +// Operations +const ensureIndex = __webpack_require__(6716).ensureIndex; +const group = __webpack_require__(6716).group; +const parallelCollectionScan = __webpack_require__(6716).parallelCollectionScan; +const removeDocuments = __webpack_require__(2296).removeDocuments; +const save = __webpack_require__(6716).save; +const updateDocuments = __webpack_require__(2296).updateDocuments; + +const AggregateOperation = __webpack_require__(1554); +const BulkWriteOperation = __webpack_require__(6976); +const CountDocumentsOperation = __webpack_require__(5131); +const CreateIndexesOperation = __webpack_require__(6394); +const DeleteManyOperation = __webpack_require__(323); +const DeleteOneOperation = __webpack_require__(6352); +const DistinctOperation = __webpack_require__(6469); +const DropCollectionOperation = __webpack_require__(2360).DropCollectionOperation; +const DropIndexOperation = __webpack_require__(3560); +const DropIndexesOperation = __webpack_require__(5328); +const EstimatedDocumentCountOperation = __webpack_require__(4451); +const FindOperation = __webpack_require__(9961); +const FindOneOperation = __webpack_require__(4497); +const FindAndModifyOperation = __webpack_require__(711); +const FindOneAndDeleteOperation = __webpack_require__(5841); +const FindOneAndReplaceOperation = __webpack_require__(4316); +const FindOneAndUpdateOperation = __webpack_require__(1925); +const GeoHaystackSearchOperation = __webpack_require__(8169); +const IndexesOperation = __webpack_require__(4218); +const IndexExistsOperation = __webpack_require__(7809); +const IndexInformationOperation = __webpack_require__(4245); +const InsertManyOperation = __webpack_require__(3592); +const InsertOneOperation = __webpack_require__(9915); +const IsCappedOperation = __webpack_require__(4956); +const ListIndexesOperation = __webpack_require__(28); +const MapReduceOperation = __webpack_require__(2779); +const OptionsOperation = __webpack_require__(43); +const RenameOperation = __webpack_require__(2808); +const ReIndexOperation = __webpack_require__(6331); +const ReplaceOneOperation = __webpack_require__(2508); +const StatsOperation = __webpack_require__(968); +const UpdateManyOperation = __webpack_require__(9350); +const UpdateOneOperation = __webpack_require__(9068); + +const executeOperation = __webpack_require__(2548); + +/** + * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + */ + +const mergeKeys = ['ignoreUndefined']; + +/** + * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) + * @class + */ +function Collection(db, topology, dbName, name, pkFactory, options) { + checkCollectionName(name); + + // Unpack variables + const internalHint = null; + const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; + const serializeFunctions = + options == null || options.serializeFunctions == null + ? db.s.options.serializeFunctions + : options.serializeFunctions; + const raw = options == null || options.raw == null ? db.s.options.raw : options.raw; + const promoteLongs = + options == null || options.promoteLongs == null + ? db.s.options.promoteLongs + : options.promoteLongs; + const promoteValues = + options == null || options.promoteValues == null + ? db.s.options.promoteValues + : options.promoteValues; + const promoteBuffers = + options == null || options.promoteBuffers == null + ? db.s.options.promoteBuffers + : options.promoteBuffers; + const collectionHint = null; + + const namespace = new MongoDBNamespace(dbName, name); + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Set custom primary key factory if provided + pkFactory = pkFactory == null ? ObjectID : pkFactory; + + // Internal state + this.s = { + // Set custom primary key factory if provided + pkFactory: pkFactory, + // Db + db: db, + // Topology + topology: topology, + // Options + options: options, + // Namespace + namespace: namespace, + // Read preference + readPreference: ReadPreference.fromOptions(options), + // SlaveOK + slaveOk: slaveOk, + // Serialize functions + serializeFunctions: serializeFunctions, + // Raw + raw: raw, + // promoteLongs + promoteLongs: promoteLongs, + // promoteValues + promoteValues: promoteValues, + // promoteBuffers + promoteBuffers: promoteBuffers, + // internalHint + internalHint: internalHint, + // collectionHint + collectionHint: collectionHint, + // Promise library + promiseLibrary: promiseLibrary, + // Read Concern + readConcern: ReadConcern.fromOptions(options), + // Write Concern + writeConcern: WriteConcern.fromOptions(options) + }; +} + +/** + * The name of the database this collection belongs to + * @member {string} dbName + * @memberof Collection# + * @readonly + */ +Object.defineProperty(Collection.prototype, 'dbName', { + enumerable: true, + get: function() { + return this.s.namespace.db; + } +}); + +/** + * The name of this collection + * @member {string} collectionName + * @memberof Collection# + * @readonly + */ +Object.defineProperty(Collection.prototype, 'collectionName', { + enumerable: true, + get: function() { + return this.s.namespace.collection; + } +}); + +/** + * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` + * @member {string} namespace + * @memberof Collection# + * @readonly + */ +Object.defineProperty(Collection.prototype, 'namespace', { + enumerable: true, + get: function() { + return this.s.namespace.toString(); + } +}); + +/** + * The current readConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + * @member {ReadConcern} [readConcern] + * @memberof Collection# + * @readonly + */ +Object.defineProperty(Collection.prototype, 'readConcern', { + enumerable: true, + get: function() { + if (this.s.readConcern == null) { + return this.s.db.readConcern; + } + return this.s.readConcern; + } +}); + +/** + * The current readPreference of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + * @member {ReadPreference} [readPreference] + * @memberof Collection# + * @readonly + */ +Object.defineProperty(Collection.prototype, 'readPreference', { + enumerable: true, + get: function() { + if (this.s.readPreference == null) { + return this.s.db.readPreference; + } + + return this.s.readPreference; + } +}); + +/** + * The current writeConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + * @member {WriteConcern} [writeConcern] + * @memberof Collection# + * @readonly + */ +Object.defineProperty(Collection.prototype, 'writeConcern', { + enumerable: true, + get: function() { + if (this.s.writeConcern == null) { + return this.s.db.writeConcern; + } + return this.s.writeConcern; + } +}); + +/** + * The current index hint for the collection + * @member {object} [hint] + * @memberof Collection# + */ +Object.defineProperty(Collection.prototype, 'hint', { + enumerable: true, + get: function() { + return this.s.collectionHint; + }, + set: function(v) { + this.s.collectionHint = normalizeHintField(v); + } +}); + +const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot', 'oplogReplay']; + +/** + * Creates a cursor for a query that can be used to iterate over results from MongoDB + * @method + * @param {object} [query={}] The cursor query object. + * @param {object} [options] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.projection] The fields to return in the query. Object of fields to either include or exclude (one of, not both), {'a':1, 'b': 1} **or** {'a': 0, 'b': 0} + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {boolean} [options.awaitData=false] Specify if the cursor is a a tailable-await cursor. Requires `tailable` to be true + * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. + * @param {number} [options.min] Set index bounds. + * @param {number} [options.max] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true + * @param {boolean} [options.noCursorTimeout] The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {boolean} [options.allowDiskUse] Enables writing to temporary files on the server. + * @param {ClientSession} [options.session] optional session to use for this operation + * @throws {MongoError} + * @return {Cursor} + */ +Collection.prototype.find = deprecateOptions( + { + name: 'collection.find', + deprecatedOptions: DEPRECATED_FIND_OPTIONS, + optionsIndex: 1 + }, + function(query, options, callback) { + if (typeof callback === 'object') { + // TODO(MAJOR): throw in the future + console.warn('Third parameter to `find()` must be a callback or undefined'); + } + + let selector = query; + // figuring out arguments + if (typeof callback !== 'function') { + if (typeof options === 'function') { + callback = options; + options = undefined; + } else if (options == null) { + callback = typeof selector === 'function' ? selector : undefined; + selector = typeof selector === 'object' ? selector : undefined; + } + } + + // Ensure selector is not null + selector = selector == null ? {} : selector; + // Validate correctness off the selector + const object = selector; + if (Buffer.isBuffer(object)) { + const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); + if (object_size !== object.length) { + const error = new Error( + 'query selector raw message size does not match message header size [' + + object.length + + '] != [' + + object_size + + ']' + ); + error.name = 'MongoError'; + throw error; + } + } + + // Check special case where we are using an objectId + if (selector != null && selector._bsontype === 'ObjectID') { + selector = { _id: selector }; + } + + if (!options) options = {}; + + let projection = options.projection || options.fields; + + if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { + projection = projection.length + ? projection.reduce((result, field) => { + result[field] = 1; + return result; + }, {}) + : { _id: 1 }; + } + + // Make a shallow copy of options + let newOptions = Object.assign({}, options); + + // Make a shallow copy of the collection options + for (let key in this.s.options) { + if (mergeKeys.indexOf(key) !== -1) { + newOptions[key] = this.s.options[key]; + } + } + + // Unpack options + newOptions.skip = options.skip ? options.skip : 0; + newOptions.limit = options.limit ? options.limit : 0; + newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; + newOptions.hint = + options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; + newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout; + // // If we have overridden slaveOk otherwise use the default db setting + newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; + + // Add read preference if needed + newOptions.readPreference = ReadPreference.resolve(this, newOptions); + + // Set slave ok to true if read preference different from primary + if ( + newOptions.readPreference != null && + (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary') + ) { + newOptions.slaveOk = true; + } + + // Ensure the query is an object + if (selector != null && typeof selector !== 'object') { + throw MongoError.create({ message: 'query selector must be an object', driver: true }); + } + + // Build the find command + const findCommand = { + find: this.s.namespace.toString(), + limit: newOptions.limit, + skip: newOptions.skip, + query: selector + }; + + if (typeof options.allowDiskUse === 'boolean') { + findCommand.allowDiskUse = options.allowDiskUse; + } + + // Ensure we use the right await data option + if (typeof newOptions.awaitdata === 'boolean') { + newOptions.awaitData = newOptions.awaitdata; + } + + // Translate to new command option noCursorTimeout + if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout; + + decorateCommand(findCommand, newOptions, ['session', 'collation']); + + if (projection) findCommand.fields = projection; + + // Add db object to the new options + newOptions.db = this.s.db; + + // Add the promise library + newOptions.promiseLibrary = this.s.promiseLibrary; + + // Set raw if available at collection level + if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; + // Set promoteLongs if available at collection level + if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') + newOptions.promoteLongs = this.s.promoteLongs; + if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') + newOptions.promoteValues = this.s.promoteValues; + if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') + newOptions.promoteBuffers = this.s.promoteBuffers; + + // Sort options + if (findCommand.sort) { + findCommand.sort = formattedOrderClause(findCommand.sort); + } + + // Set the readConcern + decorateWithReadConcern(findCommand, this, options); + + // Decorate find command with collation options + try { + decorateWithCollation(findCommand, this, options); + } catch (err) { + if (typeof callback === 'function') return callback(err, null); + throw err; + } + + const cursor = this.s.topology.cursor( + new FindOperation(this, this.s.namespace, findCommand, newOptions), + newOptions + ); + + // TODO [$5f5fbe42fcabad09c1c2419e]: remove this when NODE-2074 is resolved + if (typeof callback === 'function') { + callback(null, cursor); + return; + } + + return cursor; + } +); + +/** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object} doc Document to insert. + * @param {object} [options] Optional settings. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertOne = function(doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const insertOneOperation = new InsertOneOperation(this, doc, options); + + return executeOperation(this.s.topology, insertOneOperation, callback); +}; + +/** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} docs Documents to insert. + * @param {object} [options] Optional settings. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertMany = function(docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : { ordered: true }; + + const insertManyOperation = new InsertManyOperation(this, docs, options); + + return executeOperation(this.s.topology, insertManyOperation, callback); +}; + +/** + * @typedef {Object} Collection~BulkWriteOpResult + * @property {number} insertedCount Number of documents inserted. + * @property {number} matchedCount Number of documents matched for update. + * @property {number} modifiedCount Number of documents modified. + * @property {number} deletedCount Number of documents deleted. + * @property {number} upsertedCount Number of documents upserted. + * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation + * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~bulkWriteOpCallback + * @param {BulkWriteError} error An error instance representing the error during the execution. + * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options] Optional settings. + * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {object[]} [options.arrayFilters] Determines which array elements to modify for update operation in MongoDB 3.6 or higher. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~bulkWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.bulkWrite = function(operations, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: true }; + + if (!Array.isArray(operations)) { + throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); + } + + const bulkWriteOperation = new BulkWriteOperation(this, operations, options); + + return executeOperation(this.s.topology, bulkWriteOperation, callback); +}; + +/** + * @typedef {Object} Collection~WriteOpResult + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {object} connection The connection object used for the operation. + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~writeOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * @typedef {Object} Collection~insertWriteOpResult + * @property {number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {Object.} insertedIds Map of the index of the inserted document to the id of the inserted document. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {number} result.ok Is 1 if the command executed correctly. + * @property {number} result.n The total count of documents inserted. + */ + +/** + * @typedef {Object} Collection~insertOneWriteOpResult + * @property {number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {number} result.ok Is 1 if the command executed correctly. + * @property {number} result.n The total count of documents inserted. + */ + +/** + * The callback format for inserts + * @callback Collection~insertWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * The callback format for inserts + * @callback Collection~insertOneWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {(object|object[])} docs Documents to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated Use insertOne, insertMany or bulkWrite + */ +Collection.prototype.insert = deprecate(function(docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: false }; + docs = !Array.isArray(docs) ? [docs] : docs; + + if (options.keepGoing === true) { + options.ordered = false; + } + + return this.insertMany(docs, options, callback); +}, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); + +/** + * @typedef {Object} Collection~updateWriteOpResult + * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents scanned. + * @property {Number} result.nModified The total count of documents modified. + * @property {Object} connection The connection object used for the operation. + * @property {Number} matchedCount The number of documents that matched the filter. + * @property {Number} modifiedCount The number of documents that were modified. + * @property {Number} upsertedCount The number of documents upserted. + * @property {Object} upsertedId The upserted id. + * @property {ObjectId} upsertedId._id The upserted _id returned from the server. + * @property {Object} message The raw msg response wrapped in an internal class + * @property {object[]} [ops] In a response to {@link Collection#replaceOne replaceOne}, contains the new value of the document on the server. This is the same document that was originally passed in, and is only here for legacy purposes. + */ + +/** + * The callback format for inserts + * @callback Collection~updateWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Update a single document in a collection + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options] Optional settings. + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. + * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query.. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateOne = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation( + this.s.topology, + new UpdateOneOperation(this, filter, update, options), + callback + ); +}; + +/** + * Replace a document in a collection with another document + * @method + * @param {object} filter The Filter used to select the document to replace + * @param {object} doc The Document that replaces the matching document + * @param {object} [options] Optional settings. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. + * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.replaceOne = function(filter, doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation( + this.s.topology, + new ReplaceOneOperation(this, filter, doc, options), + callback + ); +}; + +/** + * Update multiple documents in a collection + * @method + * @param {object} filter The Filter used to select the documents to update + * @param {object} update The update operations to be applied to the documents + * @param {object} [options] Optional settings. + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. + * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query.. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateMany = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation( + this.s.topology, + new UpdateManyOperation(this, filter, update, options), + callback + ); +}; + +/** + * Updates documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} update The update operations to be applied to the documents + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {boolean} [options.multi=false] Update one/all documents with operation. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + * @deprecated use updateOne, updateMany or bulkWrite + */ +Collection.prototype.update = deprecate(function(selector, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeLegacyOperation(this.s.topology, updateDocuments, [ + this, + selector, + update, + options, + callback + ]); +}, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); + +/** + * @typedef {Object} Collection~deleteWriteOpResult + * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents deleted. + * @property {Object} connection The connection object used for the operation. + * @property {Number} deletedCount The number of documents deleted. + */ + +/** + * The callback format for deletes + * @callback Collection~deleteWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Delete a document from a collection + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options] Optional settings. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {string|object} [options.hint] optional index hint for optimizing the filter query + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteOne = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const deleteOneOperation = new DeleteOneOperation(this, filter, options); + + return executeOperation(this.s.topology, deleteOneOperation, callback); +}; + +Collection.prototype.removeOne = Collection.prototype.deleteOne; + +/** + * Delete multiple documents from a collection + * @method + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options] Optional settings. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {string|object} [options.hint] optional index hint for optimizing the filter query + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteMany = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const deleteManyOperation = new DeleteManyOperation(this, filter, options); + + return executeOperation(this.s.topology, deleteManyOperation, callback); +}; + +Collection.prototype.removeMany = Collection.prototype.deleteMany; + +/** + * Remove documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} [options] Optional settings. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.single=false] Removes the first document found. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use deleteOne, deleteMany or bulkWrite + */ +Collection.prototype.remove = deprecate(function(selector, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeLegacyOperation(this.s.topology, removeDocuments, [ + this, + selector, + options, + callback + ]); +}, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); + +/** + * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic + * operators and update instead for more efficient operations. + * @method + * @param {object} doc Document to save + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +Collection.prototype.save = deprecate(function(doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeLegacyOperation(this.s.topology, save, [this, doc, options, callback]); +}, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.'); + +/** + * The callback format for results + * @callback Collection~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * The callback format for an aggregation call + * @callback Collection~aggregationCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. + */ + +/** + * Fetches the first document that matches the query + * @method + * @param {object} query Query for find Operation + * @param {object} [options] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=1] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. + * @param {number} [options.min] Set index bounds. + * @param {number} [options.max] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOne = deprecateOptions( + { + name: 'collection.find', + deprecatedOptions: DEPRECATED_FIND_OPTIONS, + optionsIndex: 1 + }, + function(query, options, callback) { + if (typeof callback === 'object') { + // TODO(MAJOR): throw in the future + console.warn('Third parameter to `findOne()` must be a callback or undefined'); + } + + if (typeof query === 'function') (callback = query), (query = {}), (options = {}); + if (typeof options === 'function') (callback = options), (options = {}); + query = query || {}; + options = options || {}; + + const findOneOperation = new FindOneOperation(this, query, options); + + return executeOperation(this.s.topology, findOneOperation, callback); + } +); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Collection~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Rename the collection. + * + * @method + * @param {string} newName New name of of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.rename = function(newName, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + const renameOperation = new RenameOperation(this, newName, options); + + return executeOperation(this.s.topology, renameOperation, callback); +}; + +/** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {object} [options] Optional settings. + * @param {WriteConcern} [options.writeConcern] A full WriteConcern object + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j] The journal write concern + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.drop = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const dropCollectionOperation = new DropCollectionOperation( + this.s.db, + this.collectionName, + options + ); + + return executeOperation(this.s.topology, dropCollectionOperation, callback); +}; + +/** + * Returns the options of the collection. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.options = function(opts, callback) { + if (typeof opts === 'function') (callback = opts), (opts = {}); + opts = opts || {}; + + const optionsOperation = new OptionsOperation(this, opts); + + return executeOperation(this.s.topology, optionsOperation, callback); +}; + +/** + * Returns if the collection is a capped collection + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.isCapped = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const isCappedOperation = new IsCappedOperation(this, options); + + return executeOperation(this.s.topology, isCappedOperation, callback); +}; + +/** + * Creates an index on the db and collection collection. + * @method + * @param {(string|array|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {(number|string)} [options.commitQuorum] (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @example + * const collection = client.db('foo').collection('bar'); + * + * await collection.createIndex({ a: 1, b: -1 }); + * + * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes + * await collection.createIndex([ [c, 1], [d, -1] ]); + * + * // Equivalent to { e: 1 } + * await collection.createIndex('e'); + * + * // Equivalent to { f: 1, g: 1 } + * await collection.createIndex(['f', 'g']) + * + * // Equivalent to { h: 1, i: -1 } + * await collection.createIndex([ { h: 1 }, { i: -1 } ]); + * + * // Equivalent to { j: 1, k: -1, l: 2d } + * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) + */ +Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const createIndexesOperation = new CreateIndexesOperation( + this, + this.collectionName, + fieldOrSpec, + options + ); + + return executeOperation(this.s.topology, createIndexesOperation, callback); +}; + +/** + * @typedef {object} Collection~IndexDefinition + * @description A definition for an index. Used by the createIndex command. + * @see https://docs.mongodb.com/manual/reference/command/createIndexes/ + */ + +/** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. + * + * **Note**: Unlike {@link Collection#createIndex createIndex}, this function takes in raw index specifications. + * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/ here}. + * + * @method + * @param {Collection~IndexDefinition[]} indexSpecs An array of index specifications to be created + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {(number|string)} [options.commitQuorum] (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @example + * const collection = client.db('foo').collection('bar'); + * await collection.createIndexes([ + * // Simple index on field fizz + * { + * key: { fizz: 1 }, + * } + * // wildcard index + * { + * key: { '$**': 1 } + * }, + * // named index on darmok and jalad + * { + * key: { darmok: 1, jalad: -1 } + * name: 'tanagra' + * } + * ]); + */ +Collection.prototype.createIndexes = function(indexSpecs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + + options = options ? Object.assign({}, options) : {}; + + if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; + + const createIndexesOperation = new CreateIndexesOperation( + this, + this.collectionName, + indexSpecs, + options + ); + + return executeOperation(this.s.topology, createIndexesOperation, callback); +}; + +/** + * Drops an index from this collection. + * @method + * @param {string} indexName Name of the index to drop. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndex = function(indexName, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + options = args.length ? args.shift() || {} : {}; + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + const dropIndexOperation = new DropIndexOperation(this, indexName, options); + + return executeOperation(this.s.topology, dropIndexOperation, callback); +}; + +/** + * Drops all indexes from this collection. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndexes = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + + if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; + + const dropIndexesOperation = new DropIndexesOperation(this, options); + + return executeOperation(this.s.topology, dropIndexesOperation, callback); +}; + +/** + * Drops all indexes from this collection. + * @method + * @deprecated use dropIndexes + * @param {Collection~resultCallback} callback The command result callback + * @return {Promise} returns Promise if no [callback] passed + */ +Collection.prototype.dropAllIndexes = deprecate( + Collection.prototype.dropIndexes, + 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.' +); + +/** + * Reindex all indexes on the collection + * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. + * @method + * @deprecated use db.command instead + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.reIndex = deprecate(function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const reIndexOperation = new ReIndexOperation(this, options); + + return executeOperation(this.s.topology, reIndexOperation, callback); +}, 'collection.reIndex is deprecated. Use db.command instead.'); + +/** + * Get the list of all indexes information for the collection. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {CommandCursor} + */ +Collection.prototype.listIndexes = function(options) { + const cursor = new CommandCursor( + this.s.topology, + new ListIndexesOperation(this, options), + options + ); + + return cursor; +}; + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated use createIndexes instead + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.s.topology, ensureIndex, [ + this, + fieldOrSpec, + options, + callback + ]); +}, 'collection.ensureIndex is deprecated. Use createIndexes instead.'); + +/** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * @method + * @param {(string|array)} indexes One or more index names to check. + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexExists = function(indexes, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const indexExistsOperation = new IndexExistsOperation(this, indexes, options); + + return executeOperation(this.s.topology, indexExistsOperation, callback); +}; + +/** + * Retrieves this collections index info. + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexInformation = function(options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + const indexInformationOperation = new IndexInformationOperation( + this.s.db, + this.collectionName, + options + ); + + return executeOperation(this.s.topology, indexInformationOperation, callback); +}; + +/** + * The callback format for results + * @callback Collection~countCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} result The count of documents that matched the query. + */ + +/** + * An estimated count of matching documents in the db to a query. + * + * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents + * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments countDocuments}. + * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount estimatedDocumentCount}. + * + * @method + * @param {object} [query={}] The query for the count. + * @param {object} [options] Optional settings. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {boolean} [options.limit] The limit of documents to count. + * @param {boolean} [options.skip] The number of documents to skip for the count. + * @param {string} [options.hint] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~countCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead + */ +Collection.prototype.count = deprecate(function(query, options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + query = args.length ? args.shift() || {} : {}; + options = args.length ? args.shift() || {} : {}; + + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation( + this.s.topology, + new EstimatedDocumentCountOperation(this, query, options), + callback + ); +}, 'collection.count is deprecated, and will be removed in a future version.' + + ' Use Collection.countDocuments or Collection.estimatedDocumentCount instead'); + +/** + * Gets an estimate of the count of documents in a collection using collection metadata. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. + * @param {Collection~countCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed. + */ +Collection.prototype.estimatedDocumentCount = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const estimatedDocumentCountOperation = new EstimatedDocumentCountOperation(this, options); + + return executeOperation(this.s.topology, estimatedDocumentCountOperation, callback); +}; + +/** + * Gets the number of documents matching the filter. + * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount estimatedDocumentCount}. + * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ + * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param {object} [query] the query for the count + * @param {object} [options] Optional settings. + * @param {object} [options.collation] Specifies a collation. + * @param {string|object} [options.hint] The index to use. + * @param {number} [options.limit] The maximum number of document to count. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. + * @param {number} [options.skip] The number of documents to skip before counting. + * @param {Collection~countCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed. + * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ + * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + +Collection.prototype.countDocuments = function(query, options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + query = args.length ? args.shift() || {} : {}; + options = args.length ? args.shift() || {} : {}; + + const countDocumentsOperation = new CountDocumentsOperation(this, query, options); + + return executeOperation(this.s.topology, countDocumentsOperation, callback); +}; + +/** + * The distinct command returns a list of distinct values for the given key across a collection. + * @method + * @param {string} key Field of the document to find distinct values for. + * @param {object} [query] The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.distinct = function(key, query, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + const queryOption = args.length ? args.shift() || {} : {}; + const optionsOption = args.length ? args.shift() || {} : {}; + + const distinctOperation = new DistinctOperation(this, key, queryOption, optionsOption); + + return executeOperation(this.s.topology, distinctOperation, callback); +}; + +/** + * Retrieve all the indexes on the collection. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexes = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const indexesOperation = new IndexesOperation(this, options); + + return executeOperation(this.s.topology, indexesOperation, callback); +}; + +/** + * Get all the collection statistics. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.scale] Divide the returned sizes by scale value. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.stats = function(options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + const statsOperation = new StatsOperation(this, options); + + return executeOperation(this.s.topology, statsOperation, callback); +}; + +/** + * @typedef {Object} Collection~findAndModifyWriteOpResult + * @property {object} value Document returned from the `findAndModify` command. If no documents were found, `value` will be `null` by default (`returnOriginal: true`), even if a document was upserted; if `returnOriginal` was false, the upserted document will be returned in that case. + * @property {object} lastErrorObject The raw lastErrorObject returned from the command. See {@link https://docs.mongodb.com/manual/reference/command/findAndModify/index.html#lasterrorobject|findAndModify command documentation}. + * @property {Number} ok Is 1 if the command executed correctly. + */ + +/** + * The callback format for inserts + * @callback Collection~findAndModifyCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options] Optional settings. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndDelete = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation( + this.s.topology, + new FindOneAndDeleteOperation(this, filter, options), + callback + ); +}; + +/** + * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to replace + * @param {object} replacement The Document that replaces the matching document + * @param {object} [options] Optional settings. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {string|object} [options.hint] An optional index to use for this operation + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation( + this.s.topology, + new FindOneAndReplaceOperation(this, filter, replacement, options), + callback + ); +}; + +/** + * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update Update operations to be performed on the document + * @param {object} [options] Optional settings. + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {string|object} [options.hint] An optional index to use for this operation + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] An ptional session to use for this operation + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation( + this.s.topology, + new FindOneAndUpdateOperation(this, filter, update, options), + callback + ); +}; + +/** + * Find and update a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.remove=false] Set to true to remove the object before returning. + * @param {boolean} [options.upsert=false] Perform an upsert operation. + * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. + * @param {object} [options.projection] Object containing the field projection for the result returned from the operation. + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {Collection~findAndModifyCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +Collection.prototype.findAndModify = deprecate( + _findAndModify, + 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.' +); + +/** + * @ignore + */ + +Collection.prototype._findAndModify = _findAndModify; + +function _findAndModify(query, sort, doc, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + sort = args.length ? args.shift() || [] : []; + doc = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Clone options + options = Object.assign({}, options); + // Force read preference primary + options.readPreference = ReadPreference.PRIMARY; + + return executeOperation( + this.s.topology, + new FindAndModifyOperation(this, query, sort, doc, options), + callback + ); +} + +/** + * Find and remove a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndDelete instead + */ +Collection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + sort = args.length ? args.shift() || [] : []; + options = args.length ? args.shift() || {} : {}; + + // Add the remove option + options.remove = true; + + return executeOperation( + this.s.topology, + new FindAndModifyOperation(this, query, sort, null, options), + callback + ); +}, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.'); + +/** + * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 + * @method + * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize=1000] Deprecated. Use `options.batchSize` + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {string} [options.comment] Add a comment to an aggregation command + * @param {string|object} [options.hint] Add an index selection hint to an aggregation command + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~aggregationCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Collection.prototype.aggregate = function(pipeline, options, callback) { + if (Array.isArray(pipeline)) { + // Set up callback if one is provided + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if (options == null && callback == null) { + options = {}; + } + } else { + // Aggregation pipeline passed as arguments on the method + const args = Array.prototype.slice.call(arguments, 0); + // Get the callback + callback = args.pop(); + // Get the possible options object + const opts = args[args.length - 1]; + // If it contains any of the admissible options pop it of the args + options = + opts && + (opts.readPreference || + opts.explain || + opts.cursor || + opts.out || + opts.maxTimeMS || + opts.hint || + opts.allowDiskUse) + ? args.pop() + : {}; + // Left over arguments is the pipeline + pipeline = args; + } + + const cursor = new AggregationCursor( + this.s.topology, + new AggregateOperation(this, pipeline, options), + options + ); + + // TODO [$5f5fbe42fcabad09c1c2419f]: remove this when NODE-2074 is resolved + if (typeof callback === 'function') { + callback(null, cursor); + return; + } + + return cursor; +}; + +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * @method + * @since 3.0.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +Collection.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * The callback format for results + * @callback Collection~parallelCollectionScanCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. + */ + +/** + * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are + * no ordering guarantees for returned results. + * @method + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.parallelCollectionScan = deprecate(function(options, callback) { + if (typeof options === 'function') (callback = options), (options = { numCursors: 1 }); + // Set number of cursors to 1 + options.numCursors = options.numCursors || 1; + options.batchSize = options.batchSize || 1000; + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = ReadPreference.resolve(this, options); + + // Add a promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + if (options.session) { + options.session = undefined; + } + + return executeLegacyOperation( + this.s.topology, + parallelCollectionScan, + [this, options, callback], + { skipSessions: true } + ); +}, 'parallelCollectionScan is deprecated in MongoDB v4.1'); + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxDistance] Include results up to maxDistance from the point. + * @param {object} [options.search] Filter the results by a query. + * @param {number} [options.limit=false] Max number of results to return. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated See {@link https://docs.mongodb.com/manual/geospatial-queries/|geospatial queries docs} for current geospatial support + */ +Collection.prototype.geoHaystackSearch = deprecate(function(x, y, options, callback) { + const args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + const geoHaystackSearchOperation = new GeoHaystackSearchOperation(this, x, y, options); + + return executeOperation(this.s.topology, geoHaystackSearchOperation, callback); +}, 'geoHaystackSearch is deprecated, and will be removed in a future version.'); + +/** + * Run a group command across a collection + * + * @method + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. + */ +Collection.prototype.group = deprecate(function( + keys, + condition, + initial, + reduce, + finalize, + command, + options, + callback +) { + const args = Array.prototype.slice.call(arguments, 3); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + reduce = args.length ? args.shift() : null; + finalize = args.length ? args.shift() : null; + command = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Make sure we are backward compatible + if (!(typeof finalize === 'function')) { + command = finalize; + finalize = null; + } + + if ( + !Array.isArray(keys) && + keys instanceof Object && + typeof keys !== 'function' && + !(keys._bsontype === 'Code') + ) { + keys = Object.keys(keys); + } + + if (typeof reduce === 'function') { + reduce = reduce.toString(); + } + + if (typeof finalize === 'function') { + finalize = finalize.toString(); + } + + // Set up the command as default + command = command == null ? true : command; + + return executeLegacyOperation(this.s.topology, group, [ + this, + keys, + condition, + initial, + reduce, + finalize, + command, + options, + callback + ]); +}, +'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.'); + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* + * @param {object} [options.query] Query filter object. + * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. + * @param {number} [options.limit] Number of objects to return from collection. + * @param {boolean} [options.keeptemp=false] Keep temporary data. + * @param {(function|string)} [options.finalize] Finalize function. + * @param {object} [options.scope] Can pass in variables that can be access from map/reduce/finalize. + * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. + * @param {boolean} [options.verbose=false] Provide statistics on job execution time. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.mapReduce = function(map, reduce, options, callback) { + if ('function' === typeof options) (callback = options), (options = {}); + // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) + if (null == options.out) { + throw new Error( + 'the out option parameter must be defined, see mongodb docs for possible values' + ); + } + + if ('function' === typeof map) { + map = map.toString(); + } + + if ('function' === typeof reduce) { + reduce = reduce.toString(); + } + + if ('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + const mapReduceOperation = new MapReduceOperation(this, map, reduce, options); + + return executeOperation(this.s.topology, mapReduceOperation, callback); +}; + +/** + * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {UnorderedBulkOperation} + */ +Collection.prototype.initializeUnorderedBulkOp = function(options) { + options = options || {}; + // Give function's options precedence over session options. + if (options.ignoreUndefined == null) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + options.promiseLibrary = this.s.promiseLibrary; + return unordered(this.s.topology, this, options); +}; + +/** + * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {OrderedBulkOperation} callback The command result callback + * @return {null} + */ +Collection.prototype.initializeOrderedBulkOp = function(options) { + options = options || {}; + // Give function's options precedence over session's options. + if (options.ignoreUndefined == null) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + options.promiseLibrary = this.s.promiseLibrary; + return ordered(this.s.topology, this, options); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +Collection.prototype.getLogger = function() { + return this.s.db.s.logger; +}; + +module.exports = Collection; + + +/***/ }), + +/***/ 538: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const ReadPreference = __webpack_require__(3994).ReadPreference; +const MongoError = __webpack_require__(3994).MongoError; +const Cursor = __webpack_require__(7159); +const CursorState = __webpack_require__(4847).CursorState; + +/** + * @fileOverview The **CommandCursor** class is an internal class that embodies a + * generalized cursor based on a MongoDB command allowing for iteration over the + * results returned. It supports one by one document iteration, conversion to an + * array or can be iterated as a Node 0.10.X or higher stream + * + * **CommandCursor Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('listCollectionsExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // List the database collections available + * db.listCollections().toArray(function(err, items) { + * test.equal(null, err); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class CommandCursor + * @extends external:Readable + * @fires CommandCursor#data + * @fires CommandCursor#end + * @fires CommandCursor#close + * @fires CommandCursor#readable + * @return {CommandCursor} an CommandCursor instance. + */ +class CommandCursor extends Cursor { + constructor(topology, ns, cmd, options) { + super(topology, ns, cmd, options); + } + + /** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ + setReadPreference(readPreference) { + if (this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (this.s.state !== CursorState.INIT) { + throw MongoError.create({ + message: 'cannot change cursor readPreference after cursor has been accessed', + driver: true + }); + } + + if (readPreference instanceof ReadPreference) { + this.options.readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this.options.readPreference = new ReadPreference(readPreference); + } else { + throw new TypeError('Invalid read preference: ' + readPreference); + } + + return this; + } + + /** + * Set the batch size for the cursor. + * @method + * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + * @throws {MongoError} + * @return {CommandCursor} + */ + batchSize(value) { + if (this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + } + + if (this.cmd.cursor) { + this.cmd.cursor.batchSize = value; + } + + this.setCursorBatchSize(value); + return this; + } + + /** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {CommandCursor} + */ + maxTimeMS(value) { + if (this.topology.lastIsMaster().minWireVersion > 2) { + this.cmd.maxTimeMS = value; + } + + return this; + } + + /** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ + getLogger() { + return this.logger; + } +} + +// aliases +CommandCursor.prototype.get = CommandCursor.prototype.toArray; + +/** + * CommandCursor stream data event, fired for each document in the cursor. + * + * @event CommandCursor#data + * @type {object} + */ + +/** + * CommandCursor stream end event + * + * @event CommandCursor#end + * @type {null} + */ + +/** + * CommandCursor stream close event + * + * @event CommandCursor#close + * @type {null} + */ + +/** + * CommandCursor stream readable event + * + * @event CommandCursor#readable + * @type {null} + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function CommandCursor.prototype.next + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Check if there is any document still available in the cursor + * @function CommandCursor.prototype.hasNext + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previously accessed. + * @method CommandCursor.prototype.toArray + * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previously accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method CommandCursor.prototype.each + * @param {CommandCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method CommandCursor.prototype.close + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method CommandCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Clone the cursor + * @function CommandCursor.prototype.clone + * @return {CommandCursor} + */ + +/** + * Resets the cursor + * @function CommandCursor.prototype.rewind + * @return {CommandCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback CommandCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback CommandCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method CommandCursor.prototype.forEach + * @param {CommandCursor~iteratorCallback} iterator The iteration callback. + * @param {CommandCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +module.exports = CommandCursor; + + +/***/ }), + +/***/ 147: +/***/ ((module) => { + +"use strict"; + + +module.exports = { + SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces', + SYSTEM_INDEX_COLLECTION: 'system.indexes', + SYSTEM_PROFILE_COLLECTION: 'system.profile', + SYSTEM_USER_COLLECTION: 'system.users', + SYSTEM_COMMAND_COLLECTION: '$cmd', + SYSTEM_JS_COLLECTION: 'system.js' +}; + + +/***/ }), + +/***/ 557: +/***/ ((module) => { + +"use strict"; + + +/** + * Context used during authentication + * + * @property {Connection} connection The connection to authenticate + * @property {MongoCredentials} credentials The credentials to use for authentication + * @property {object} options The options passed to the `connect` method + * @property {object?} response The response of the initial handshake + * @property {Buffer?} nonce A random nonce generated for use in an authentication conversation + */ +class AuthContext { + constructor(connection, credentials, options) { + this.connection = connection; + this.credentials = credentials; + this.options = options; + } +} + +class AuthProvider { + constructor(bson) { + this.bson = bson; + } + + /** + * Prepare the handshake document before the initial handshake. + * + * @param {object} handshakeDoc The document used for the initial handshake on a connection + * @param {AuthContext} authContext Context for authentication flow + * @param {function} callback + */ + prepare(handshakeDoc, context, callback) { + callback(undefined, handshakeDoc); + } + + /** + * Authenticate + * + * @param {AuthContext} context A shared context for authentication flow + * @param {authResultCallback} callback The callback to return the result from the authentication + */ + auth(context, callback) { + callback(new TypeError('`auth` method must be overridden by subclass')); + } +} + +/** + * This is a result from an authentication provider + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = { AuthContext, AuthProvider }; + + +/***/ }), + +/***/ 2192: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const MongoCR = __webpack_require__(4228); +const X509 = __webpack_require__(7324); +const Plain = __webpack_require__(8728); +const GSSAPI = __webpack_require__(2640); +const ScramSHA1 = __webpack_require__(864).ScramSHA1; +const ScramSHA256 = __webpack_require__(864).ScramSHA256; +const MongoDBAWS = __webpack_require__(8857); + +/** + * Returns the default authentication providers. + * + * @param {BSON} bson Bson definition + * @returns {Object} a mapping of auth names to auth types + */ +function defaultAuthProviders(bson) { + return { + 'mongodb-aws': new MongoDBAWS(bson), + mongocr: new MongoCR(bson), + x509: new X509(bson), + plain: new Plain(bson), + gssapi: new GSSAPI(bson), + 'scram-sha-1': new ScramSHA1(bson), + 'scram-sha-256': new ScramSHA256(bson) + }; +} + +module.exports = { defaultAuthProviders }; + + +/***/ }), + +/***/ 2640: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const dns = __webpack_require__(881); + +const AuthProvider = __webpack_require__(557).AuthProvider; +const retrieveKerberos = __webpack_require__(1178).retrieveKerberos; +const MongoError = __webpack_require__(3111).MongoError; + +const kGssapiClient = Symbol('GSSAPI_CLIENT'); +let kerberos; + +class GSSAPI extends AuthProvider { + prepare(handshakeDoc, authContext, callback) { + const host = authContext.options.host; + const port = authContext.options.port; + const credentials = authContext.credentials; + if (!host || !port || !credentials) { + return callback( + new MongoError( + `Connection must specify: ${host ? 'host' : ''}, ${port ? 'port' : ''}, ${ + credentials ? 'host' : 'credentials' + }.` + ) + ); + } + if (kerberos == null) { + try { + kerberos = retrieveKerberos(); + } catch (e) { + return callback(e); + } + } + const username = credentials.username; + const password = credentials.password; + const mechanismProperties = credentials.mechanismProperties; + const serviceName = + mechanismProperties['gssapiservicename'] || + mechanismProperties['gssapiServiceName'] || + 'mongodb'; + performGssapiCanonicalizeHostName(host, mechanismProperties, (err, host) => { + if (err) return callback(err); + const initOptions = {}; + if (password != null) { + Object.assign(initOptions, { user: username, password: password }); + } + kerberos.initializeClient( + `${serviceName}${process.platform === 'win32' ? '/' : '@'}${host}`, + initOptions, + (err, client) => { + if (err) return callback(new MongoError(err)); + if (client == null) return callback(); + this[kGssapiClient] = client; + callback(undefined, handshakeDoc); + } + ); + }); + } + auth(authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (credentials == null) return callback(new MongoError('credentials required')); + const username = credentials.username; + const client = this[kGssapiClient]; + if (client == null) return callback(new MongoError('gssapi client missing')); + function externalCommand(command, cb) { + return connection.command('$external.$cmd', command, cb); + } + client.step('', (err, payload) => { + if (err) return callback(err); + externalCommand(saslStart(payload), (err, response) => { + const result = response.result; + if (err) return callback(err); + negotiate(client, 10, result.payload, (err, payload) => { + if (err) return callback(err); + externalCommand(saslContinue(payload, result.conversationId), (err, response) => { + const result = response.result; + if (err) return callback(err); + finalize(client, username, result.payload, (err, payload) => { + if (err) return callback(err); + externalCommand( + { + saslContinue: 1, + conversationId: result.conversationId, + payload + }, + (err, result) => { + if (err) return callback(err); + callback(undefined, result); + } + ); + }); + }); + }); + }); + }); + } +} +module.exports = GSSAPI; + +function saslStart(payload) { + return { + saslStart: 1, + mechanism: 'GSSAPI', + payload, + autoAuthorize: 1 + }; +} +function saslContinue(payload, conversationId) { + return { + saslContinue: 1, + conversationId, + payload + }; +} +function negotiate(client, retries, payload, callback) { + client.step(payload, (err, response) => { + // Retries exhausted, raise error + if (err && retries === 0) return callback(err); + // Adjust number of retries and call step again + if (err) return negotiate(client, retries - 1, payload, callback); + // Return the payload + callback(undefined, response || ''); + }); +} +function finalize(client, user, payload, callback) { + // GSS Client Unwrap + client.unwrap(payload, (err, response) => { + if (err) return callback(err); + // Wrap the response + client.wrap(response || '', { user }, (err, wrapped) => { + if (err) return callback(err); + // Return the payload + callback(undefined, wrapped); + }); + }); +} +function performGssapiCanonicalizeHostName(host, mechanismProperties, callback) { + const canonicalizeHostName = + typeof mechanismProperties.gssapiCanonicalizeHostName === 'boolean' + ? mechanismProperties.gssapiCanonicalizeHostName + : false; + if (!canonicalizeHostName) return callback(undefined, host); + // Attempt to resolve the host name + dns.resolveCname(host, (err, r) => { + if (err) return callback(err); + // Get the first resolve host id + if (Array.isArray(r) && r.length > 0) { + return callback(undefined, r[0]); + } + callback(undefined, host); + }); +} + + +/***/ }), + +/***/ 2222: +/***/ ((module) => { + +"use strict"; + + +// Resolves the default auth mechanism according to +// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst +function getDefaultAuthMechanism(ismaster) { + if (ismaster) { + // If ismaster contains saslSupportedMechs, use scram-sha-256 + // if it is available, else scram-sha-1 + if (Array.isArray(ismaster.saslSupportedMechs)) { + return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0 + ? 'scram-sha-256' + : 'scram-sha-1'; + } + + // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 + if (ismaster.maxWireVersion >= 3) { + return 'scram-sha-1'; + } + } + + // Default for wireprotocol < 3 + return 'mongocr'; +} + +/** + * A representation of the credentials used by MongoDB + * @class + * @property {string} mechanism The method used to authenticate + * @property {string} [username] The username used for authentication + * @property {string} [password] The password used for authentication + * @property {string} [source] The database that the user should authenticate against + * @property {object} [mechanismProperties] Special properties used by some types of auth mechanisms + */ +class MongoCredentials { + /** + * Creates a new MongoCredentials object + * @param {object} [options] + * @param {string} [options.username] The username used for authentication + * @param {string} [options.password] The password used for authentication + * @param {string} [options.source] The database that the user should authenticate against + * @param {string} [options.mechanism] The method used to authenticate + * @param {object} [options.mechanismProperties] Special properties used by some types of auth mechanisms + */ + constructor(options) { + options = options || {}; + this.username = options.username; + this.password = options.password; + this.source = options.source || options.db; + this.mechanism = options.mechanism || 'default'; + this.mechanismProperties = options.mechanismProperties || {}; + + if (this.mechanism.match(/MONGODB-AWS/i)) { + if (this.username == null && process.env.AWS_ACCESS_KEY_ID) { + this.username = process.env.AWS_ACCESS_KEY_ID; + } + + if (this.password == null && process.env.AWS_SECRET_ACCESS_KEY) { + this.password = process.env.AWS_SECRET_ACCESS_KEY; + } + + if (this.mechanismProperties.AWS_SESSION_TOKEN == null && process.env.AWS_SESSION_TOKEN) { + this.mechanismProperties.AWS_SESSION_TOKEN = process.env.AWS_SESSION_TOKEN; + } + } + + Object.freeze(this.mechanismProperties); + Object.freeze(this); + } + + /** + * Determines if two MongoCredentials objects are equivalent + * @param {MongoCredentials} other another MongoCredentials object + * @returns {boolean} true if the two objects are equal. + */ + equals(other) { + return ( + this.mechanism === other.mechanism && + this.username === other.username && + this.password === other.password && + this.source === other.source + ); + } + + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param {Object} [ismaster] An ismaster response from the server + * @returns {MongoCredentials} + */ + resolveAuthMechanism(ismaster) { + // If the mechanism is not "default", then it does not need to be resolved + if (this.mechanism.match(/DEFAULT/i)) { + return new MongoCredentials({ + username: this.username, + password: this.password, + source: this.source, + mechanism: getDefaultAuthMechanism(ismaster), + mechanismProperties: this.mechanismProperties + }); + } + + return this; + } +} + +module.exports = { MongoCredentials }; + + +/***/ }), + +/***/ 4228: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const crypto = __webpack_require__(6417); +const AuthProvider = __webpack_require__(557).AuthProvider; + +class MongoCR extends AuthProvider { + auth(authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + const username = credentials.username; + const password = credentials.password; + const source = credentials.source; + + connection.command(`${source}.$cmd`, { getnonce: 1 }, (err, result) => { + let nonce = null; + let key = null; + + // Get nonce + if (err == null) { + const r = result.result; + nonce = r.nonce; + // Use node md5 generator + let md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password, 'utf8'); + const hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password, 'utf8'); + key = md5.digest('hex'); + } + + const authenticateCommand = { + authenticate: 1, + user: username, + nonce, + key + }; + + connection.command(`${source}.$cmd`, authenticateCommand, callback); + }); + } +} + +module.exports = MongoCR; + + +/***/ }), + +/***/ 8857: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const AuthProvider = __webpack_require__(557).AuthProvider; +const MongoCredentials = __webpack_require__(2222).MongoCredentials; +const MongoError = __webpack_require__(3111).MongoError; +const crypto = __webpack_require__(6417); +const http = __webpack_require__(8605); +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const url = __webpack_require__(8835); + +let aws4; +try { + aws4 = __webpack_require__(6071); +} catch (e) { + // don't do anything; +} + +const ASCII_N = 110; +const AWS_RELATIVE_URI = 'http://169.254.170.2'; +const AWS_EC2_URI = 'http://169.254.169.254'; +const AWS_EC2_PATH = '/latest/meta-data/iam/security-credentials'; + +class MongoDBAWS extends AuthProvider { + auth(authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + + if (maxWireVersion(connection) < 9) { + callback(new MongoError('MONGODB-AWS authentication requires MongoDB version 4.4 or later')); + return; + } + + if (aws4 == null) { + callback( + new MongoError( + 'MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project' + ) + ); + + return; + } + + if (credentials.username == null) { + makeTempCredentials(credentials, (err, tempCredentials) => { + if (err) return callback(err); + + authContext.credentials = tempCredentials; + this.auth(authContext, callback); + }); + + return; + } + + const username = credentials.username; + const password = credentials.password; + const db = credentials.source; + const token = credentials.mechanismProperties.AWS_SESSION_TOKEN; + const bson = this.bson; + + crypto.randomBytes(32, (err, nonce) => { + if (err) { + callback(err); + return; + } + + const saslStart = { + saslStart: 1, + mechanism: 'MONGODB-AWS', + payload: bson.serialize({ r: nonce, p: ASCII_N }) + }; + + connection.command(`${db}.$cmd`, saslStart, (err, result) => { + if (err) return callback(err); + + const res = result.result; + const serverResponse = bson.deserialize(res.payload.buffer); + const host = serverResponse.h; + const serverNonce = serverResponse.s.buffer; + if (serverNonce.length !== 64) { + callback( + new MongoError(`Invalid server nonce length ${serverNonce.length}, expected 64`) + ); + return; + } + + if (serverNonce.compare(nonce, 0, nonce.length, 0, nonce.length) !== 0) { + callback(new MongoError('Server nonce does not begin with client nonce')); + return; + } + + if (host.length < 1 || host.length > 255 || host.indexOf('..') !== -1) { + callback(new MongoError(`Server returned an invalid host: "${host}"`)); + return; + } + + const body = 'Action=GetCallerIdentity&Version=2011-06-15'; + const options = aws4.sign( + { + method: 'POST', + host, + region: deriveRegion(serverResponse.h), + service: 'sts', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Length': body.length, + 'X-MongoDB-Server-Nonce': serverNonce.toString('base64'), + 'X-MongoDB-GS2-CB-Flag': 'n' + }, + path: '/', + body + }, + { + accessKeyId: username, + secretAccessKey: password, + token + } + ); + + const authorization = options.headers.Authorization; + const date = options.headers['X-Amz-Date']; + const payload = { a: authorization, d: date }; + if (token) { + payload.t = token; + } + + const saslContinue = { + saslContinue: 1, + conversationId: 1, + payload: bson.serialize(payload) + }; + + connection.command(`${db}.$cmd`, saslContinue, err => { + if (err) return callback(err); + callback(); + }); + }); + }); + } +} + +function makeTempCredentials(credentials, callback) { + function done(creds) { + if (creds.AccessKeyId == null || creds.SecretAccessKey == null || creds.Token == null) { + callback(new MongoError('Could not obtain temporary MONGODB-AWS credentials')); + return; + } + + callback( + undefined, + new MongoCredentials({ + username: creds.AccessKeyId, + password: creds.SecretAccessKey, + source: credentials.source, + mechanism: 'MONGODB-AWS', + mechanismProperties: { + AWS_SESSION_TOKEN: creds.Token + } + }) + ); + } + + // If the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI + // is set then drivers MUST assume that it was set by an AWS ECS agent + if (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) { + request( + `${AWS_RELATIVE_URI}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`, + (err, res) => { + if (err) return callback(err); + done(res); + } + ); + + return; + } + + // Otherwise assume we are on an EC2 instance + + // get a token + + request( + `${AWS_EC2_URI}/latest/api/token`, + { method: 'PUT', json: false, headers: { 'X-aws-ec2-metadata-token-ttl-seconds': 30 } }, + (err, token) => { + if (err) return callback(err); + + // get role name + request( + `${AWS_EC2_URI}/${AWS_EC2_PATH}`, + { json: false, headers: { 'X-aws-ec2-metadata-token': token } }, + (err, roleName) => { + if (err) return callback(err); + + // get temp credentials + request( + `${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`, + { headers: { 'X-aws-ec2-metadata-token': token } }, + (err, creds) => { + if (err) return callback(err); + done(creds); + } + ); + } + ); + } + ); +} + +function deriveRegion(host) { + const parts = host.split('.'); + if (parts.length === 1 || parts[1] === 'amazonaws') { + return 'us-east-1'; + } + + return parts[1]; +} + +function request(uri, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = Object.assign( + { + method: 'GET', + timeout: 10000, + json: true + }, + url.parse(uri), + options + ); + + const req = http.request(options, res => { + res.setEncoding('utf8'); + + let data = ''; + res.on('data', d => (data += d)); + res.on('end', () => { + if (options.json === false) { + callback(undefined, data); + return; + } + + try { + const parsed = JSON.parse(data); + callback(undefined, parsed); + } catch (err) { + callback(new MongoError(`Invalid JSON response: "${data}"`)); + } + }); + }); + + req.on('error', err => callback(err)); + req.end(); +} + +module.exports = MongoDBAWS; + + +/***/ }), + +/***/ 8728: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const retrieveBSON = __webpack_require__(7746).retrieveBSON; +const AuthProvider = __webpack_require__(557).AuthProvider; + +// TODO [$5f5fbe42fcabad09c1c241a0]: can we get the Binary type from this.bson instead? +const BSON = retrieveBSON(); +const Binary = BSON.Binary; + +class Plain extends AuthProvider { + auth(authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + const username = credentials.username; + const password = credentials.password; + + const payload = new Binary(`\x00${username}\x00${password}`); + const command = { + saslStart: 1, + mechanism: 'PLAIN', + payload: payload, + autoAuthorize: 1 + }; + + connection.command('$external.$cmd', command, callback); + } +} + +module.exports = Plain; + + +/***/ }), + +/***/ 864: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const crypto = __webpack_require__(6417); +const Buffer = __webpack_require__(1867).Buffer; +const retrieveBSON = __webpack_require__(7746).retrieveBSON; +const MongoError = __webpack_require__(3111).MongoError; +const AuthProvider = __webpack_require__(557).AuthProvider; + +const BSON = retrieveBSON(); +const Binary = BSON.Binary; + +let saslprep; +try { + saslprep = __webpack_require__(9178); +} catch (e) { + // don't do anything; +} + +class ScramSHA extends AuthProvider { + constructor(bson, cryptoMethod) { + super(bson); + this.cryptoMethod = cryptoMethod || 'sha1'; + } + + prepare(handshakeDoc, authContext, callback) { + const cryptoMethod = this.cryptoMethod; + if (cryptoMethod === 'sha256' && saslprep == null) { + console.warn('Warning: no saslprep library specified. Passwords will not be sanitized'); + } + + crypto.randomBytes(24, (err, nonce) => { + if (err) { + return callback(err); + } + + // store the nonce for later use + Object.assign(authContext, { nonce }); + + const credentials = authContext.credentials; + const request = Object.assign({}, handshakeDoc, { + speculativeAuthenticate: Object.assign(makeFirstMessage(cryptoMethod, credentials, nonce), { + db: credentials.source + }) + }); + + callback(undefined, request); + }); + } + + auth(authContext, callback) { + const response = authContext.response; + if (response && response.speculativeAuthenticate) { + continueScramConversation( + this.cryptoMethod, + response.speculativeAuthenticate, + authContext, + callback + ); + + return; + } + + executeScram(this.cryptoMethod, authContext, callback); + } +} + +function cleanUsername(username) { + return username.replace('=', '=3D').replace(',', '=2C'); +} + +function clientFirstMessageBare(username, nonce) { + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return Buffer.concat([ + Buffer.from('n=', 'utf8'), + Buffer.from(username, 'utf8'), + Buffer.from(',r=', 'utf8'), + Buffer.from(nonce.toString('base64'), 'utf8') + ]); +} + +function makeFirstMessage(cryptoMethod, credentials, nonce) { + const username = cleanUsername(credentials.username); + const mechanism = cryptoMethod === 'sha1' ? 'SCRAM-SHA-1' : 'SCRAM-SHA-256'; + + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return { + saslStart: 1, + mechanism, + payload: new Binary( + Buffer.concat([Buffer.from('n,,', 'utf8'), clientFirstMessageBare(username, nonce)]) + ), + autoAuthorize: 1, + options: { skipEmptyExchange: true } + }; +} + +function executeScram(cryptoMethod, authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + const nonce = authContext.nonce; + const db = credentials.source; + + const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce); + connection.command(`${db}.$cmd`, saslStartCmd, (_err, result) => { + const err = resolveError(_err, result); + if (err) { + return callback(err); + } + + continueScramConversation(cryptoMethod, result.result, authContext, callback); + }); +} + +function continueScramConversation(cryptoMethod, response, authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + const nonce = authContext.nonce; + + const db = credentials.source; + const username = cleanUsername(credentials.username); + const password = credentials.password; + + let processedPassword; + if (cryptoMethod === 'sha256') { + processedPassword = saslprep ? saslprep(password) : password; + } else { + try { + processedPassword = passwordDigest(username, password); + } catch (e) { + return callback(e); + } + } + + const payload = Buffer.isBuffer(response.payload) + ? new Binary(response.payload) + : response.payload; + const dict = parsePayload(payload.value()); + + const iterations = parseInt(dict.i, 10); + if (iterations && iterations < 4096) { + callback(new MongoError(`Server returned an invalid iteration count ${iterations}`), false); + return; + } + + const salt = dict.s; + const rnonce = dict.r; + if (rnonce.startsWith('nonce')) { + callback(new MongoError(`Server returned an invalid nonce: ${rnonce}`), false); + return; + } + + // Set up start of proof + const withoutProof = `c=biws,r=${rnonce}`; + const saltedPassword = HI( + processedPassword, + Buffer.from(salt, 'base64'), + iterations, + cryptoMethod + ); + + const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); + const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key'); + const storedKey = H(cryptoMethod, clientKey); + const authMessage = [ + clientFirstMessageBare(username, nonce), + payload.value().toString('base64'), + withoutProof + ].join(','); + + const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); + const clientProof = `p=${xor(clientKey, clientSignature)}`; + const clientFinal = [withoutProof, clientProof].join(','); + + const serverSignature = HMAC(cryptoMethod, serverKey, authMessage); + const saslContinueCmd = { + saslContinue: 1, + conversationId: response.conversationId, + payload: new Binary(Buffer.from(clientFinal)) + }; + + connection.command(`${db}.$cmd`, saslContinueCmd, (_err, result) => { + const err = resolveError(_err, result); + if (err) { + return callback(err); + } + + const r = result.result; + const parsedResponse = parsePayload(r.payload.value()); + if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) { + callback(new MongoError('Server returned an invalid signature')); + return; + } + + if (!r || r.done !== false) { + return callback(err, r); + } + + const retrySaslContinueCmd = { + saslContinue: 1, + conversationId: r.conversationId, + payload: Buffer.alloc(0) + }; + + connection.command(`${db}.$cmd`, retrySaslContinueCmd, callback); + }); +} + +function parsePayload(payload) { + const dict = {}; + const parts = payload.split(','); + for (let i = 0; i < parts.length; i++) { + const valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + + return dict; +} + +function passwordDigest(username, password) { + if (typeof username !== 'string') { + throw new MongoError('username must be a string'); + } + + if (typeof password !== 'string') { + throw new MongoError('password must be a string'); + } + + if (password.length === 0) { + throw new MongoError('password cannot be empty'); + } + + const md5 = crypto.createHash('md5'); + md5.update(`${username}:mongo:${password}`, 'utf8'); + return md5.digest('hex'); +} + +// XOR two buffers +function xor(a, b) { + if (!Buffer.isBuffer(a)) { + a = Buffer.from(a); + } + + if (!Buffer.isBuffer(b)) { + b = Buffer.from(b); + } + + const length = Math.max(a.length, b.length); + const res = []; + + for (let i = 0; i < length; i += 1) { + res.push(a[i] ^ b[i]); + } + + return Buffer.from(res).toString('base64'); +} + +function H(method, text) { + return crypto + .createHash(method) + .update(text) + .digest(); +} + +function HMAC(method, key, text) { + return crypto + .createHmac(method, key) + .update(text) + .digest(); +} + +let _hiCache = {}; +let _hiCacheCount = 0; +function _hiCachePurge() { + _hiCache = {}; + _hiCacheCount = 0; +} + +const hiLengthMap = { + sha256: 32, + sha1: 20 +}; + +function HI(data, salt, iterations, cryptoMethod) { + // omit the work if already generated + const key = [data, salt.toString('base64'), iterations].join('_'); + if (_hiCache[key] !== undefined) { + return _hiCache[key]; + } + + // generate the salt + const saltedData = crypto.pbkdf2Sync( + data, + salt, + iterations, + hiLengthMap[cryptoMethod], + cryptoMethod + ); + + // cache a copy to speed up the next lookup, but prevent unbounded cache growth + if (_hiCacheCount >= 200) { + _hiCachePurge(); + } + + _hiCache[key] = saltedData; + _hiCacheCount += 1; + return saltedData; +} + +function compareDigest(lhs, rhs) { + if (lhs.length !== rhs.length) { + return false; + } + + if (typeof crypto.timingSafeEqual === 'function') { + return crypto.timingSafeEqual(lhs, rhs); + } + + let result = 0; + for (let i = 0; i < lhs.length; i++) { + result |= lhs[i] ^ rhs[i]; + } + + return result === 0; +} + +function resolveError(err, result) { + if (err) return err; + + const r = result.result; + if (r.$err || r.errmsg) return new MongoError(r); +} + +class ScramSHA1 extends ScramSHA { + constructor(bson) { + super(bson, 'sha1'); + } +} + +class ScramSHA256 extends ScramSHA { + constructor(bson) { + super(bson, 'sha256'); + } +} + +module.exports = { ScramSHA1, ScramSHA256 }; + + +/***/ }), + +/***/ 7324: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const AuthProvider = __webpack_require__(557).AuthProvider; + +class X509 extends AuthProvider { + prepare(handshakeDoc, authContext, callback) { + const credentials = authContext.credentials; + Object.assign(handshakeDoc, { + speculativeAuthenticate: x509AuthenticateCommand(credentials) + }); + + callback(undefined, handshakeDoc); + } + + auth(authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + const response = authContext.response; + if (response.speculativeAuthenticate) { + return callback(); + } + + connection.command('$external.$cmd', x509AuthenticateCommand(credentials), callback); + } +} + +function x509AuthenticateCommand(credentials) { + const command = { authenticate: 1, mechanism: 'MONGODB-X509' }; + if (credentials.username) { + Object.apply(command, { user: credentials.username }); + } + + return command; +} + +module.exports = X509; + + +/***/ }), + +/***/ 9815: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const Msg = __webpack_require__(8988).Msg; +const KillCursor = __webpack_require__(9814).KillCursor; +const GetMore = __webpack_require__(9814).GetMore; +const calculateDurationInMs = __webpack_require__(1371).calculateDurationInMs; + +/** Commands that we want to redact because of the sensitive nature of their contents */ +const SENSITIVE_COMMANDS = new Set([ + 'authenticate', + 'saslStart', + 'saslContinue', + 'getnonce', + 'createUser', + 'updateUser', + 'copydbgetnonce', + 'copydbsaslstart', + 'copydb' +]); + +// helper methods +const extractCommandName = commandDoc => Object.keys(commandDoc)[0]; +const namespace = command => command.ns; +const databaseName = command => command.ns.split('.')[0]; +const collectionName = command => command.ns.split('.')[1]; +const generateConnectionId = pool => + pool.options ? `${pool.options.host}:${pool.options.port}` : pool.address; +const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result); +const isLegacyPool = pool => pool.s && pool.queue; + +const LEGACY_FIND_QUERY_MAP = { + $query: 'filter', + $orderby: 'sort', + $hint: 'hint', + $comment: 'comment', + $maxScan: 'maxScan', + $max: 'max', + $min: 'min', + $returnKey: 'returnKey', + $showDiskLoc: 'showRecordId', + $maxTimeMS: 'maxTimeMS', + $snapshot: 'snapshot' +}; + +const LEGACY_FIND_OPTIONS_MAP = { + numberToSkip: 'skip', + numberToReturn: 'batchSize', + returnFieldsSelector: 'projection' +}; + +const OP_QUERY_KEYS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'partial', + 'exhaust' +]; + +/** + * Extract the actual command from the query, possibly upconverting if it's a legacy + * format + * + * @param {Object} command the command + */ +const extractCommand = command => { + if (command instanceof GetMore) { + return { + getMore: command.cursorId, + collection: collectionName(command), + batchSize: command.numberToReturn + }; + } + + if (command instanceof KillCursor) { + return { + killCursors: collectionName(command), + cursors: command.cursorIds + }; + } + + if (command instanceof Msg) { + return command.command; + } + + if (command.query && command.query.$query) { + let result; + if (command.ns === 'admin.$cmd') { + // upconvert legacy command + result = Object.assign({}, command.query.$query); + } else { + // upconvert legacy find command + result = { find: collectionName(command) }; + Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { + if (typeof command.query[key] !== 'undefined') + result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key]; + }); + } + + Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { + if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key]; + }); + + OP_QUERY_KEYS.forEach(key => { + if (command[key]) result[key] = command[key]; + }); + + if (typeof command.pre32Limit !== 'undefined') { + result.limit = command.pre32Limit; + } + + if (command.query.$explain) { + return { explain: result }; + } + + return result; + } + + return command.query ? command.query : command; +}; + +const extractReply = (command, reply) => { + if (command instanceof GetMore) { + return { + ok: 1, + cursor: { + id: reply.message.cursorId, + ns: namespace(command), + nextBatch: reply.message.documents + } + }; + } + + if (command instanceof KillCursor) { + return { + ok: 1, + cursorsUnknown: command.cursorIds + }; + } + + // is this a legacy find command? + if (command.query && typeof command.query.$query !== 'undefined') { + return { + ok: 1, + cursor: { + id: reply.message.cursorId, + ns: namespace(command), + firstBatch: reply.message.documents + } + }; + } + + return reply && reply.result ? reply.result : reply; +}; + +const extractConnectionDetails = pool => { + if (isLegacyPool(pool)) { + return { + connectionId: generateConnectionId(pool) + }; + } + + // APM in the modern pool is done at the `Connection` level, so we rename it here for + // readability. + const connection = pool; + return { + address: connection.address, + connectionId: connection.id + }; +}; + +/** An event indicating the start of a given command */ +class CommandStartedEvent { + /** + * Create a started event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + */ + constructor(pool, command) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const connectionDetails = extractConnectionDetails(pool); + + // NOTE: remove in major revision, this is not spec behavior + if (SENSITIVE_COMMANDS.has(commandName)) { + this.commandObj = {}; + this.commandObj[commandName] = true; + } + + Object.assign(this, connectionDetails, { + requestId: command.requestId, + databaseName: databaseName(command), + commandName, + command: cmd + }); + } +} + +/** An event indicating the success of a given command */ +class CommandSucceededEvent { + /** + * Create a succeeded event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + * @param {Object} reply the reply for this command from the server + * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(pool, command, reply, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const connectionDetails = extractConnectionDetails(pool); + + Object.assign(this, connectionDetails, { + requestId: command.requestId, + commandName, + duration: calculateDurationInMs(started), + reply: maybeRedact(commandName, extractReply(command, reply)) + }); + } +} + +/** An event indicating the failure of a given command */ +class CommandFailedEvent { + /** + * Create a failure event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + * @param {MongoError|Object} error the generated error or a server error response + * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(pool, command, error, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const connectionDetails = extractConnectionDetails(pool); + + Object.assign(this, connectionDetails, { + requestId: command.requestId, + commandName, + duration: calculateDurationInMs(started), + failure: maybeRedact(commandName, error) + }); + } +} + +module.exports = { + CommandStartedEvent, + CommandSucceededEvent, + CommandFailedEvent +}; + + +/***/ }), + +/***/ 2337: +/***/ ((module) => { + +"use strict"; + + +/** + * Creates a new CommandResult instance + * @class + * @param {object} result CommandResult object + * @param {Connection} connection A connection instance associated with this result + * @return {CommandResult} A cursor instance + */ +var CommandResult = function(result, connection, message) { + this.result = result; + this.connection = connection; + this.message = message; +}; + +/** + * Convert CommandResult to JSON + * @method + * @return {object} + */ +CommandResult.prototype.toJSON = function() { + let result = Object.assign({}, this, this.result); + delete result.message; + return result; +}; + +/** + * Convert CommandResult to String representation + * @method + * @return {string} + */ +CommandResult.prototype.toString = function() { + return JSON.stringify(this.toJSON()); +}; + +module.exports = CommandResult; + + +/***/ }), + +/***/ 9814: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var retrieveBSON = __webpack_require__(7746).retrieveBSON; +var BSON = retrieveBSON(); +var Long = BSON.Long; +const Buffer = __webpack_require__(1867).Buffer; + +// Incrementing request id +var _requestId = 0; + +// Wire command operation ids +var opcodes = __webpack_require__(7272).opcodes; + +// Query flags +var OPTS_TAILABLE_CURSOR = 2; +var OPTS_SLAVE = 4; +var OPTS_OPLOG_REPLAY = 8; +var OPTS_NO_CURSOR_TIMEOUT = 16; +var OPTS_AWAIT_DATA = 32; +var OPTS_EXHAUST = 64; +var OPTS_PARTIAL = 128; + +// Response flags +var CURSOR_NOT_FOUND = 1; +var QUERY_FAILURE = 2; +var SHARD_CONFIG_STALE = 4; +var AWAIT_CAPABLE = 8; + +/************************************************************** + * QUERY + **************************************************************/ +var Query = function(bson, ns, query, options) { + var self = this; + // Basic options needed to be passed in + if (ns == null) throw new Error('ns must be specified for query'); + if (query == null) throw new Error('query must be specified for query'); + + // Validate that we are not passing 0x00 in the collection name + if (ns.indexOf('\x00') !== -1) { + throw new Error('namespace cannot contain a null character'); + } + + // Basic options + this.bson = bson; + this.ns = ns; + this.query = query; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || null; + this.requestId = Query.getRequestId(); + + // special case for pre-3.2 find commands, delete ASAP + this.pre32Limit = options.pre32Limit; + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true; + this.batchSize = self.numberToReturn; + + // Flags + this.tailable = false; + this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; +}; + +// +// Assign a new request Id +Query.prototype.incRequestId = function() { + this.requestId = _requestId++; +}; + +// +// Assign a new request Id +Query.nextRequestId = function() { + return _requestId + 1; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +Query.prototype.toBin = function() { + var self = this; + var buffers = []; + var projection = null; + + // Set up the flags + var flags = 0; + if (this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + + if (this.slaveOk) { + flags |= OPTS_SLAVE; + } + + if (this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + + if (this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + + if (this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + + if (this.exhaust) { + flags |= OPTS_EXHAUST; + } + + if (this.partial) { + flags |= OPTS_PARTIAL; + } + + // If batchSize is different to self.numberToReturn + if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize; + + // Allocate write protocol header buffer + var header = Buffer.alloc( + 4 * 4 + // Header + 4 + // Flags + Buffer.byteLength(self.ns) + + 1 + // namespace + 4 + // numberToSkip + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + var query = self.bson.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + + // Add query document + buffers.push(query); + + if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = self.bson.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add projection document + buffers.push(projection); + } + + // Total message size + var totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + var index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = totalLength & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = this.requestId & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = 0 & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff; + header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff; + header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff; + header[index] = opcodes.OP_QUERY & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = flags & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = this.numberToSkip & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +}; + +Query.getRequestId = function() { + return ++_requestId; +}; + +/************************************************************** + * GETMORE + **************************************************************/ +var GetMore = function(bson, ns, cursorId, opts) { + opts = opts || {}; + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.bson = bson; + this.ns = ns; + this.cursorId = cursorId; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +GetMore.prototype.toBin = function() { + var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; + // Create command buffer + var index = 0; + // Allocate buffer + var _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff; + _buffer[index] = opcodes.OP_GETMORE & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getHighBits() & 0xff; + index = index + 4; + + // Return buffer + return _buffer; +}; + +/************************************************************** + * KILLCURSOR + **************************************************************/ +var KillCursor = function(bson, ns, cursorIds) { + this.ns = ns; + this.requestId = _requestId++; + this.cursorIds = cursorIds; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +KillCursor.prototype.toBin = function() { + var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; + + // Create command buffer + var index = 0; + var _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = opcodes.OP_KILL_CURSORS & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = this.cursorIds.length & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for (var i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; + index = index + 4; + } + + // Return buffer + return _buffer; +}; + +var Response = function(bson, message, msgHeader, msgBody, opts) { + opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.bson = bson; + this.opts = opts; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Read the message body + this.responseFlags = msgBody.readInt32LE(0); + this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); + this.startingFrom = msgBody.readInt32LE(12); + this.numberReturned = msgBody.readInt32LE(16); + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; + this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; + this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; + this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; +}; + +Response.prototype.isParsed = function() { + return this.parsed; +}; + +Response.prototype.parse = function(options) { + // Don't parse again if not needed + if (this.parsed) return; + options = options || {}; + + // Allow the return of raw documents instead of parsing + var raw = options.raw || false; + var documentsReturnedIn = options.documentsReturnedIn || null; + var promoteLongs = + typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; + var promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; + var promoteBuffers = + typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers; + var bsonSize, _options; + + // Set up the options + _options = { + promoteLongs: promoteLongs, + promoteValues: promoteValues, + promoteBuffers: promoteBuffers + }; + + // Position within OP_REPLY at which documents start + // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) + this.index = 20; + + // + // Parse Body + // + for (var i = 0; i < this.numberReturned; i++) { + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + + // If we have raw results specified slice the return document + if (raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = this.bson.deserialize( + this.data.slice(this.index, this.index + bsonSize), + _options + ); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + const doc = this.bson.deserialize(this.documents[0], _options); + this.documents = [doc]; + } + + // Set parsed + this.parsed = true; +}; + +module.exports = { + Query: Query, + GetMore: GetMore, + Response: Response, + KillCursor: KillCursor +}; + + +/***/ }), + +/***/ 6573: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const net = __webpack_require__(1631); +const tls = __webpack_require__(4016); +const Connection = __webpack_require__(6096); +const MongoError = __webpack_require__(3111).MongoError; +const MongoNetworkError = __webpack_require__(3111).MongoNetworkError; +const MongoNetworkTimeoutError = __webpack_require__(3111).MongoNetworkTimeoutError; +const defaultAuthProviders = __webpack_require__(2192).defaultAuthProviders; +const AuthContext = __webpack_require__(557).AuthContext; +const WIRE_CONSTANTS = __webpack_require__(7161); +const makeClientMetadata = __webpack_require__(1178).makeClientMetadata; +const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; +const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; +const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; +const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; +let AUTH_PROVIDERS; + +function connect(options, cancellationToken, callback) { + if (typeof cancellationToken === 'function') { + callback = cancellationToken; + cancellationToken = undefined; + } + + const ConnectionType = options && options.connectionType ? options.connectionType : Connection; + if (AUTH_PROVIDERS == null) { + AUTH_PROVIDERS = defaultAuthProviders(options.bson); + } + + const family = options.family !== void 0 ? options.family : 0; + makeConnection(family, options, cancellationToken, (err, socket) => { + if (err) { + callback(err, socket); // in the error case, `socket` is the originating error event name + return; + } + + performInitialHandshake(new ConnectionType(socket, options), options, callback); + }); +} + +function isModernConnectionType(conn) { + return !(conn instanceof Connection); +} + +function checkSupportedServer(ismaster, options) { + const serverVersionHighEnough = + ismaster && + typeof ismaster.maxWireVersion === 'number' && + ismaster.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION; + const serverVersionLowEnough = + ismaster && + typeof ismaster.minWireVersion === 'number' && + ismaster.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION; + + if (serverVersionHighEnough) { + if (serverVersionLowEnough) { + return null; + } + + const message = `Server at ${options.host}:${options.port} reports minimum wire version ${ismaster.minWireVersion}, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + return new MongoError(message); + } + + const message = `Server at ${options.host}:${ + options.port + } reports maximum wire version ${ismaster.maxWireVersion || + 0}, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`; + return new MongoError(message); +} + +function performInitialHandshake(conn, options, _callback) { + const callback = function(err, ret) { + if (err && conn) { + conn.destroy(); + } + _callback(err, ret); + }; + + const credentials = options.credentials; + if (credentials) { + if (!credentials.mechanism.match(/DEFAULT/i) && !AUTH_PROVIDERS[credentials.mechanism]) { + callback(new MongoError(`authMechanism '${credentials.mechanism}' not supported`)); + return; + } + } + + const authContext = new AuthContext(conn, credentials, options); + prepareHandshakeDocument(authContext, (err, handshakeDoc) => { + if (err) { + return callback(err); + } + + const handshakeOptions = Object.assign({}, options); + if (options.connectTimeoutMS || options.connectionTimeout) { + // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS + handshakeOptions.socketTimeout = options.connectTimeoutMS || options.connectionTimeout; + } + + const start = new Date().getTime(); + conn.command('admin.$cmd', handshakeDoc, handshakeOptions, (err, result) => { + if (err) { + callback(err); + return; + } + + const response = result.result; + if (response.ok === 0) { + callback(new MongoError(response)); + return; + } + + const supportedServerErr = checkSupportedServer(response, options); + if (supportedServerErr) { + callback(supportedServerErr); + return; + } + + if (!isModernConnectionType(conn)) { + // resolve compression + if (response.compression) { + const agreedCompressors = handshakeDoc.compression.filter( + compressor => response.compression.indexOf(compressor) !== -1 + ); + + if (agreedCompressors.length) { + conn.agreedCompressor = agreedCompressors[0]; + } + + if (options.compression && options.compression.zlibCompressionLevel) { + conn.zlibCompressionLevel = options.compression.zlibCompressionLevel; + } + } + } + + // NOTE: This is metadata attached to the connection while porting away from + // handshake being done in the `Server` class. Likely, it should be + // relocated, or at very least restructured. + conn.ismaster = response; + conn.lastIsMasterMS = new Date().getTime() - start; + + if (!response.arbiterOnly && credentials) { + // store the response on auth context + Object.assign(authContext, { response }); + + const resolvedCredentials = credentials.resolveAuthMechanism(response); + const authProvider = AUTH_PROVIDERS[resolvedCredentials.mechanism]; + authProvider.auth(authContext, err => { + if (err) return callback(err); + callback(undefined, conn); + }); + + return; + } + + callback(undefined, conn); + }); + }); +} + +function prepareHandshakeDocument(authContext, callback) { + const options = authContext.options; + const compressors = + options.compression && options.compression.compressors ? options.compression.compressors : []; + + const handshakeDoc = { + ismaster: true, + client: options.metadata || makeClientMetadata(options), + compression: compressors + }; + + const credentials = authContext.credentials; + if (credentials) { + if (credentials.mechanism.match(/DEFAULT/i) && credentials.username) { + Object.assign(handshakeDoc, { + saslSupportedMechs: `${credentials.source}.${credentials.username}` + }); + + AUTH_PROVIDERS['scram-sha-256'].prepare(handshakeDoc, authContext, callback); + return; + } + + const authProvider = AUTH_PROVIDERS[credentials.mechanism]; + authProvider.prepare(handshakeDoc, authContext, callback); + return; + } + + callback(undefined, handshakeDoc); +} + +const LEGAL_SSL_SOCKET_OPTIONS = [ + 'pfx', + 'key', + 'passphrase', + 'cert', + 'ca', + 'ciphers', + 'NPNProtocols', + 'ALPNProtocols', + 'servername', + 'ecdhCurve', + 'secureProtocol', + 'secureContext', + 'session', + 'minDHSize', + 'crl', + 'rejectUnauthorized' +]; + +function parseConnectOptions(family, options) { + const host = typeof options.host === 'string' ? options.host : 'localhost'; + if (host.indexOf('/') !== -1) { + return { path: host }; + } + + const result = { + family, + host, + port: typeof options.port === 'number' ? options.port : 27017, + rejectUnauthorized: false + }; + + return result; +} + +function parseSslOptions(family, options) { + const result = parseConnectOptions(family, options); + + // Merge in valid SSL options + for (const name in options) { + if (options[name] != null && LEGAL_SSL_SOCKET_OPTIONS.indexOf(name) !== -1) { + result[name] = options[name]; + } + } + + // Override checkServerIdentity behavior + if (options.checkServerIdentity === false) { + // Skip the identiy check by retuning undefined as per node documents + // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback + result.checkServerIdentity = function() { + return undefined; + }; + } else if (typeof options.checkServerIdentity === 'function') { + result.checkServerIdentity = options.checkServerIdentity; + } + + // Set default sni servername to be the same as host + if (result.servername == null) { + result.servername = result.host; + } + + return result; +} + +const SOCKET_ERROR_EVENTS = new Set(['error', 'close', 'timeout', 'parseError']); +function makeConnection(family, options, cancellationToken, _callback) { + const useSsl = typeof options.ssl === 'boolean' ? options.ssl : false; + const keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; + let keepAliveInitialDelay = + typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 120000; + const noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true; + const connectionTimeout = + typeof options.connectionTimeout === 'number' + ? options.connectionTimeout + : typeof options.connectTimeoutMS === 'number' + ? options.connectTimeoutMS + : 30000; + const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; + const rejectUnauthorized = + typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true; + + if (keepAliveInitialDelay > socketTimeout) { + keepAliveInitialDelay = Math.round(socketTimeout / 2); + } + + let socket; + const callback = function(err, ret) { + if (err && socket) { + socket.destroy(); + } + + _callback(err, ret); + }; + + try { + if (useSsl) { + socket = tls.connect(parseSslOptions(family, options)); + if (typeof socket.disableRenegotiation === 'function') { + socket.disableRenegotiation(); + } + } else { + socket = net.createConnection(parseConnectOptions(family, options)); + } + } catch (err) { + return callback(err); + } + + socket.setKeepAlive(keepAlive, keepAliveInitialDelay); + socket.setTimeout(connectionTimeout); + socket.setNoDelay(noDelay); + + const connectEvent = useSsl ? 'secureConnect' : 'connect'; + let cancellationHandler; + function errorHandler(eventName) { + return err => { + SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); + if (cancellationHandler) { + cancellationToken.removeListener('cancel', cancellationHandler); + } + + socket.removeListener(connectEvent, connectHandler); + callback(connectionFailureError(eventName, err)); + }; + } + + function connectHandler() { + SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); + if (cancellationHandler) { + cancellationToken.removeListener('cancel', cancellationHandler); + } + + if (socket.authorizationError && rejectUnauthorized) { + return callback(socket.authorizationError); + } + + socket.setTimeout(socketTimeout); + callback(null, socket); + } + + SOCKET_ERROR_EVENTS.forEach(event => socket.once(event, errorHandler(event))); + if (cancellationToken) { + cancellationHandler = errorHandler('cancel'); + cancellationToken.once('cancel', cancellationHandler); + } + + socket.once(connectEvent, connectHandler); +} + +function connectionFailureError(type, err) { + switch (type) { + case 'error': + return new MongoNetworkError(err); + case 'timeout': + return new MongoNetworkTimeoutError(`connection timed out`); + case 'close': + return new MongoNetworkError(`connection closed`); + case 'cancel': + return new MongoNetworkError(`connection establishment was cancelled`); + default: + return new MongoNetworkError(`unknown network error`); + } +} + +module.exports = connect; + + +/***/ }), + +/***/ 6096: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const EventEmitter = __webpack_require__(8614).EventEmitter; +const crypto = __webpack_require__(6417); +const debugOptions = __webpack_require__(7746).debugOptions; +const parseHeader = __webpack_require__(7272).parseHeader; +const decompress = __webpack_require__(7793).decompress; +const Response = __webpack_require__(9814).Response; +const BinMsg = __webpack_require__(8988).BinMsg; +const MongoNetworkError = __webpack_require__(3111).MongoNetworkError; +const MongoNetworkTimeoutError = __webpack_require__(3111).MongoNetworkTimeoutError; +const MongoError = __webpack_require__(3111).MongoError; +const Logger = __webpack_require__(104); +const OP_COMPRESSED = __webpack_require__(7272).opcodes.OP_COMPRESSED; +const OP_MSG = __webpack_require__(7272).opcodes.OP_MSG; +const MESSAGE_HEADER_SIZE = __webpack_require__(7272).MESSAGE_HEADER_SIZE; +const Buffer = __webpack_require__(1867).Buffer; +const Query = __webpack_require__(9814).Query; +const CommandResult = __webpack_require__(2337); + +let _id = 0; + +const DEFAULT_MAX_BSON_MESSAGE_SIZE = 1024 * 1024 * 16 * 4; +const DEBUG_FIELDS = [ + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'socketTimeout', + 'ssl', + 'ca', + 'crl', + 'cert', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'checkServerIdentity' +]; + +let connectionAccountingSpy = undefined; +let connectionAccounting = false; +let connections = {}; + +/** + * A class representing a single connection to a MongoDB server + * + * @fires Connection#connect + * @fires Connection#close + * @fires Connection#error + * @fires Connection#timeout + * @fires Connection#parseError + * @fires Connection#message + */ +class Connection extends EventEmitter { + /** + * Creates a new Connection instance + * + * **NOTE**: Internal class, do not instantiate directly + * + * @param {Socket} socket The socket this connection wraps + * @param {Object} options Various settings + * @param {object} options.bson An implementation of bson serialize and deserialize + * @param {string} [options.host='localhost'] The host the socket is connected to + * @param {number} [options.port=27017] The port used for the socket connection + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {boolean} [options.promoteLongs] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers] Promotes Binary BSON values to native Node Buffers. + * @param {number} [options.maxBsonMessageSize=0x4000000] Largest possible size of a BSON message (for legacy purposes) + */ + constructor(socket, options) { + super(); + + options = options || {}; + if (!options.bson) { + throw new TypeError('must pass in valid bson parser'); + } + + this.id = _id++; + this.options = options; + this.logger = Logger('Connection', options); + this.bson = options.bson; + this.tag = options.tag; + this.maxBsonMessageSize = options.maxBsonMessageSize || DEFAULT_MAX_BSON_MESSAGE_SIZE; + + this.port = options.port || 27017; + this.host = options.host || 'localhost'; + this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; + + // These values are inspected directly in tests, but maybe not necessary to keep around + this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; + this.keepAliveInitialDelay = + typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 120000; + this.connectionTimeout = + typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; + if (this.keepAliveInitialDelay > this.socketTimeout) { + this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2); + } + + // Debug information + if (this.logger.isDebug()) { + this.logger.debug( + `creating connection ${this.id} with options [${JSON.stringify( + debugOptions(DEBUG_FIELDS, options) + )}]` + ); + } + + // Response options + this.responseOptions = { + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false + }; + + // Flushing + this.flushing = false; + this.queue = []; + + // Internal state + this.writeStream = null; + this.destroyed = false; + this.timedOut = false; + + // Create hash method + const hash = crypto.createHash('sha1'); + hash.update(this.address); + this.hashedName = hash.digest('hex'); + + // All operations in flight on the connection + this.workItems = []; + + // setup socket + this.socket = socket; + this.socket.once('error', errorHandler(this)); + this.socket.once('timeout', timeoutHandler(this)); + this.socket.once('close', closeHandler(this)); + this.socket.on('data', dataHandler(this)); + + if (connectionAccounting) { + addConnection(this.id, this); + } + } + + setSocketTimeout(value) { + if (this.socket) { + this.socket.setTimeout(value); + } + } + + resetSocketTimeout() { + if (this.socket) { + this.socket.setTimeout(this.socketTimeout); + } + } + + static enableConnectionAccounting(spy) { + if (spy) { + connectionAccountingSpy = spy; + } + + connectionAccounting = true; + connections = {}; + } + + static disableConnectionAccounting() { + connectionAccounting = false; + connectionAccountingSpy = undefined; + } + + static connections() { + return connections; + } + + get address() { + return `${this.host}:${this.port}`; + } + + /** + * Unref this connection + * @method + * @return {boolean} + */ + unref() { + if (this.socket == null) { + this.once('connect', () => this.socket.unref()); + return; + } + + this.socket.unref(); + } + + /** + * Flush all work Items on this connection + * + * @param {*} err The error to propagate to the flushed work items + */ + flush(err) { + while (this.workItems.length > 0) { + const workItem = this.workItems.shift(); + if (workItem.cb) { + workItem.cb(err); + } + } + } + + /** + * Destroy connection + * @method + */ + destroy(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = Object.assign({ force: false }, options); + + if (connectionAccounting) { + deleteConnection(this.id); + } + + if (this.socket == null) { + this.destroyed = true; + return; + } + + if (options.force || this.timedOut) { + this.socket.destroy(); + this.destroyed = true; + if (typeof callback === 'function') callback(null, null); + return; + } + + this.socket.end(err => { + this.destroyed = true; + if (typeof callback === 'function') callback(err, null); + }); + } + + /** + * Write to connection + * @method + * @param {Command} command Command to write out need to implement toBin and toBinUnified + */ + write(buffer) { + // Debug Log + if (this.logger.isDebug()) { + if (!Array.isArray(buffer)) { + this.logger.debug(`writing buffer [${buffer.toString('hex')}] to ${this.address}`); + } else { + for (let i = 0; i < buffer.length; i++) + this.logger.debug(`writing buffer [${buffer[i].toString('hex')}] to ${this.address}`); + } + } + + // Double check that the connection is not destroyed + if (this.socket.destroyed === false) { + // Write out the command + if (!Array.isArray(buffer)) { + this.socket.write(buffer, 'binary'); + return true; + } + + // Iterate over all buffers and write them in order to the socket + for (let i = 0; i < buffer.length; i++) { + this.socket.write(buffer[i], 'binary'); + } + + return true; + } + + // Connection is destroyed return write failed + return false; + } + + /** + * Return id of connection as a string + * @method + * @return {string} + */ + toString() { + return '' + this.id; + } + + /** + * Return json object of connection + * @method + * @return {object} + */ + toJSON() { + return { id: this.id, host: this.host, port: this.port }; + } + + /** + * Is the connection connected + * @method + * @return {boolean} + */ + isConnected() { + if (this.destroyed) return false; + return !this.socket.destroyed && this.socket.writable; + } + + /** + * @ignore + */ + command(ns, command, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + + const conn = this; + const socketTimeout = + typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; + const bson = conn.options.bson; + const query = new Query(bson, ns, command, { + numberToSkip: 0, + numberToReturn: 1 + }); + + const noop = () => {}; + function _callback(err, result) { + callback(err, result); + callback = noop; + } + + function errorHandler(err) { + conn.resetSocketTimeout(); + CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); + conn.removeListener('message', messageHandler); + + if (err == null) { + err = new MongoError(`runCommand failed for connection to '${conn.address}'`); + } + + // ignore all future errors + conn.on('error', noop); + _callback(err); + } + + function messageHandler(msg) { + if (msg.responseTo !== query.requestId) { + return; + } + + conn.resetSocketTimeout(); + CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); + conn.removeListener('message', messageHandler); + + msg.parse({ promoteValues: true }); + + const response = msg.documents[0]; + if (response.ok === 0 || response.$err || response.errmsg || response.code) { + _callback(new MongoError(response)); + return; + } + + _callback(undefined, new CommandResult(response, this, msg)); + } + + conn.setSocketTimeout(socketTimeout); + CONNECTION_ERROR_EVENTS.forEach(eventName => conn.once(eventName, errorHandler)); + conn.on('message', messageHandler); + conn.write(query.toBin()); + } +} + +const CONNECTION_ERROR_EVENTS = ['error', 'close', 'timeout', 'parseError']; + +function deleteConnection(id) { + // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) + delete connections[id]; + + if (connectionAccountingSpy) { + connectionAccountingSpy.deleteConnection(id); + } +} + +function addConnection(id, connection) { + // console.log("=== added connection " + id + " :: " + connection.port) + connections[id] = connection; + + if (connectionAccountingSpy) { + connectionAccountingSpy.addConnection(id, connection); + } +} + +// +// Connection handlers +function errorHandler(conn) { + return function(err) { + if (connectionAccounting) deleteConnection(conn.id); + // Debug information + if (conn.logger.isDebug()) { + conn.logger.debug( + `connection ${conn.id} for [${conn.address}] errored out with [${JSON.stringify(err)}]` + ); + } + + conn.emit('error', new MongoNetworkError(err), conn); + }; +} + +function timeoutHandler(conn) { + return function() { + if (connectionAccounting) deleteConnection(conn.id); + + if (conn.logger.isDebug()) { + conn.logger.debug(`connection ${conn.id} for [${conn.address}] timed out`); + } + + conn.timedOut = true; + conn.emit( + 'timeout', + new MongoNetworkTimeoutError(`connection ${conn.id} to ${conn.address} timed out`, { + beforeHandshake: conn.ismaster == null + }), + conn + ); + }; +} + +function closeHandler(conn) { + return function(hadError) { + if (connectionAccounting) deleteConnection(conn.id); + + if (conn.logger.isDebug()) { + conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`); + } + + if (!hadError) { + conn.emit( + 'close', + new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`), + conn + ); + } + }; +} + +// Handle a message once it is received +function processMessage(conn, message) { + const msgHeader = parseHeader(message); + if (msgHeader.opCode !== OP_COMPRESSED) { + const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; + conn.emit( + 'message', + new ResponseConstructor( + conn.bson, + message, + msgHeader, + message.slice(MESSAGE_HEADER_SIZE), + conn.responseOptions + ), + conn + ); + + return; + } + + msgHeader.fromCompressed = true; + let index = MESSAGE_HEADER_SIZE; + msgHeader.opCode = message.readInt32LE(index); + index += 4; + msgHeader.length = message.readInt32LE(index); + index += 4; + const compressorID = message[index]; + index++; + + decompress(compressorID, message.slice(index), (err, decompressedMsgBody) => { + if (err) { + conn.emit('error', err); + return; + } + + if (decompressedMsgBody.length !== msgHeader.length) { + conn.emit( + 'error', + new MongoError( + 'Decompressing a compressed message from the server failed. The message is corrupt.' + ) + ); + + return; + } + + const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; + conn.emit( + 'message', + new ResponseConstructor( + conn.bson, + message, + msgHeader, + decompressedMsgBody, + conn.responseOptions + ), + conn + ); + }); +} + +function dataHandler(conn) { + return function(data) { + // Parse until we are done with the data + while (data.length > 0) { + // If we still have bytes to read on the current message + if (conn.bytesRead > 0 && conn.sizeOfMessage > 0) { + // Calculate the amount of remaining bytes + const remainingBytesToRead = conn.sizeOfMessage - conn.bytesRead; + // Check if the current chunk contains the rest of the message + if (remainingBytesToRead > data.length) { + // Copy the new data into the exiting buffer (should have been allocated when we know the message size) + data.copy(conn.buffer, conn.bytesRead); + // Adjust the number of bytes read so it point to the correct index in the buffer + conn.bytesRead = conn.bytesRead + data.length; + + // Reset state of buffer + data = Buffer.alloc(0); + } else { + // Copy the missing part of the data into our current buffer + data.copy(conn.buffer, conn.bytesRead, 0, remainingBytesToRead); + // Slice the overflow into a new buffer that we will then re-parse + data = data.slice(remainingBytesToRead); + + // Emit current complete message + const emitBuffer = conn.buffer; + // Reset state of buffer + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + + processMessage(conn, emitBuffer); + } + } else { + // Stub buffer is kept in case we don't get enough bytes to determine the + // size of the message (< 4 bytes) + if (conn.stubBuffer != null && conn.stubBuffer.length > 0) { + // If we have enough bytes to determine the message size let's do it + if (conn.stubBuffer.length + data.length > 4) { + // Prepad the data + const newData = Buffer.alloc(conn.stubBuffer.length + data.length); + conn.stubBuffer.copy(newData, 0); + data.copy(newData, conn.stubBuffer.length); + // Reassign for parsing + data = newData; + + // Reset state of buffer + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + } else { + // Add the the bytes to the stub buffer + const newStubBuffer = Buffer.alloc(conn.stubBuffer.length + data.length); + // Copy existing stub buffer + conn.stubBuffer.copy(newStubBuffer, 0); + // Copy missing part of the data + data.copy(newStubBuffer, conn.stubBuffer.length); + // Exit parsing loop + data = Buffer.alloc(0); + } + } else { + if (data.length > 4) { + // Retrieve the message size + const sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); + // If we have a negative sizeOfMessage emit error and return + if (sizeOfMessage < 0 || sizeOfMessage > conn.maxBsonMessageSize) { + const errorObject = { + err: 'socketHandler', + trace: '', + bin: conn.buffer, + parseState: { + sizeOfMessage: sizeOfMessage, + bytesRead: conn.bytesRead, + stubBuffer: conn.stubBuffer + } + }; + // We got a parse Error fire it off then keep going + conn.emit('parseError', errorObject, conn); + return; + } + + // Ensure that the size of message is larger than 0 and less than the max allowed + if ( + sizeOfMessage > 4 && + sizeOfMessage < conn.maxBsonMessageSize && + sizeOfMessage > data.length + ) { + conn.buffer = Buffer.alloc(sizeOfMessage); + // Copy all the data into the buffer + data.copy(conn.buffer, 0); + // Update bytes read + conn.bytesRead = data.length; + // Update sizeOfMessage + conn.sizeOfMessage = sizeOfMessage; + // Ensure stub buffer is null + conn.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + } else if ( + sizeOfMessage > 4 && + sizeOfMessage < conn.maxBsonMessageSize && + sizeOfMessage === data.length + ) { + const emitBuffer = data; + // Reset state of buffer + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + // Emit the message + processMessage(conn, emitBuffer); + } else if (sizeOfMessage <= 4 || sizeOfMessage > conn.maxBsonMessageSize) { + const errorObject = { + err: 'socketHandler', + trace: null, + bin: data, + parseState: { + sizeOfMessage: sizeOfMessage, + bytesRead: 0, + buffer: null, + stubBuffer: null + } + }; + // We got a parse Error fire it off then keep going + conn.emit('parseError', errorObject, conn); + + // Clear out the state of the parser + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + } else { + const emitBuffer = data.slice(0, sizeOfMessage); + // Reset state of buffer + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + // Copy rest of message + data = data.slice(sizeOfMessage); + // Emit the message + processMessage(conn, emitBuffer); + } + } else { + // Create a buffer that contains the space for the non-complete message + conn.stubBuffer = Buffer.alloc(data.length); + // Copy the data to the stub buffer + data.copy(conn.stubBuffer, 0); + // Exit parsing loop + data = Buffer.alloc(0); + } + } + } + } + }; +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Connection#connect + * @type {Connection} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Connection#close + * @type {Connection} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Connection#error + * @type {Connection} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Connection#timeout + * @type {Connection} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Connection#parseError + * @type {Connection} + */ + +/** + * An event emitted each time the connection receives a parsed message from the wire + * + * @event Connection#message + * @type {Connection} + */ + +module.exports = Connection; + + +/***/ }), + +/***/ 104: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var f = __webpack_require__(1669).format, + MongoError = __webpack_require__(3111).MongoError; + +// Filters for classes +var classFilters = {}; +var filteredClasses = {}; +var level = null; +// Save the process id +var pid = process.pid; +// current logger +var currentLogger = null; + +/** + * @callback Logger~loggerCallback + * @param {string} msg message being logged + * @param {object} state an object containing more metadata about the logging message + */ + +/** + * Creates a new Logger instance + * @class + * @param {string} className The Class name associated with the logging instance + * @param {object} [options=null] Optional settings. + * @param {Logger~loggerCallback} [options.logger=null] Custom logger function; + * @param {string} [options.loggerLevel=error] Override default global log level. + */ +var Logger = function(className, options) { + if (!(this instanceof Logger)) return new Logger(className, options); + options = options || {}; + + // Current reference + this.className = className; + + // Current logger + if (options.logger) { + currentLogger = options.logger; + } else if (currentLogger == null) { + currentLogger = console.log; + } + + // Set level of logging, default is error + if (options.loggerLevel) { + level = options.loggerLevel || 'error'; + } + + // Add all class names + if (filteredClasses[this.className] == null) classFilters[this.className] = true; +}; + +/** + * Log a message at the debug level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.debug = function(message, object) { + if ( + this.isDebug() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); + var state = { + type: 'debug', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } +}; + +/** + * Log a message at the warn level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +(Logger.prototype.warn = function(message, object) { + if ( + this.isWarn() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); + var state = { + type: 'warn', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } +}), + /** + * Log a message at the info level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ + (Logger.prototype.info = function(message, object) { + if ( + this.isInfo() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); + var state = { + type: 'info', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } + }), + /** + * Log a message at the error level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ + (Logger.prototype.error = function(message, object) { + if ( + this.isError() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); + var state = { + type: 'error', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } + }), + /** + * Is the logger set at info level + * @method + * @return {boolean} + */ + (Logger.prototype.isInfo = function() { + return level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at error level + * @method + * @return {boolean} + */ + (Logger.prototype.isError = function() { + return level === 'error' || level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at error level + * @method + * @return {boolean} + */ + (Logger.prototype.isWarn = function() { + return level === 'error' || level === 'warn' || level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at debug level + * @method + * @return {boolean} + */ + (Logger.prototype.isDebug = function() { + return level === 'debug'; + }); + +/** + * Resets the logger to default settings, error and no filtered classes + * @method + * @return {null} + */ +Logger.reset = function() { + level = 'error'; + filteredClasses = {}; +}; + +/** + * Get the current logger function + * @method + * @return {Logger~loggerCallback} + */ +Logger.currentLogger = function() { + return currentLogger; +}; + +/** + * Set the current logger function + * @method + * @param {Logger~loggerCallback} logger Logger function. + * @return {null} + */ +Logger.setCurrentLogger = function(logger) { + if (typeof logger !== 'function') throw new MongoError('current logger must be a function'); + currentLogger = logger; +}; + +/** + * Set what classes to log. + * @method + * @param {string} type The type of filter (currently only class) + * @param {string[]} values The filters to apply + * @return {null} + */ +Logger.filter = function(type, values) { + if (type === 'class' && Array.isArray(values)) { + filteredClasses = {}; + + values.forEach(function(x) { + filteredClasses[x] = true; + }); + } +}; + +/** + * Set the current log level + * @method + * @param {string} level Set current log level (debug, info, error) + * @return {null} + */ +Logger.setLevel = function(_level) { + if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') { + throw new Error(f('%s is an illegal logging level', _level)); + } + + level = _level; +}; + +module.exports = Logger; + + +/***/ }), + +/***/ 8988: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// Implementation of OP_MSG spec: +// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst +// +// struct Section { +// uint8 payloadType; +// union payload { +// document document; // payloadType == 0 +// struct sequence { // payloadType == 1 +// int32 size; +// cstring identifier; +// document* documents; +// }; +// }; +// }; + +// struct OP_MSG { +// struct MsgHeader { +// int32 messageLength; +// int32 requestID; +// int32 responseTo; +// int32 opCode = 2013; +// }; +// uint32 flagBits; +// Section+ sections; +// [uint32 checksum;] +// }; + +const Buffer = __webpack_require__(1867).Buffer; +const opcodes = __webpack_require__(7272).opcodes; +const databaseNamespace = __webpack_require__(7272).databaseNamespace; +const ReadPreference = __webpack_require__(4485); + +// Incrementing request id +let _requestId = 0; + +// Msg Flags +const OPTS_CHECKSUM_PRESENT = 1; +const OPTS_MORE_TO_COME = 2; +const OPTS_EXHAUST_ALLOWED = 1 << 16; + +class Msg { + constructor(bson, ns, command, options) { + // Basic options needed to be passed in + if (command == null) throw new Error('query must be specified for query'); + + // Basic options + this.bson = bson; + this.ns = ns; + this.command = command; + this.command.$db = databaseNamespace(ns); + + if (options.readPreference && options.readPreference.mode !== ReadPreference.PRIMARY) { + this.command.$readPreference = options.readPreference.toJSON(); + } + + // Ensure empty options + this.options = options || {}; + + // Additional options + this.requestId = options.requestId ? options.requestId : Msg.getRequestId(); + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + + // flags + this.checksumPresent = false; + this.moreToCome = options.moreToCome || false; + this.exhaustAllowed = + typeof options.exhaustAllowed === 'boolean' ? options.exhaustAllowed : false; + } + + toBin() { + const buffers = []; + let flags = 0; + + if (this.checksumPresent) { + flags |= OPTS_CHECKSUM_PRESENT; + } + + if (this.moreToCome) { + flags |= OPTS_MORE_TO_COME; + } + + if (this.exhaustAllowed) { + flags |= OPTS_EXHAUST_ALLOWED; + } + + const header = Buffer.alloc( + 4 * 4 + // Header + 4 // Flags + ); + + buffers.push(header); + + let totalLength = header.length; + const command = this.command; + totalLength += this.makeDocumentSegment(buffers, command); + + header.writeInt32LE(totalLength, 0); // messageLength + header.writeInt32LE(this.requestId, 4); // requestID + header.writeInt32LE(0, 8); // responseTo + header.writeInt32LE(opcodes.OP_MSG, 12); // opCode + header.writeUInt32LE(flags, 16); // flags + return buffers; + } + + makeDocumentSegment(buffers, document) { + const payloadTypeBuffer = Buffer.alloc(1); + payloadTypeBuffer[0] = 0; + + const documentBuffer = this.serializeBson(document); + buffers.push(payloadTypeBuffer); + buffers.push(documentBuffer); + + return payloadTypeBuffer.length + documentBuffer.length; + } + + serializeBson(document) { + return this.bson.serialize(document, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + } +} + +Msg.getRequestId = function() { + _requestId = (_requestId + 1) & 0x7fffffff; + return _requestId; +}; + +class BinMsg { + constructor(bson, message, msgHeader, msgBody, opts) { + opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.bson = bson; + this.opts = opts; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Read response flags + this.responseFlags = msgBody.readInt32LE(0); + this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; + this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; + this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; + this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; + this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; + this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; + + this.documents = []; + } + + isParsed() { + return this.parsed; + } + + parse(options) { + // Don't parse again if not needed + if (this.parsed) return; + options = options || {}; + + this.index = 4; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const promoteLongs = + typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; + const promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; + const promoteBuffers = + typeof options.promoteBuffers === 'boolean' + ? options.promoteBuffers + : this.opts.promoteBuffers; + + // Set up the options + const _options = { + promoteLongs: promoteLongs, + promoteValues: promoteValues, + promoteBuffers: promoteBuffers + }; + + while (this.index < this.data.length) { + const payloadType = this.data.readUInt8(this.index++); + if (payloadType === 1) { + console.error('TYPE 1'); + } else if (payloadType === 0) { + const bsonSize = this.data.readUInt32LE(this.index); + const bin = this.data.slice(this.index, this.index + bsonSize); + this.documents.push(raw ? bin : this.bson.deserialize(bin, _options)); + + this.index += bsonSize; + } + } + + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + const doc = this.bson.deserialize(this.documents[0], _options); + this.documents = [doc]; + } + + this.parsed = true; + } +} + +module.exports = { Msg, BinMsg }; + + +/***/ }), + +/***/ 5500: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const inherits = __webpack_require__(1669).inherits; +const EventEmitter = __webpack_require__(8614).EventEmitter; +const MongoError = __webpack_require__(3111).MongoError; +const MongoTimeoutError = __webpack_require__(3111).MongoTimeoutError; +const MongoWriteConcernError = __webpack_require__(3111).MongoWriteConcernError; +const Logger = __webpack_require__(104); +const f = __webpack_require__(1669).format; +const Msg = __webpack_require__(8988).Msg; +const CommandResult = __webpack_require__(2337); +const MESSAGE_HEADER_SIZE = __webpack_require__(7272).MESSAGE_HEADER_SIZE; +const COMPRESSION_DETAILS_SIZE = __webpack_require__(7272).COMPRESSION_DETAILS_SIZE; +const opcodes = __webpack_require__(7272).opcodes; +const compress = __webpack_require__(7793).compress; +const compressorIDs = __webpack_require__(7793).compressorIDs; +const uncompressibleCommands = __webpack_require__(7793).uncompressibleCommands; +const apm = __webpack_require__(9815); +const Buffer = __webpack_require__(1867).Buffer; +const connect = __webpack_require__(6573); +const updateSessionFromResponse = __webpack_require__(5474).updateSessionFromResponse; +const eachAsync = __webpack_require__(1178).eachAsync; +const makeStateMachine = __webpack_require__(1178).makeStateMachine; +const now = __webpack_require__(1371).now; + +const DISCONNECTED = 'disconnected'; +const CONNECTING = 'connecting'; +const CONNECTED = 'connected'; +const DRAINING = 'draining'; +const DESTROYING = 'destroying'; +const DESTROYED = 'destroyed'; +const stateTransition = makeStateMachine({ + [DISCONNECTED]: [CONNECTING, DRAINING, DISCONNECTED], + [CONNECTING]: [CONNECTING, CONNECTED, DRAINING, DISCONNECTED], + [CONNECTED]: [CONNECTED, DISCONNECTED, DRAINING], + [DRAINING]: [DRAINING, DESTROYING, DESTROYED], + [DESTROYING]: [DESTROYING, DESTROYED], + [DESTROYED]: [DESTROYED] +}); + +const CONNECTION_EVENTS = new Set([ + 'error', + 'close', + 'timeout', + 'parseError', + 'connect', + 'message' +]); + +var _id = 0; + +/** + * Creates a new Pool instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Max server connection pool size + * @param {number} [options.minSize=0] Minimum server connection pool size + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @fires Pool#connect + * @fires Pool#close + * @fires Pool#error + * @fires Pool#timeout + * @fires Pool#parseError + * @return {Pool} A cursor instance + */ +var Pool = function(topology, options) { + // Add event listener + EventEmitter.call(this); + + // Store topology for later use + this.topology = topology; + + this.s = { + state: DISCONNECTED, + cancellationToken: new EventEmitter() + }; + + // we don't care how many connections are listening for cancellation + this.s.cancellationToken.setMaxListeners(Infinity); + + // Add the options + this.options = Object.assign( + { + // Host and port settings + host: 'localhost', + port: 27017, + // Pool default max size + size: 5, + // Pool default min size + minSize: 0, + // socket settings + connectionTimeout: 30000, + socketTimeout: 360000, + keepAlive: true, + keepAliveInitialDelay: 120000, + noDelay: true, + // SSL Settings + ssl: false, + checkServerIdentity: true, + ca: null, + crl: null, + cert: null, + key: null, + passphrase: null, + rejectUnauthorized: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + // Reconnection options + reconnect: true, + reconnectInterval: 1000, + reconnectTries: 30, + // Enable domains + domainsEnabled: false, + // feature flag for determining if we are running with the unified topology or not + legacyCompatMode: true + }, + options + ); + + // Identification information + this.id = _id++; + // Current reconnect retries + this.retriesLeft = this.options.reconnectTries; + this.reconnectId = null; + this.reconnectError = null; + // No bson parser passed in + if ( + !options.bson || + (options.bson && + (typeof options.bson.serialize !== 'function' || + typeof options.bson.deserialize !== 'function')) + ) { + throw new Error('must pass in valid bson parser'); + } + + // Logger instance + this.logger = Logger('Pool', options); + // Connections + this.availableConnections = []; + this.inUseConnections = []; + this.connectingConnections = 0; + // Currently executing + this.executing = false; + // Operation work queue + this.queue = []; + + // Number of consecutive timeouts caught + this.numberOfConsecutiveTimeouts = 0; + // Current pool Index + this.connectionIndex = 0; + + // event handlers + const pool = this; + this._messageHandler = messageHandler(this); + this._connectionCloseHandler = function(err) { + const connection = this; + connectionFailureHandler(pool, 'close', err, connection); + }; + + this._connectionErrorHandler = function(err) { + const connection = this; + connectionFailureHandler(pool, 'error', err, connection); + }; + + this._connectionTimeoutHandler = function(err) { + const connection = this; + connectionFailureHandler(pool, 'timeout', err, connection); + }; + + this._connectionParseErrorHandler = function(err) { + const connection = this; + connectionFailureHandler(pool, 'parseError', err, connection); + }; +}; + +inherits(Pool, EventEmitter); + +Object.defineProperty(Pool.prototype, 'size', { + enumerable: true, + get: function() { + return this.options.size; + } +}); + +Object.defineProperty(Pool.prototype, 'minSize', { + enumerable: true, + get: function() { + return this.options.minSize; + } +}); + +Object.defineProperty(Pool.prototype, 'connectionTimeout', { + enumerable: true, + get: function() { + return this.options.connectionTimeout; + } +}); + +Object.defineProperty(Pool.prototype, 'socketTimeout', { + enumerable: true, + get: function() { + return this.options.socketTimeout; + } +}); + +Object.defineProperty(Pool.prototype, 'state', { + enumerable: true, + get: function() { + return this.s.state; + } +}); + +// clears all pool state +function resetPoolState(pool) { + pool.inUseConnections = []; + pool.availableConnections = []; + pool.connectingConnections = 0; + pool.executing = false; + pool.numberOfConsecutiveTimeouts = 0; + pool.connectionIndex = 0; + pool.retriesLeft = pool.options.reconnectTries; + pool.reconnectId = null; +} + +function connectionFailureHandler(pool, event, err, conn) { + if (conn) { + if (conn._connectionFailHandled) { + return; + } + + conn._connectionFailHandled = true; + conn.destroy(); + + // Remove the connection + removeConnection(pool, conn); + + // flush remaining work items + conn.flush(err); + } + + // Did we catch a timeout, increment the numberOfConsecutiveTimeouts + if (event === 'timeout') { + pool.numberOfConsecutiveTimeouts = pool.numberOfConsecutiveTimeouts + 1; + + // Have we timed out more than reconnectTries in a row ? + // Force close the pool as we are trying to connect to tcp sink hole + if (pool.numberOfConsecutiveTimeouts > pool.options.reconnectTries) { + pool.numberOfConsecutiveTimeouts = 0; + // Destroy all connections and pool + pool.destroy(true); + // Emit close event + return pool.emit('close', pool); + } + } + + // No more socket available propegate the event + if (pool.socketCount() === 0) { + if (pool.state !== DESTROYED && pool.state !== DESTROYING && pool.state !== DRAINING) { + if (pool.options.reconnect) { + stateTransition(pool, DISCONNECTED); + } + } + + // Do not emit error events, they are always close events + // do not trigger the low level error handler in node + event = event === 'error' ? 'close' : event; + pool.emit(event, err); + } + + // Start reconnection attempts + if (!pool.reconnectId && pool.options.reconnect) { + pool.reconnectError = err; + pool.reconnectId = setTimeout(attemptReconnect(pool), pool.options.reconnectInterval); + } + + // Do we need to do anything to maintain the minimum pool size + const totalConnections = totalConnectionCount(pool); + if (totalConnections < pool.minSize) { + createConnection(pool); + } +} + +function attemptReconnect(pool, callback) { + return function() { + pool.emit('attemptReconnect', pool); + + if (pool.state === DESTROYED || pool.state === DESTROYING) { + if (typeof callback === 'function') { + callback(new MongoError('Cannot create connection when pool is destroyed')); + } + + return; + } + + pool.retriesLeft = pool.retriesLeft - 1; + if (pool.retriesLeft <= 0) { + pool.destroy(); + + const error = new MongoTimeoutError( + `failed to reconnect after ${pool.options.reconnectTries} attempts with interval ${pool.options.reconnectInterval} ms`, + pool.reconnectError + ); + + pool.emit('reconnectFailed', error); + if (typeof callback === 'function') { + callback(error); + } + + return; + } + + // clear the reconnect id on retry + pool.reconnectId = null; + + // now retry creating a connection + createConnection(pool, (err, conn) => { + if (err == null) { + pool.reconnectId = null; + pool.retriesLeft = pool.options.reconnectTries; + pool.emit('reconnect', pool); + } + + if (typeof callback === 'function') { + callback(err, conn); + } + }); + }; +} + +function moveConnectionBetween(connection, from, to) { + var index = from.indexOf(connection); + // Move the connection from connecting to available + if (index !== -1) { + from.splice(index, 1); + to.push(connection); + } +} + +function messageHandler(self) { + return function(message, connection) { + // workItem to execute + var workItem = null; + + // Locate the workItem + for (var i = 0; i < connection.workItems.length; i++) { + if (connection.workItems[i].requestId === message.responseTo) { + // Get the callback + workItem = connection.workItems[i]; + // Remove from list of workItems + connection.workItems.splice(i, 1); + } + } + + if (workItem && workItem.monitoring) { + moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); + } + + // Reset timeout counter + self.numberOfConsecutiveTimeouts = 0; + + // Reset the connection timeout if we modified it for + // this operation + if (workItem && workItem.socketTimeout) { + connection.resetSocketTimeout(); + } + + // Log if debug enabled + if (self.logger.isDebug()) { + self.logger.debug( + f( + 'message [%s] received from %s:%s', + message.raw.toString('hex'), + self.options.host, + self.options.port + ) + ); + } + + function handleOperationCallback(self, cb, err, result) { + // No domain enabled + if (!self.options.domainsEnabled) { + return process.nextTick(function() { + return cb(err, result); + }); + } + + // Domain enabled just call the callback + cb(err, result); + } + + // Keep executing, ensure current message handler does not stop execution + if (!self.executing) { + process.nextTick(function() { + _execute(self)(); + }); + } + + // Time to dispatch the message if we have a callback + if (workItem && !workItem.immediateRelease) { + try { + // Parse the message according to the provided options + message.parse(workItem); + } catch (err) { + return handleOperationCallback(self, workItem.cb, new MongoError(err)); + } + + if (message.documents[0]) { + const document = message.documents[0]; + const session = workItem.session; + if (session) { + updateSessionFromResponse(session, document); + } + + if (self.topology && document.$clusterTime) { + self.topology.clusterTime = document.$clusterTime; + } + } + + // Establish if we have an error + if (workItem.command && message.documents[0]) { + const responseDoc = message.documents[0]; + + if (responseDoc.writeConcernError) { + const err = new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc); + return handleOperationCallback(self, workItem.cb, err); + } + + if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) { + return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc)); + } + } + + // Add the connection details + message.hashedName = connection.hashedName; + + // Return the documents + handleOperationCallback( + self, + workItem.cb, + null, + new CommandResult(workItem.fullResult ? message : message.documents[0], connection, message) + ); + } + }; +} + +/** + * Return the total socket count in the pool. + * @method + * @return {Number} The number of socket available. + */ +Pool.prototype.socketCount = function() { + return this.availableConnections.length + this.inUseConnections.length; + // + this.connectingConnections.length; +}; + +function totalConnectionCount(pool) { + return ( + pool.availableConnections.length + pool.inUseConnections.length + pool.connectingConnections + ); +} + +/** + * Return all pool connections + * @method + * @return {Connection[]} The pool connections + */ +Pool.prototype.allConnections = function() { + return this.availableConnections.concat(this.inUseConnections); +}; + +/** + * Get a pool connection (round-robin) + * @method + * @return {Connection} + */ +Pool.prototype.get = function() { + return this.allConnections()[0]; +}; + +/** + * Is the pool connected + * @method + * @return {boolean} + */ +Pool.prototype.isConnected = function() { + // We are in a destroyed state + if (this.state === DESTROYED || this.state === DESTROYING) { + return false; + } + + // Get connections + var connections = this.availableConnections.concat(this.inUseConnections); + + // Check if we have any connected connections + for (var i = 0; i < connections.length; i++) { + if (connections[i].isConnected()) return true; + } + + // Not connected + return false; +}; + +/** + * Was the pool destroyed + * @method + * @return {boolean} + */ +Pool.prototype.isDestroyed = function() { + return this.state === DESTROYED || this.state === DESTROYING; +}; + +/** + * Is the pool in a disconnected state + * @method + * @return {boolean} + */ +Pool.prototype.isDisconnected = function() { + return this.state === DISCONNECTED; +}; + +/** + * Connect pool + */ +Pool.prototype.connect = function(callback) { + if (this.state !== DISCONNECTED) { + throw new MongoError('connection in unlawful state ' + this.state); + } + + stateTransition(this, CONNECTING); + createConnection(this, (err, conn) => { + if (err) { + if (typeof callback === 'function') { + this.destroy(); + callback(err); + return; + } + + if (this.state === CONNECTING) { + this.emit('error', err); + } + + this.destroy(); + return; + } + + stateTransition(this, CONNECTED); + + // create min connections + if (this.minSize) { + for (let i = 0; i < this.minSize; i++) { + createConnection(this); + } + } + + if (typeof callback === 'function') { + callback(null, conn); + } else { + this.emit('connect', this, conn); + } + }); +}; + +/** + * Authenticate using a specified mechanism + * @param {authResultCallback} callback A callback function + */ +Pool.prototype.auth = function(credentials, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +/** + * Logout all users against a database + * @param {authResultCallback} callback A callback function + */ +Pool.prototype.logout = function(dbName, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +/** + * Unref the pool + * @method + */ +Pool.prototype.unref = function() { + // Get all the known connections + var connections = this.availableConnections.concat(this.inUseConnections); + + connections.forEach(function(c) { + c.unref(); + }); +}; + +// Destroy the connections +function destroy(self, connections, options, callback) { + stateTransition(self, DESTROYING); + + // indicate that in-flight connections should cancel + self.s.cancellationToken.emit('cancel'); + + eachAsync( + connections, + (conn, cb) => { + for (const eventName of CONNECTION_EVENTS) { + conn.removeAllListeners(eventName); + } + + // ignore any errors during destruction + conn.on('error', () => {}); + + conn.destroy(options, cb); + }, + err => { + if (err) { + if (typeof callback === 'function') callback(err, null); + return; + } + + resetPoolState(self); + self.queue = []; + + stateTransition(self, DESTROYED); + if (typeof callback === 'function') callback(null, null); + } + ); +} + +/** + * Destroy pool + * @method + */ +Pool.prototype.destroy = function(force, callback) { + var self = this; + if (typeof force === 'function') { + callback = force; + force = false; + } + + // Do not try again if the pool is already dead + if (this.state === DESTROYED || self.state === DESTROYING) { + if (typeof callback === 'function') callback(null, null); + return; + } + + // Set state to draining + stateTransition(this, DRAINING); + + // Are we force closing + if (force) { + // Get all the known connections + var connections = self.availableConnections.concat(self.inUseConnections); + + // Flush any remaining work items with + // an error + while (self.queue.length > 0) { + var workItem = self.queue.shift(); + if (typeof workItem.cb === 'function') { + workItem.cb(new MongoError('Pool was force destroyed')); + } + } + + // Destroy the topology + return destroy(self, connections, { force: true }, callback); + } + + // Clear out the reconnect if set + if (this.reconnectId) { + clearTimeout(this.reconnectId); + } + + // Wait for the operations to drain before we close the pool + function checkStatus() { + if (self.state === DESTROYED || self.state === DESTROYING) { + if (typeof callback === 'function') { + callback(); + } + + return; + } + + flushMonitoringOperations(self.queue); + + if (self.queue.length === 0) { + // Get all the known connections + var connections = self.availableConnections.concat(self.inUseConnections); + + // Check if we have any in flight operations + for (var i = 0; i < connections.length; i++) { + // There is an operation still in flight, reschedule a + // check waiting for it to drain + if (connections[i].workItems.length > 0) { + return setTimeout(checkStatus, 1); + } + } + + destroy(self, connections, { force: false }, callback); + } else { + // Ensure we empty the queue + _execute(self)(); + // Set timeout + setTimeout(checkStatus, 1); + } + } + + // Initiate drain of operations + checkStatus(); +}; + +/** + * Reset all connections of this pool + * + * @param {function} [callback] + */ +Pool.prototype.reset = function(callback) { + if (this.s.state !== CONNECTED) { + if (typeof callback === 'function') { + callback(new MongoError('pool is not connected, reset aborted')); + } + + return; + } + + // signal in-flight connections should be cancelled + this.s.cancellationToken.emit('cancel'); + + // destroy existing connections + const connections = this.availableConnections.concat(this.inUseConnections); + eachAsync( + connections, + (conn, cb) => { + for (const eventName of CONNECTION_EVENTS) { + conn.removeAllListeners(eventName); + } + + conn.destroy({ force: true }, cb); + }, + err => { + if (err) { + if (typeof callback === 'function') { + callback(err, null); + return; + } + } + + resetPoolState(this); + + // create a new connection, this will ultimately trigger execution + createConnection(this, () => { + if (typeof callback === 'function') { + callback(null, null); + } + }); + } + ); +}; + +// Prepare the buffer that Pool.prototype.write() uses to send to the server +function serializeCommand(self, command, callback) { + const originalCommandBuffer = command.toBin(); + + // Check whether we and the server have agreed to use a compressor + const shouldCompress = !!self.options.agreedCompressor; + if (!shouldCompress || !canCompress(command)) { + return callback(null, originalCommandBuffer); + } + + // Transform originalCommandBuffer into OP_COMPRESSED + const concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer); + const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); + + // Extract information needed for OP_COMPRESSED from the uncompressed message + const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); + + // Compress the message body + compress(self, messageToBeCompressed, function(err, compressedMessage) { + if (err) return callback(err, null); + + // Create the msgHeader of OP_COMPRESSED + const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); + msgHeader.writeInt32LE( + MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, + 0 + ); // messageLength + msgHeader.writeInt32LE(command.requestId, 4); // requestID + msgHeader.writeInt32LE(0, 8); // responseTo (zero) + msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode + + // Create the compression details of OP_COMPRESSED + const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); + compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode + compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader + compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID + + return callback(null, [msgHeader, compressionDetails, compressedMessage]); + }); +} + +/** + * Write a message to MongoDB + * @method + * @return {Connection} + */ +Pool.prototype.write = function(command, options, cb) { + var self = this; + // Ensure we have a callback + if (typeof options === 'function') { + cb = options; + } + + // Always have options + options = options || {}; + + // We need to have a callback function unless the message returns no response + if (!(typeof cb === 'function') && !options.noResponse) { + throw new MongoError('write method must provide a callback'); + } + + // Pool was destroyed error out + if (this.state === DESTROYED || this.state === DESTROYING) { + cb(new MongoError('pool destroyed')); + return; + } + + if (this.state === DRAINING) { + cb(new MongoError('pool is draining, new operations prohibited')); + return; + } + + if (this.options.domainsEnabled && process.domain && typeof cb === 'function') { + // if we have a domain bind to it + var oldCb = cb; + cb = process.domain.bind(function() { + // v8 - argumentsToArray one-liner + var args = new Array(arguments.length); + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + // bounce off event loop so domain switch takes place + process.nextTick(function() { + oldCb.apply(null, args); + }); + }); + } + + // Do we have an operation + var operation = { + cb: cb, + raw: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + fullResult: false + }; + + // Set the options for the parsing + operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true; + operation.promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : true; + operation.promoteBuffers = + typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false; + operation.raw = typeof options.raw === 'boolean' ? options.raw : false; + operation.immediateRelease = + typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false; + operation.documentsReturnedIn = options.documentsReturnedIn; + operation.command = typeof options.command === 'boolean' ? options.command : false; + operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false; + operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false; + operation.session = options.session || null; + + // Optional per operation socketTimeout + operation.socketTimeout = options.socketTimeout; + operation.monitoring = options.monitoring; + + // Get the requestId + operation.requestId = command.requestId; + + // If command monitoring is enabled we need to modify the callback here + if (self.options.monitorCommands) { + this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); + + operation.started = now(); + operation.cb = (err, reply) => { + if (err) { + self.emit( + 'commandFailed', + new apm.CommandFailedEvent(this, command, err, operation.started) + ); + } else { + if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { + self.emit( + 'commandFailed', + new apm.CommandFailedEvent(this, command, reply.result, operation.started) + ); + } else { + self.emit( + 'commandSucceeded', + new apm.CommandSucceededEvent(this, command, reply, operation.started) + ); + } + } + + if (typeof cb === 'function') cb(err, reply); + }; + } + + // Prepare the operation buffer + serializeCommand(self, command, (err, serializedBuffers) => { + if (err) throw err; + + // Set the operation's buffer to the serialization of the commands + operation.buffer = serializedBuffers; + + // If we have a monitoring operation schedule as the very first operation + // Otherwise add to back of queue + if (options.monitoring) { + self.queue.unshift(operation); + } else { + self.queue.push(operation); + } + + // Attempt to execute the operation + if (!self.executing) { + process.nextTick(function() { + _execute(self)(); + }); + } + }); +}; + +// Return whether a command contains an uncompressible command term +// Will return true if command contains no uncompressible command terms +function canCompress(command) { + const commandDoc = command instanceof Msg ? command.command : command.query; + const commandName = Object.keys(commandDoc)[0]; + return !uncompressibleCommands.has(commandName); +} + +// Remove connection method +function remove(connection, connections) { + for (var i = 0; i < connections.length; i++) { + if (connections[i] === connection) { + connections.splice(i, 1); + return true; + } + } +} + +function removeConnection(self, connection) { + if (remove(connection, self.availableConnections)) return; + if (remove(connection, self.inUseConnections)) return; +} + +function createConnection(pool, callback) { + if (pool.state === DESTROYED || pool.state === DESTROYING) { + if (typeof callback === 'function') { + callback(new MongoError('Cannot create connection when pool is destroyed')); + } + + return; + } + + pool.connectingConnections++; + connect(pool.options, pool.s.cancellationToken, (err, connection) => { + pool.connectingConnections--; + + if (err) { + if (pool.logger.isDebug()) { + pool.logger.debug(`connection attempt failed with error [${JSON.stringify(err)}]`); + } + + // check if reconnect is enabled, and attempt retry if so + if (!pool.reconnectId && pool.options.reconnect) { + if (pool.state === CONNECTING && pool.options.legacyCompatMode) { + callback(err); + return; + } + + pool.reconnectError = err; + pool.reconnectId = setTimeout( + attemptReconnect(pool, callback), + pool.options.reconnectInterval + ); + + return; + } + + if (typeof callback === 'function') { + callback(err); + } + + return; + } + + // the pool might have been closed since we started creating the connection + if (pool.state === DESTROYED || pool.state === DESTROYING) { + if (typeof callback === 'function') { + callback(new MongoError('Pool was destroyed after connection creation')); + } + + connection.destroy(); + return; + } + + // otherwise, connect relevant event handlers and add it to our available connections + connection.on('error', pool._connectionErrorHandler); + connection.on('close', pool._connectionCloseHandler); + connection.on('timeout', pool._connectionTimeoutHandler); + connection.on('parseError', pool._connectionParseErrorHandler); + connection.on('message', pool._messageHandler); + + pool.availableConnections.push(connection); + + // if a callback was provided, return the connection + if (typeof callback === 'function') { + callback(null, connection); + } + + // immediately execute any waiting work + _execute(pool)(); + }); +} + +function flushMonitoringOperations(queue) { + for (var i = 0; i < queue.length; i++) { + if (queue[i].monitoring) { + var workItem = queue[i]; + queue.splice(i, 1); + workItem.cb( + new MongoError({ message: 'no connection available for monitoring', driver: true }) + ); + } + } +} + +function _execute(self) { + return function() { + if (self.state === DESTROYED) return; + // Already executing, skip + if (self.executing) return; + // Set pool as executing + self.executing = true; + + // New pool connections are in progress, wait them to finish + // before executing any more operation to ensure distribution of + // operations + if (self.connectingConnections > 0) { + self.executing = false; + return; + } + + // As long as we have available connections + // eslint-disable-next-line + while (true) { + // Total availble connections + const totalConnections = totalConnectionCount(self); + + // No available connections available, flush any monitoring ops + if (self.availableConnections.length === 0) { + // Flush any monitoring operations + flushMonitoringOperations(self.queue); + + // Try to create a new connection to execute stuck operation + if (totalConnections < self.options.size && self.queue.length > 0) { + createConnection(self); + } + + break; + } + + // No queue break + if (self.queue.length === 0) { + break; + } + + var connection = null; + const connections = self.availableConnections.filter(conn => conn.workItems.length === 0); + + // No connection found that has no work on it, just pick one for pipelining + if (connections.length === 0) { + connection = + self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; + } else { + connection = connections[self.connectionIndex++ % connections.length]; + } + + // Is the connection connected + if (!connection.isConnected()) { + // Remove the disconnected connection + removeConnection(self, connection); + // Flush any monitoring operations in the queue, failing fast + flushMonitoringOperations(self.queue); + break; + } + + // Get the next work item + var workItem = self.queue.shift(); + + // If we are monitoring we need to use a connection that is not + // running another operation to avoid socket timeout changes + // affecting an existing operation + if (workItem.monitoring) { + var foundValidConnection = false; + + for (let i = 0; i < self.availableConnections.length; i++) { + // If the connection is connected + // And there are no pending workItems on it + // Then we can safely use it for monitoring. + if ( + self.availableConnections[i].isConnected() && + self.availableConnections[i].workItems.length === 0 + ) { + foundValidConnection = true; + connection = self.availableConnections[i]; + break; + } + } + + // No safe connection found, attempt to grow the connections + // if possible and break from the loop + if (!foundValidConnection) { + // Put workItem back on the queue + self.queue.unshift(workItem); + + // Attempt to grow the pool if it's not yet maxsize + if (totalConnections < self.options.size && self.queue.length > 0) { + // Create a new connection + createConnection(self); + } + + // Re-execute the operation + setTimeout(() => _execute(self)(), 10); + break; + } + } + + // Don't execute operation until we have a full pool + if (totalConnections < self.options.size) { + // Connection has work items, then put it back on the queue + // and create a new connection + if (connection.workItems.length > 0) { + // Lets put the workItem back on the list + self.queue.unshift(workItem); + // Create a new connection + createConnection(self); + // Break from the loop + break; + } + } + + // Get actual binary commands + var buffer = workItem.buffer; + + // If we are monitoring take the connection of the availableConnections + if (workItem.monitoring) { + moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); + } + + // Track the executing commands on the mongo server + // as long as there is an expected response + if (!workItem.noResponse) { + connection.workItems.push(workItem); + } + + // We have a custom socketTimeout + if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') { + connection.setSocketTimeout(workItem.socketTimeout); + } + + // Capture if write was successful + var writeSuccessful = true; + + // Put operation on the wire + if (Array.isArray(buffer)) { + for (let i = 0; i < buffer.length; i++) { + writeSuccessful = connection.write(buffer[i]); + } + } else { + writeSuccessful = connection.write(buffer); + } + + // if the command is designated noResponse, call the callback immeditely + if (workItem.noResponse && typeof workItem.cb === 'function') { + workItem.cb(null, null); + } + + if (writeSuccessful === false) { + // If write not successful put back on queue + self.queue.unshift(workItem); + // Remove the disconnected connection + removeConnection(self, connection); + // Flush any monitoring operations in the queue, failing fast + flushMonitoringOperations(self.queue); + break; + } + } + + self.executing = false; + }; +} + +// Make execution loop available for testing +Pool._execute = _execute; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Pool#connect + * @type {Pool} + */ + +/** + * A server reconnect event, used to verify that pool reconnected. + * + * @event Pool#reconnect + * @type {Pool} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Pool#close + * @type {Pool} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Pool#error + * @type {Pool} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Pool#timeout + * @type {Pool} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Pool#parseError + * @type {Pool} + */ + +/** + * The driver attempted to reconnect + * + * @event Pool#attemptReconnect + * @type {Pool} + */ + +/** + * The driver exhausted all reconnect attempts + * + * @event Pool#reconnectFailed + * @type {Pool} + */ + +module.exports = Pool; + + +/***/ }), + +/***/ 7746: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const require_optional = __webpack_require__(6985); + +function debugOptions(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +function retrieveBSON() { + var BSON = __webpack_require__(4044); + BSON.native = false; + + try { + var optionalBSON = require_optional('bson-ext'); + if (optionalBSON) { + optionalBSON.native = true; + return optionalBSON; + } + } catch (err) {} // eslint-disable-line + + return BSON; +} + +// Throw an error if an attempt to use Snappy is made when Snappy is not installed +function noSnappyWarning() { + throw new Error( + 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.' + ); +} + +// Facilitate loading Snappy optionally +function retrieveSnappy() { + var snappy = null; + try { + snappy = require_optional('snappy'); + } catch (error) {} // eslint-disable-line + if (!snappy) { + snappy = { + compress: noSnappyWarning, + uncompress: noSnappyWarning, + compressSync: noSnappyWarning, + uncompressSync: noSnappyWarning + }; + } + return snappy; +} + +module.exports = { + debugOptions, + retrieveBSON, + retrieveSnappy +}; + + +/***/ }), + +/***/ 4847: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Logger = __webpack_require__(104); +const retrieveBSON = __webpack_require__(7746).retrieveBSON; +const MongoError = __webpack_require__(3111).MongoError; +const MongoNetworkError = __webpack_require__(3111).MongoNetworkError; +const collationNotSupported = __webpack_require__(1178).collationNotSupported; +const ReadPreference = __webpack_require__(4485); +const isUnifiedTopology = __webpack_require__(1178).isUnifiedTopology; +const executeOperation = __webpack_require__(2548); +const Readable = __webpack_require__(2413).Readable; +const SUPPORTS = __webpack_require__(1371).SUPPORTS; +const MongoDBNamespace = __webpack_require__(1371).MongoDBNamespace; +const OperationBase = __webpack_require__(1018).OperationBase; + +const BSON = retrieveBSON(); +const Long = BSON.Long; + +// Possible states for a cursor +const CursorState = { + INIT: 0, + OPEN: 1, + CLOSED: 2, + GET_MORE: 3 +}; + +// +// Handle callback (including any exceptions thrown) +function handleCallback(callback, err, result) { + try { + callback(err, result); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } +} + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. + * + * **CURSORS Cannot directly be instantiated** + */ + +/** + * The core cursor class. All cursors in the driver build off of this one. + * + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +class CoreCursor extends Readable { + /** + * Create a new core `Cursor` instance. + * **NOTE** Not to be instantiated directly + * + * @param {object} topology The server topology instance. + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/| find command documentation} and {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype._next + */ + constructor(topology, ns, cmd, options) { + super({ objectMode: true }); + options = options || {}; + + if (ns instanceof OperationBase) { + this.operation = ns; + ns = this.operation.ns.toString(); + options = this.operation.options; + cmd = this.operation.cmd ? this.operation.cmd : {}; + } + + // Cursor pool + this.pool = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = topology.s.bson; + this.ns = ns; + this.namespace = MongoDBNamespace.fromString(ns); + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.cursorState = { + cursorId: null, + cmd, + documents: options.documents || [], + cursorIndex: 0, + dead: false, + killed: false, + init: false, + notified: false, + limit: options.limit || cmd.limit || 0, + skip: options.skip || cmd.skip || 0, + batchSize: options.batchSize || cmd.batchSize || 1000, + currentLimit: 0, + // Result field name if not a cursor (contains the array of results) + transforms: options.transforms, + raw: options.raw || (cmd && cmd.raw) + }; + + if (typeof options.session === 'object') { + this.cursorState.session = options.session; + } + + // Add promoteLong to cursor state + const topologyOptions = topology.s.options; + if (typeof topologyOptions.promoteLongs === 'boolean') { + this.cursorState.promoteLongs = topologyOptions.promoteLongs; + } else if (typeof options.promoteLongs === 'boolean') { + this.cursorState.promoteLongs = options.promoteLongs; + } + + // Add promoteValues to cursor state + if (typeof topologyOptions.promoteValues === 'boolean') { + this.cursorState.promoteValues = topologyOptions.promoteValues; + } else if (typeof options.promoteValues === 'boolean') { + this.cursorState.promoteValues = options.promoteValues; + } + + // Add promoteBuffers to cursor state + if (typeof topologyOptions.promoteBuffers === 'boolean') { + this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; + } else if (typeof options.promoteBuffers === 'boolean') { + this.cursorState.promoteBuffers = options.promoteBuffers; + } + + if (topologyOptions.reconnect) { + this.cursorState.reconnect = topologyOptions.reconnect; + } + + // Logger + this.logger = Logger('Cursor', topologyOptions); + + // + // Did we pass in a cursor id + if (typeof cmd === 'number') { + this.cursorState.cursorId = Long.fromNumber(cmd); + this.cursorState.lastCursorId = this.cursorState.cursorId; + } else if (cmd instanceof Long) { + this.cursorState.cursorId = cmd; + this.cursorState.lastCursorId = cmd; + } + + // TODO [$5f5fbe42fcabad09c1c241a1]: remove as part of NODE-2104 + if (this.operation) { + this.operation.cursorState = this.cursorState; + } + } + + setCursorBatchSize(value) { + this.cursorState.batchSize = value; + } + + cursorBatchSize() { + return this.cursorState.batchSize; + } + + setCursorLimit(value) { + this.cursorState.limit = value; + } + + cursorLimit() { + return this.cursorState.limit; + } + + setCursorSkip(value) { + this.cursorState.skip = value; + } + + cursorSkip() { + return this.cursorState.skip; + } + + /** + * Retrieve the next document from the cursor + * @method + * @param {resultCallback} callback A callback function + */ + _next(callback) { + nextFunction(this, callback); + } + + /** + * Clone the cursor + * @method + * @return {Cursor} + */ + clone() { + return this.topology.cursor(this.ns, this.cmd, this.options); + } + + /** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ + isDead() { + return this.cursorState.dead === true; + } + + /** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ + isKilled() { + return this.cursorState.killed === true; + } + + /** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ + isNotified() { + return this.cursorState.notified === true; + } + + /** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ + bufferedCount() { + return this.cursorState.documents.length - this.cursorState.cursorIndex; + } + + /** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ + readBufferedDocuments(number) { + const unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; + const length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + let elements = this.cursorState.documents.slice( + this.cursorState.cursorIndex, + this.cursorState.cursorIndex + length + ); + + // Transform the doc with passed in transformation method if provided + if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') { + // Transform all the elements + for (let i = 0; i < elements.length; i++) { + elements[i] = this.cursorState.transforms.doc(elements[i]); + } + } + + // Ensure we do not return any more documents than the limit imposed + // Just return the number of elements up to the limit + if ( + this.cursorState.limit > 0 && + this.cursorState.currentLimit + elements.length > this.cursorState.limit + ) { + elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit); + this.kill(); + } + + // Adjust current limit + this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; + this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; + + // Return elements + return elements; + } + + /** + * Resets local state for this cursor instance, and issues a `killCursors` command to the server + * + * @param {resultCallback} callback A callback function + */ + kill(callback) { + // Set cursor to dead + this.cursorState.dead = true; + this.cursorState.killed = true; + // Remove documents + this.cursorState.documents = []; + + // If no cursor id just return + if ( + this.cursorState.cursorId == null || + this.cursorState.cursorId.isZero() || + this.cursorState.init === false + ) { + if (callback) callback(null, null); + return; + } + + this.server.killCursors(this.ns, this.cursorState, callback); + } + + /** + * Resets the cursor + */ + rewind() { + if (this.cursorState.init) { + if (!this.cursorState.dead) { + this.kill(); + } + + this.cursorState.currentLimit = 0; + this.cursorState.init = false; + this.cursorState.dead = false; + this.cursorState.killed = false; + this.cursorState.notified = false; + this.cursorState.documents = []; + this.cursorState.cursorId = null; + this.cursorState.cursorIndex = 0; + } + } + + // Internal methods + _read() { + if ((this.s && this.s.state === CursorState.CLOSED) || this.isDead()) { + return this.push(null); + } + + // Get the next item + this._next((err, result) => { + if (err) { + if (this.listeners('error') && this.listeners('error').length > 0) { + this.emit('error', err); + } + if (!this.isDead()) this.close(); + + // Emit end event + this.emit('end'); + return this.emit('finish'); + } + + // If we provided a transformation method + if ( + this.cursorState.streamOptions && + typeof this.cursorState.streamOptions.transform === 'function' && + result != null + ) { + return this.push(this.cursorState.streamOptions.transform(result)); + } + + // Return the result + this.push(result); + + if (result === null && this.isDead()) { + this.once('end', () => { + this.close(); + this.emit('finish'); + }); + } + }); + } + + _endSession(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + const session = this.cursorState.session; + + if (session && (options.force || session.owner === this)) { + this.cursorState.session = undefined; + + if (this.operation) { + this.operation.clearSession(); + } + + session.endSession(callback); + return true; + } + + if (callback) { + callback(); + } + + return false; + } + + _getMore(callback) { + if (this.logger.isDebug()) { + this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`); + } + + // Set the current batchSize + let batchSize = this.cursorState.batchSize; + if ( + this.cursorState.limit > 0 && + this.cursorState.currentLimit + batchSize > this.cursorState.limit + ) { + batchSize = this.cursorState.limit - this.cursorState.currentLimit; + } + + const cursorState = this.cursorState; + this.server.getMore(this.ns, cursorState, batchSize, this.options, (err, result, conn) => { + // NOTE: `getMore` modifies `cursorState`, would be very ideal not to do so in the future + if (err || (cursorState.cursorId && cursorState.cursorId.isZero())) { + this._endSession(); + } + + callback(err, result, conn); + }); + } + + _initializeCursor(callback) { + const cursor = this; + + // NOTE: this goes away once cursors use `executeOperation` + if (isUnifiedTopology(cursor.topology) && cursor.topology.shouldCheckForSessionSupport()) { + cursor.topology.selectServer(ReadPreference.primaryPreferred, err => { + if (err) { + callback(err); + return; + } + + this._initializeCursor(callback); + }); + + return; + } + + function done(err, result) { + const cursorState = cursor.cursorState; + if (err || (cursorState.cursorId && cursorState.cursorId.isZero())) { + cursor._endSession(); + } + + if ( + cursorState.documents.length === 0 && + cursorState.cursorId && + cursorState.cursorId.isZero() && + !cursor.cmd.tailable && + !cursor.cmd.awaitData + ) { + return setCursorNotified(cursor, callback); + } + + callback(err, result); + } + + const queryCallback = (err, r) => { + if (err) { + return done(err); + } + + const result = r.message; + + if (Array.isArray(result.documents) && result.documents.length === 1) { + const document = result.documents[0]; + + if (result.queryFailure) { + return done(new MongoError(document), null); + } + + // Check if we have a command cursor + if (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) { + // We have an error document, return the error + if (document.$err || document.errmsg) { + return done(new MongoError(document), null); + } + + // We have a cursor document + if (document.cursor != null && typeof document.cursor !== 'string') { + const id = document.cursor.id; + // If we have a namespace change set the new namespace for getmores + if (document.cursor.ns) { + cursor.ns = document.cursor.ns; + } + // Promote id to long if needed + cursor.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; + cursor.cursorState.lastCursorId = cursor.cursorState.cursorId; + cursor.cursorState.operationTime = document.operationTime; + + // If we have a firstBatch set it + if (Array.isArray(document.cursor.firstBatch)) { + cursor.cursorState.documents = document.cursor.firstBatch; //.reverse(); + } + + // Return after processing command cursor + return done(null, result); + } + } + } + + // Otherwise fall back to regular find path + const cursorId = result.cursorId || 0; + cursor.cursorState.cursorId = cursorId instanceof Long ? cursorId : Long.fromNumber(cursorId); + cursor.cursorState.documents = result.documents; + cursor.cursorState.lastCursorId = result.cursorId; + + // Transform the results with passed in transformation method if provided + if ( + cursor.cursorState.transforms && + typeof cursor.cursorState.transforms.query === 'function' + ) { + cursor.cursorState.documents = cursor.cursorState.transforms.query(result); + } + + done(null, result); + }; + + if (cursor.operation) { + if (cursor.logger.isDebug()) { + cursor.logger.debug( + `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( + cursor.query + )}]` + ); + } + + executeOperation(cursor.topology, cursor.operation, (err, result) => { + if (err) { + done(err); + return; + } + + cursor.server = cursor.operation.server; + cursor.cursorState.init = true; + + // NOTE: this is a special internal method for cloning a cursor, consider removing + if (cursor.cursorState.cursorId != null) { + return done(); + } + + queryCallback(err, result); + }); + + return; + } + + // Very explicitly choose what is passed to selectServer + const serverSelectOptions = {}; + if (cursor.cursorState.session) { + serverSelectOptions.session = cursor.cursorState.session; + } + + if (cursor.operation) { + serverSelectOptions.readPreference = cursor.operation.readPreference; + } else if (cursor.options.readPreference) { + serverSelectOptions.readPreference = cursor.options.readPreference; + } + + return cursor.topology.selectServer(serverSelectOptions, (err, server) => { + if (err) { + const disconnectHandler = cursor.disconnectHandler; + if (disconnectHandler != null) { + return disconnectHandler.addObjectAndMethod( + 'cursor', + cursor, + 'next', + [callback], + callback + ); + } + + return callback(err); + } + + cursor.server = server; + cursor.cursorState.init = true; + if (collationNotSupported(cursor.server, cursor.cmd)) { + return callback(new MongoError(`server ${cursor.server.name} does not support collation`)); + } + + // NOTE: this is a special internal method for cloning a cursor, consider removing + if (cursor.cursorState.cursorId != null) { + return done(); + } + + if (cursor.logger.isDebug()) { + cursor.logger.debug( + `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( + cursor.query + )}]` + ); + } + + if (cursor.cmd.find != null) { + server.query(cursor.ns, cursor.cmd, cursor.cursorState, cursor.options, queryCallback); + return; + } + + const commandOptions = Object.assign({ session: cursor.cursorState.session }, cursor.options); + server.command(cursor.ns, cursor.cmd, commandOptions, queryCallback); + }); + } +} + +if (SUPPORTS.ASYNC_ITERATOR) { + CoreCursor.prototype[Symbol.asyncIterator] = __webpack_require__(1749).asyncIterator; +} + +/** + * Validate if the pool is dead and return error + */ +function isConnectionDead(self, callback) { + if (self.pool && self.pool.isDestroyed()) { + self.cursorState.killed = true; + const err = new MongoNetworkError( + `connection to host ${self.pool.host}:${self.pool.port} was destroyed` + ); + + _setCursorNotifiedImpl(self, () => callback(err)); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +function isCursorDeadButNotkilled(self, callback) { + // Cursor is dead but not marked killed, return null + if (self.cursorState.dead && !self.cursorState.killed) { + self.cursorState.killed = true; + setCursorNotified(self, callback); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead and was killed by user + */ +function isCursorDeadAndKilled(self, callback) { + if (self.cursorState.dead && self.cursorState.killed) { + handleCallback(callback, new MongoError('cursor is dead')); + return true; + } + + return false; +} + +/** + * Validate if the cursor was killed by the user + */ +function isCursorKilled(self, callback) { + if (self.cursorState.killed) { + setCursorNotified(self, callback); + return true; + } + + return false; +} + +/** + * Mark cursor as being dead and notified + */ +function setCursorDeadAndNotified(self, callback) { + self.cursorState.dead = true; + setCursorNotified(self, callback); +} + +/** + * Mark cursor as being notified + */ +function setCursorNotified(self, callback) { + _setCursorNotifiedImpl(self, () => handleCallback(callback, null, null)); +} + +function _setCursorNotifiedImpl(self, callback) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + if (self.cursorState.session) { + self._endSession(callback); + return; + } + + return callback(); +} + +function nextFunction(self, callback) { + // We have notified about it + if (self.cursorState.notified) { + return callback(new Error('cursor is exhausted')); + } + + // Cursor is killed return null + if (isCursorKilled(self, callback)) return; + + // Cursor is dead but not marked killed, return null + if (isCursorDeadButNotkilled(self, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if (isCursorDeadAndKilled(self, callback)) return; + + // We have just started the cursor + if (!self.cursorState.init) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if (!self.topology.isConnected(self.options)) { + // Only need this for single server, because repl sets and mongos + // will always continue trying to reconnect + if (self.topology._type === 'server' && !self.topology.s.options.reconnect) { + // Reconnect is disabled, so we'll never reconnect + return callback(new MongoError('no connection available')); + } + + if (self.disconnectHandler != null) { + if (self.topology.isDestroyed()) { + // Topology was destroyed, so don't try to wait for it to reconnect + return callback(new MongoError('Topology was destroyed')); + } + + self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); + return; + } + } + + self._initializeCursor((err, result) => { + if (err || result === null) { + callback(err, result); + return; + } + + nextFunction(self, callback); + }); + + return; + } + + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(() => + // Set cursor in dead and notified state + setCursorDeadAndNotified(self, callback) + ); + } else if ( + self.cursorState.cursorIndex === self.cursorState.documents.length && + !Long.ZERO.equals(self.cursorState.cursorId) + ) { + // Ensure an empty cursor state + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + // Check if topology is destroyed + if (self.topology.isDestroyed()) + return callback( + new MongoNetworkError('connection destroyed, not possible to instantiate cursor') + ); + + // Check if connection is dead and return if not possible to + // execute a getMore on this connection + if (isConnectionDead(self, callback)) return; + + // Execute the next get more + self._getMore(function(err, doc, connection) { + if (err) { + return handleCallback(callback, err); + } + + // Save the returned connection to ensure all getMore's fire over the same connection + self.connection = connection; + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if ( + self.cursorState.documents.length === 0 && + self.cmd.tailable && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + // No more documents in the tailed cursor + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: self.cmd.tailable, + awaitData: self.cmd.awaitData + }) + ); + } else if ( + self.cursorState.documents.length === 0 && + self.cmd.tailable && + !Long.ZERO.equals(self.cursorState.cursorId) + ) { + return nextFunction(self, callback); + } + + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if ( + self.cursorState.documents.length === self.cursorState.cursorIndex && + self.cmd.tailable && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: self.cmd.tailable, + awaitData: self.cmd.awaitData + }) + ); + } else if ( + self.cursorState.documents.length === self.cursorState.cursorIndex && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + setCursorDeadAndNotified(self, callback); + } else { + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(() => + // Set cursor in dead and notified state + setCursorDeadAndNotified(self, callback) + ); + + return; + } + + // Increment the current cursor limit + self.cursorState.currentLimit += 1; + + // Get the document + let doc = self.cursorState.documents[self.cursorState.cursorIndex++]; + + // Doc overflow + if (!doc || doc.$err) { + // Ensure we kill the cursor on the server + self.kill(() => + // Set cursor in dead and notified state + setCursorDeadAndNotified(self, function() { + handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); + }) + ); + + return; + } + + // Transform the doc with passed in transformation method if provided + if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') { + doc = self.cursorState.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); + } +} + +module.exports = { + CursorState, + CoreCursor +}; + + +/***/ }), + +/***/ 3111: +/***/ ((module) => { + +"use strict"; + + +const kErrorLabels = Symbol('errorLabels'); + +/** + * Creates a new MongoError + * + * @augments Error + * @param {Error|string|object} message The error message + * @property {string} message The error message + * @property {string} stack The error call stack + */ +class MongoError extends Error { + constructor(message) { + if (message instanceof Error) { + super(message.message); + this.stack = message.stack; + } else { + if (typeof message === 'string') { + super(message); + } else { + super(message.message || message.errmsg || message.$err || 'n/a'); + if (message.errorLabels) { + this[kErrorLabels] = new Set(message.errorLabels); + } + + for (var name in message) { + if (name === 'errorLabels' || name === 'errmsg') { + continue; + } + + this[name] = message[name]; + } + } + + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'MongoError'; + } + + /** + * Legacy name for server error responses + */ + get errmsg() { + return this.message; + } + + /** + * Creates a new MongoError object + * + * @param {Error|string|object} options The options used to create the error. + * @return {MongoError} A MongoError instance + * @deprecated Use `new MongoError()` instead. + */ + static create(options) { + return new MongoError(options); + } + + /** + * Checks the error to see if it has an error label + * @param {string} label The error label to check for + * @returns {boolean} returns true if the error has the provided error label + */ + hasErrorLabel(label) { + if (this[kErrorLabels] == null) { + return false; + } + + return this[kErrorLabels].has(label); + } + + addErrorLabel(label) { + if (this[kErrorLabels] == null) { + this[kErrorLabels] = new Set(); + } + + this[kErrorLabels].add(label); + } + + get errorLabels() { + return this[kErrorLabels] ? Array.from(this[kErrorLabels]) : []; + } +} + +const kBeforeHandshake = Symbol('beforeHandshake'); +function isNetworkErrorBeforeHandshake(err) { + return err[kBeforeHandshake] === true; +} + +/** + * An error indicating an issue with the network, including TCP + * errors and timeouts. + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + * @property {string} stack The error call stack + * @extends MongoError + */ +class MongoNetworkError extends MongoError { + constructor(message, options) { + super(message); + this.name = 'MongoNetworkError'; + + if (options && options.beforeHandshake === true) { + this[kBeforeHandshake] = true; + } + } +} + +/** + * An error indicating a network timeout occurred + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + * @property {object} [options.beforeHandshake] Indicates the timeout happened before a connection handshake completed + * @extends MongoError + */ +class MongoNetworkTimeoutError extends MongoNetworkError { + constructor(message, options) { + super(message, options); + this.name = 'MongoNetworkTimeoutError'; + } +} + +/** + * An error used when attempting to parse a value (like a connection string) + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + * @extends MongoError + */ +class MongoParseError extends MongoError { + constructor(message) { + super(message); + this.name = 'MongoParseError'; + } +} + +/** + * An error signifying a client-side timeout event + * + * @param {Error|string|object} message The error message + * @param {string|object} [reason] The reason the timeout occured + * @property {string} message The error message + * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers + * @extends MongoError + */ +class MongoTimeoutError extends MongoError { + constructor(message, reason) { + if (reason && reason.error) { + super(reason.error.message || reason.error); + } else { + super(message); + } + + this.name = 'MongoTimeoutError'; + if (reason) { + this.reason = reason; + } + } +} + +/** + * An error signifying a client-side server selection error + * + * @param {Error|string|object} message The error message + * @param {string|object} [reason] The reason the timeout occured + * @property {string} message The error message + * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers + * @extends MongoError + */ +class MongoServerSelectionError extends MongoTimeoutError { + constructor(message, reason) { + super(message, reason); + this.name = 'MongoServerSelectionError'; + } +} + +function makeWriteConcernResultObject(input) { + const output = Object.assign({}, input); + + if (output.ok === 0) { + output.ok = 1; + delete output.errmsg; + delete output.code; + delete output.codeName; + } + + return output; +} + +/** + * An error thrown when the server reports a writeConcernError + * + * @param {Error|string|object} message The error message + * @param {object} result The result document (provided if ok: 1) + * @property {string} message The error message + * @property {object} [result] The result document (provided if ok: 1) + * @extends MongoError + */ +class MongoWriteConcernError extends MongoError { + constructor(message, result) { + super(message); + this.name = 'MongoWriteConcernError'; + + if (result && Array.isArray(result.errorLabels)) { + this[kErrorLabels] = new Set(result.errorLabels); + } + + if (result != null) { + this.result = makeWriteConcernResultObject(result); + } + } +} + +// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms +const RETRYABLE_ERROR_CODES = new Set([ + 6, // HostUnreachable + 7, // HostNotFound + 89, // NetworkTimeout + 91, // ShutdownInProgress + 189, // PrimarySteppedDown + 9001, // SocketException + 10107, // NotMaster + 11600, // InterruptedAtShutdown + 11602, // InterruptedDueToReplStateChange + 13435, // NotMasterNoSlaveOk + 13436 // NotMasterOrSecondary +]); + +const RETRYABLE_WRITE_ERROR_CODES = new Set([ + 11600, // InterruptedAtShutdown + 11602, // InterruptedDueToReplStateChange + 10107, // NotMaster + 13435, // NotMasterNoSlaveOk + 13436, // NotMasterOrSecondary + 189, // PrimarySteppedDown + 91, // ShutdownInProgress + 7, // HostNotFound + 6, // HostUnreachable + 89, // NetworkTimeout + 9001, // SocketException + 262 // ExceededTimeLimit +]); + +function isRetryableWriteError(error) { + if (error instanceof MongoWriteConcernError) { + return ( + RETRYABLE_WRITE_ERROR_CODES.has(error.code) || + RETRYABLE_WRITE_ERROR_CODES.has(error.result.code) + ); + } + + return RETRYABLE_WRITE_ERROR_CODES.has(error.code); +} + +/** + * Determines whether an error is something the driver should attempt to retry + * + * @ignore + * @param {MongoError|Error} error + */ +function isRetryableError(error) { + return ( + RETRYABLE_ERROR_CODES.has(error.code) || + error instanceof MongoNetworkError || + error.message.match(/not master/) || + error.message.match(/node is recovering/) + ); +} + +const SDAM_RECOVERING_CODES = new Set([ + 91, // ShutdownInProgress + 189, // PrimarySteppedDown + 11600, // InterruptedAtShutdown + 11602, // InterruptedDueToReplStateChange + 13436 // NotMasterOrSecondary +]); + +const SDAM_NOTMASTER_CODES = new Set([ + 10107, // NotMaster + 13435 // NotMasterNoSlaveOk +]); + +const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ + 11600, // InterruptedAtShutdown + 91 // ShutdownInProgress +]); + +function isRecoveringError(err) { + if (err.code && SDAM_RECOVERING_CODES.has(err.code)) { + return true; + } + + return err.message.match(/not master or secondary/) || err.message.match(/node is recovering/); +} + +function isNotMasterError(err) { + if (err.code && SDAM_NOTMASTER_CODES.has(err.code)) { + return true; + } + + if (isRecoveringError(err)) { + return false; + } + + return err.message.match(/not master/); +} + +function isNodeShuttingDownError(err) { + return err.code && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code); +} + +/** + * Determines whether SDAM can recover from a given error. If it cannot + * then the pool will be cleared, and server state will completely reset + * locally. + * + * @ignore + * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering + * @param {MongoError|Error} error + */ +function isSDAMUnrecoverableError(error) { + // NOTE: null check is here for a strictly pre-CMAP world, a timeout or + // close event are considered unrecoverable + if (error instanceof MongoParseError || error == null) { + return true; + } + + if (isRecoveringError(error) || isNotMasterError(error)) { + return true; + } + + return false; +} + +module.exports = { + MongoError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoParseError, + MongoTimeoutError, + MongoServerSelectionError, + MongoWriteConcernError, + isRetryableError, + isSDAMUnrecoverableError, + isNodeShuttingDownError, + isRetryableWriteError, + isNetworkErrorBeforeHandshake +}; + + +/***/ }), + +/***/ 3994: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +let BSON = __webpack_require__(4044); +const require_optional = __webpack_require__(6985); +const EJSON = __webpack_require__(1178).retrieveEJSON(); + +try { + // Attempt to grab the native BSON parser + const BSONNative = require_optional('bson-ext'); + // If we got the native parser, use it instead of the + // Javascript one + if (BSONNative) { + BSON = BSONNative; + } +} catch (err) {} // eslint-disable-line + +module.exports = { + // Errors + MongoError: __webpack_require__(3111).MongoError, + MongoNetworkError: __webpack_require__(3111).MongoNetworkError, + MongoParseError: __webpack_require__(3111).MongoParseError, + MongoTimeoutError: __webpack_require__(3111).MongoTimeoutError, + MongoServerSelectionError: __webpack_require__(3111).MongoServerSelectionError, + MongoWriteConcernError: __webpack_require__(3111).MongoWriteConcernError, + // Core + Connection: __webpack_require__(6096), + Server: __webpack_require__(6495), + ReplSet: __webpack_require__(1134), + Mongos: __webpack_require__(8175), + Logger: __webpack_require__(104), + Cursor: __webpack_require__(4847).CoreCursor, + ReadPreference: __webpack_require__(4485), + Sessions: __webpack_require__(5474), + BSON: BSON, + EJSON: EJSON, + Topology: __webpack_require__(4149).Topology, + // Raw operations + Query: __webpack_require__(9814).Query, + // Auth mechanisms + MongoCredentials: __webpack_require__(2222).MongoCredentials, + defaultAuthProviders: __webpack_require__(2192).defaultAuthProviders, + MongoCR: __webpack_require__(4228), + X509: __webpack_require__(7324), + Plain: __webpack_require__(8728), + GSSAPI: __webpack_require__(2640), + ScramSHA1: __webpack_require__(864).ScramSHA1, + ScramSHA256: __webpack_require__(864).ScramSHA256, + // Utilities + parseConnectionString: __webpack_require__(8767) +}; + + +/***/ }), + +/***/ 2291: +/***/ ((module) => { + +"use strict"; + + +// shared state names +const STATE_CLOSING = 'closing'; +const STATE_CLOSED = 'closed'; +const STATE_CONNECTING = 'connecting'; +const STATE_CONNECTED = 'connected'; + +// An enumeration of topology types we know about +const TopologyType = { + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown' +}; + +// An enumeration of server types we know about +const ServerType = { + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown' +}; + +// helper to get a server's type that works for both legacy and unified topologies +function serverType(server) { + let description = server.s.description || server.s.serverDescription; + if (description.topologyType === TopologyType.Single) return description.servers[0].type; + return description.type; +} + +const TOPOLOGY_DEFAULTS = { + useUnifiedTopology: true, + localThresholdMS: 15, + serverSelectionTimeoutMS: 30000, + heartbeatFrequencyMS: 10000, + minHeartbeatFrequencyMS: 500 +}; + +function drainTimerQueue(queue) { + queue.forEach(clearTimeout); + queue.clear(); +} + +function clearAndRemoveTimerFrom(timer, timers) { + clearTimeout(timer); + return timers.delete(timer); +} + +module.exports = { + STATE_CLOSING, + STATE_CLOSED, + STATE_CONNECTING, + STATE_CONNECTED, + TOPOLOGY_DEFAULTS, + TopologyType, + ServerType, + serverType, + drainTimerQueue, + clearAndRemoveTimerFrom +}; + + +/***/ }), + +/***/ 2785: +/***/ ((module) => { + +"use strict"; + + +/** + * Published when server description changes, but does NOT include changes to the RTT. + * + * @property {Object} topologyId A unique identifier for the topology + * @property {ServerAddress} address The address (host/port pair) of the server + * @property {ServerDescription} previousDescription The previous server description + * @property {ServerDescription} newDescription The new server description + */ +class ServerDescriptionChangedEvent { + constructor(topologyId, address, previousDescription, newDescription) { + Object.assign(this, { topologyId, address, previousDescription, newDescription }); + } +} + +/** + * Published when server is initialized. + * + * @property {Object} topologyId A unique identifier for the topology + * @property {ServerAddress} address The address (host/port pair) of the server + */ +class ServerOpeningEvent { + constructor(topologyId, address) { + Object.assign(this, { topologyId, address }); + } +} + +/** + * Published when server is closed. + * + * @property {ServerAddress} address The address (host/port pair) of the server + * @property {Object} topologyId A unique identifier for the topology + */ +class ServerClosedEvent { + constructor(topologyId, address) { + Object.assign(this, { topologyId, address }); + } +} + +/** + * Published when topology description changes. + * + * @property {Object} topologyId + * @property {TopologyDescription} previousDescription The old topology description + * @property {TopologyDescription} newDescription The new topology description + */ +class TopologyDescriptionChangedEvent { + constructor(topologyId, previousDescription, newDescription) { + Object.assign(this, { topologyId, previousDescription, newDescription }); + } +} + +/** + * Published when topology is initialized. + * + * @param {Object} topologyId A unique identifier for the topology + */ +class TopologyOpeningEvent { + constructor(topologyId) { + Object.assign(this, { topologyId }); + } +} + +/** + * Published when topology is closed. + * + * @param {Object} topologyId A unique identifier for the topology + */ +class TopologyClosedEvent { + constructor(topologyId) { + Object.assign(this, { topologyId }); + } +} + +/** + * Fired when the server monitor’s ismaster command is started - immediately before + * the ismaster command is serialized into raw BSON and written to the socket. + * + * @property {Object} connectionId The connection id for the command + */ +class ServerHeartbeatStartedEvent { + constructor(connectionId) { + Object.assign(this, { connectionId }); + } +} + +/** + * Fired when the server monitor’s ismaster succeeds. + * + * @param {Number} duration The execution time of the event in ms + * @param {Object} reply The command reply + * @param {Object} connectionId The connection id for the command + */ +class ServerHeartbeatSucceededEvent { + constructor(duration, reply, connectionId) { + Object.assign(this, { connectionId, duration, reply }); + } +} + +/** + * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. + * + * @param {Number} duration The execution time of the event in ms + * @param {MongoError|Object} failure The command failure + * @param {Object} connectionId The connection id for the command + */ +class ServerHeartbeatFailedEvent { + constructor(duration, failure, connectionId) { + Object.assign(this, { connectionId, duration, failure }); + } +} + +module.exports = { + ServerDescriptionChangedEvent, + ServerOpeningEvent, + ServerClosedEvent, + TopologyDescriptionChangedEvent, + TopologyOpeningEvent, + TopologyClosedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent, + ServerHeartbeatFailedEvent +}; + + +/***/ }), + +/***/ 1203: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const ServerType = __webpack_require__(2291).ServerType; +const EventEmitter = __webpack_require__(8614); +const connect = __webpack_require__(6573); +const Connection = __webpack_require__(9820).Connection; +const common = __webpack_require__(2291); +const makeStateMachine = __webpack_require__(1178).makeStateMachine; +const MongoNetworkError = __webpack_require__(3111).MongoNetworkError; +const BSON = __webpack_require__(7746).retrieveBSON(); +const makeInterruptableAsyncInterval = __webpack_require__(1371).makeInterruptableAsyncInterval; +const calculateDurationInMs = __webpack_require__(1371).calculateDurationInMs; +const now = __webpack_require__(1371).now; + +const sdamEvents = __webpack_require__(2785); +const ServerHeartbeatStartedEvent = sdamEvents.ServerHeartbeatStartedEvent; +const ServerHeartbeatSucceededEvent = sdamEvents.ServerHeartbeatSucceededEvent; +const ServerHeartbeatFailedEvent = sdamEvents.ServerHeartbeatFailedEvent; + +const kServer = Symbol('server'); +const kMonitorId = Symbol('monitorId'); +const kConnection = Symbol('connection'); +const kCancellationToken = Symbol('cancellationToken'); +const kRTTPinger = Symbol('rttPinger'); +const kRoundTripTime = Symbol('roundTripTime'); + +const STATE_CLOSED = common.STATE_CLOSED; +const STATE_CLOSING = common.STATE_CLOSING; +const STATE_IDLE = 'idle'; +const STATE_MONITORING = 'monitoring'; +const stateTransition = makeStateMachine({ + [STATE_CLOSING]: [STATE_CLOSING, STATE_IDLE, STATE_CLOSED], + [STATE_CLOSED]: [STATE_CLOSED, STATE_MONITORING], + [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, STATE_CLOSING], + [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, STATE_CLOSING] +}); + +const INVALID_REQUEST_CHECK_STATES = new Set([STATE_CLOSING, STATE_CLOSED, STATE_MONITORING]); + +function isInCloseState(monitor) { + return monitor.s.state === STATE_CLOSED || monitor.s.state === STATE_CLOSING; +} + +class Monitor extends EventEmitter { + constructor(server, options) { + super(options); + + this[kServer] = server; + this[kConnection] = undefined; + this[kCancellationToken] = new EventEmitter(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kMonitorId] = null; + this.s = { + state: STATE_CLOSED + }; + + this.address = server.description.address; + this.options = Object.freeze({ + connectTimeoutMS: + typeof options.connectionTimeout === 'number' + ? options.connectionTimeout + : typeof options.connectTimeoutMS === 'number' + ? options.connectTimeoutMS + : 10000, + heartbeatFrequencyMS: + typeof options.heartbeatFrequencyMS === 'number' ? options.heartbeatFrequencyMS : 10000, + minHeartbeatFrequencyMS: + typeof options.minHeartbeatFrequencyMS === 'number' ? options.minHeartbeatFrequencyMS : 500 + }); + + // TODO [$5f5fbe42fcabad09c1c241a2]: refactor this to pull it directly from the pool, requires new ConnectionPool integration + const connectOptions = Object.assign( + { + id: '', + host: server.description.host, + port: server.description.port, + bson: server.s.bson, + connectionType: Connection + }, + server.s.options, + this.options, + + // force BSON serialization options + { + raw: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: true + } + ); + + // ensure no authentication is used for monitoring + delete connectOptions.credentials; + this.connectOptions = Object.freeze(connectOptions); + } + + connect() { + if (this.s.state !== STATE_CLOSED) { + return; + } + + // start + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = makeInterruptableAsyncInterval(monitorServer(this), { + interval: heartbeatFrequencyMS, + minInterval: minHeartbeatFrequencyMS, + immediate: true + }); + } + + requestCheck() { + if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { + return; + } + + this[kMonitorId].wake(); + } + + reset() { + if (isInCloseState(this)) { + return; + } + + stateTransition(this, STATE_CLOSING); + resetMonitorState(this); + + // restart monitor + stateTransition(this, STATE_IDLE); + + // restart monitoring + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = makeInterruptableAsyncInterval(monitorServer(this), { + interval: heartbeatFrequencyMS, + minInterval: minHeartbeatFrequencyMS + }); + } + + close() { + if (isInCloseState(this)) { + return; + } + + stateTransition(this, STATE_CLOSING); + resetMonitorState(this); + + // close monitor + this.emit('close'); + stateTransition(this, STATE_CLOSED); + } +} + +function resetMonitorState(monitor) { + stateTransition(monitor, STATE_CLOSING); + if (monitor[kMonitorId]) { + monitor[kMonitorId].stop(); + monitor[kMonitorId] = null; + } + + if (monitor[kRTTPinger]) { + monitor[kRTTPinger].close(); + monitor[kRTTPinger] = undefined; + } + + monitor[kCancellationToken].emit('cancel'); + if (monitor[kMonitorId]) { + clearTimeout(monitor[kMonitorId]); + monitor[kMonitorId] = undefined; + } + + if (monitor[kConnection]) { + monitor[kConnection].destroy({ force: true }); + } +} + +function checkServer(monitor, callback) { + let start = now(); + monitor.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(monitor.address)); + + function failureHandler(err) { + if (monitor[kConnection]) { + monitor[kConnection].destroy({ force: true }); + monitor[kConnection] = undefined; + } + + monitor.emit( + 'serverHeartbeatFailed', + new ServerHeartbeatFailedEvent(calculateDurationInMs(start), err, monitor.address) + ); + + monitor.emit('resetServer', err); + monitor.emit('resetConnectionPool'); + callback(err); + } + + if (monitor[kConnection] != null && !monitor[kConnection].closed) { + const connectTimeoutMS = monitor.options.connectTimeoutMS; + const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS; + const topologyVersion = monitor[kServer].description.topologyVersion; + const isAwaitable = topologyVersion != null; + + const cmd = isAwaitable + ? { ismaster: true, maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) } + : { ismaster: true }; + + const options = isAwaitable + ? { socketTimeout: connectTimeoutMS + maxAwaitTimeMS, exhaustAllowed: true } + : { socketTimeout: connectTimeoutMS }; + + if (isAwaitable && monitor[kRTTPinger] == null) { + monitor[kRTTPinger] = new RTTPinger(monitor[kCancellationToken], monitor.connectOptions); + } + + monitor[kConnection].command('admin.$cmd', cmd, options, (err, result) => { + if (err) { + failureHandler(err); + return; + } + + const isMaster = result.result; + const duration = isAwaitable + ? monitor[kRTTPinger].roundTripTime + : calculateDurationInMs(start); + + monitor.emit( + 'serverHeartbeatSucceeded', + new ServerHeartbeatSucceededEvent(duration, isMaster, monitor.address) + ); + + // if we are using the streaming protocol then we immediately issue another `started` + // event, otherwise the "check" is complete and return to the main monitor loop + if (isAwaitable && isMaster.topologyVersion) { + monitor.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(monitor.address)); + start = now(); + } else { + if (monitor[kRTTPinger]) { + monitor[kRTTPinger].close(); + monitor[kRTTPinger] = undefined; + } + + callback(undefined, isMaster); + } + }); + + return; + } + + // connecting does an implicit `ismaster` + connect(monitor.connectOptions, monitor[kCancellationToken], (err, conn) => { + if (conn && isInCloseState(monitor)) { + conn.destroy({ force: true }); + return; + } + + if (err) { + monitor[kConnection] = undefined; + + // we already reset the connection pool on network errors in all cases + if (!(err instanceof MongoNetworkError)) { + monitor.emit('resetConnectionPool'); + } + + failureHandler(err); + return; + } + + monitor[kConnection] = conn; + monitor.emit( + 'serverHeartbeatSucceeded', + new ServerHeartbeatSucceededEvent( + calculateDurationInMs(start), + conn.ismaster, + monitor.address + ) + ); + + callback(undefined, conn.ismaster); + }); +} + +function monitorServer(monitor) { + return callback => { + stateTransition(monitor, STATE_MONITORING); + function done() { + if (!isInCloseState(monitor)) { + stateTransition(monitor, STATE_IDLE); + } + + callback(); + } + + // TODO [$5f5fbe42fcabad09c1c241a3]: the next line is a legacy event, remove in v4 + process.nextTick(() => monitor.emit('monitoring', monitor[kServer])); + + checkServer(monitor, (err, isMaster) => { + if (err) { + // otherwise an error occured on initial discovery, also bail + if (monitor[kServer].description.type === ServerType.Unknown) { + monitor.emit('resetServer', err); + return done(); + } + } + + // if the check indicates streaming is supported, immediately reschedule monitoring + if (isMaster && isMaster.topologyVersion) { + setTimeout(() => { + if (!isInCloseState(monitor)) { + monitor[kMonitorId].wake(); + } + }); + } + + done(); + }); + }; +} + +function makeTopologyVersion(tv) { + return { + processId: tv.processId, + counter: BSON.Long.fromNumber(tv.counter) + }; +} + +class RTTPinger { + constructor(cancellationToken, options) { + this[kConnection] = null; + this[kCancellationToken] = cancellationToken; + this[kRoundTripTime] = 0; + this.closed = false; + + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + this[kMonitorId] = setTimeout(() => measureRoundTripTime(this, options), heartbeatFrequencyMS); + } + + get roundTripTime() { + return this[kRoundTripTime]; + } + + close() { + this.closed = true; + + clearTimeout(this[kMonitorId]); + this[kMonitorId] = undefined; + + if (this[kConnection]) { + this[kConnection].destroy({ force: true }); + } + } +} + +function measureRoundTripTime(rttPinger, options) { + const start = now(); + const cancellationToken = rttPinger[kCancellationToken]; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + if (rttPinger.closed) { + return; + } + + function measureAndReschedule(conn) { + if (rttPinger.closed) { + conn.destroy({ force: true }); + return; + } + + if (rttPinger[kConnection] == null) { + rttPinger[kConnection] = conn; + } + + rttPinger[kRoundTripTime] = calculateDurationInMs(start); + rttPinger[kMonitorId] = setTimeout( + () => measureRoundTripTime(rttPinger, options), + heartbeatFrequencyMS + ); + } + + if (rttPinger[kConnection] == null) { + connect(options, cancellationToken, (err, conn) => { + if (err) { + rttPinger[kConnection] = undefined; + rttPinger[kRoundTripTime] = 0; + return; + } + + measureAndReschedule(conn); + }); + + return; + } + + rttPinger[kConnection].command('admin.$cmd', { ismaster: 1 }, err => { + if (err) { + rttPinger[kConnection] = undefined; + rttPinger[kRoundTripTime] = 0; + return; + } + + measureAndReschedule(); + }); +} + +module.exports = { + Monitor +}; + + +/***/ }), + +/***/ 7062: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const EventEmitter = __webpack_require__(8614); +const ConnectionPool = __webpack_require__(2529).ConnectionPool; +const CMAP_EVENT_NAMES = __webpack_require__(897).CMAP_EVENT_NAMES; +const MongoError = __webpack_require__(3111).MongoError; +const relayEvents = __webpack_require__(1178).relayEvents; +const BSON = __webpack_require__(7746).retrieveBSON(); +const Logger = __webpack_require__(104); +const ServerDescription = __webpack_require__(750).ServerDescription; +const compareTopologyVersion = __webpack_require__(750).compareTopologyVersion; +const ReadPreference = __webpack_require__(4485); +const Monitor = __webpack_require__(1203).Monitor; +const MongoNetworkError = __webpack_require__(3111).MongoNetworkError; +const MongoNetworkTimeoutError = __webpack_require__(3111).MongoNetworkTimeoutError; +const collationNotSupported = __webpack_require__(1178).collationNotSupported; +const debugOptions = __webpack_require__(7746).debugOptions; +const isSDAMUnrecoverableError = __webpack_require__(3111).isSDAMUnrecoverableError; +const isRetryableWriteError = __webpack_require__(3111).isRetryableWriteError; +const isNodeShuttingDownError = __webpack_require__(3111).isNodeShuttingDownError; +const isNetworkErrorBeforeHandshake = __webpack_require__(3111).isNetworkErrorBeforeHandshake; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const makeStateMachine = __webpack_require__(1178).makeStateMachine; +const common = __webpack_require__(2291); +const ServerType = common.ServerType; +const isTransactionCommand = __webpack_require__(1707).isTransactionCommand; + +// Used for filtering out fields for logging +const DEBUG_FIELDS = [ + 'reconnect', + 'reconnectTries', + 'reconnectInterval', + 'emitError', + 'cursorFactory', + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'checkServerIdentity', + 'socketTimeout', + 'ssl', + 'ca', + 'crl', + 'cert', + 'key', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'servername' +]; + +const STATE_CLOSING = common.STATE_CLOSING; +const STATE_CLOSED = common.STATE_CLOSED; +const STATE_CONNECTING = common.STATE_CONNECTING; +const STATE_CONNECTED = common.STATE_CONNECTED; +const stateTransition = makeStateMachine({ + [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], + [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], + [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], + [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] +}); + +const kMonitor = Symbol('monitor'); + +/** + * + * @fires Server#serverHeartbeatStarted + * @fires Server#serverHeartbeatSucceeded + * @fires Server#serverHeartbeatFailed + */ +class Server extends EventEmitter { + /** + * Create a server + * + * @param {ServerDescription} description + * @param {Object} options + */ + constructor(description, options, topology) { + super(); + + this.s = { + // the server description + description, + // a saved copy of the incoming options + options, + // the server logger + logger: Logger('Server', options), + // the bson parser + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // the server state + state: STATE_CLOSED, + credentials: options.credentials, + topology + }; + + // create the connection pool + // NOTE: this used to happen in `connect`, we supported overriding pool options there + const poolOptions = Object.assign( + { host: this.description.host, port: this.description.port, bson: this.s.bson }, + options + ); + + this.s.pool = new ConnectionPool(poolOptions); + relayEvents( + this.s.pool, + this, + ['commandStarted', 'commandSucceeded', 'commandFailed'].concat(CMAP_EVENT_NAMES) + ); + + this.s.pool.on('clusterTimeReceived', clusterTime => { + this.clusterTime = clusterTime; + }); + + // create the monitor + this[kMonitor] = new Monitor(this, this.s.options); + relayEvents(this[kMonitor], this, [ + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + + // legacy events + 'monitoring' + ]); + + this[kMonitor].on('resetConnectionPool', () => { + this.s.pool.clear(); + }); + + this[kMonitor].on('resetServer', error => markServerUnknown(this, error)); + this[kMonitor].on('serverHeartbeatSucceeded', event => { + this.emit( + 'descriptionReceived', + new ServerDescription(this.description.address, event.reply, { + roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration) + }) + ); + + if (this.s.state === STATE_CONNECTING) { + stateTransition(this, STATE_CONNECTED); + this.emit('connect', this); + } + }); + } + + get description() { + return this.s.description; + } + + get name() { + return this.s.description.address; + } + + get autoEncrypter() { + if (this.s.options && this.s.options.autoEncrypter) { + return this.s.options.autoEncrypter; + } + return null; + } + + /** + * Initiate server connect + */ + connect() { + if (this.s.state !== STATE_CLOSED) { + return; + } + + stateTransition(this, STATE_CONNECTING); + this[kMonitor].connect(); + } + + /** + * Destroy the server connection + * + * @param {object} [options] Optional settings + * @param {Boolean} [options.force=false] Force destroy the pool + */ + destroy(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { force: false }, options); + + if (this.s.state === STATE_CLOSED) { + if (typeof callback === 'function') { + callback(); + } + + return; + } + + stateTransition(this, STATE_CLOSING); + + this[kMonitor].close(); + this.s.pool.close(options, err => { + stateTransition(this, STATE_CLOSED); + this.emit('closed'); + if (typeof callback === 'function') { + callback(err); + } + }); + } + + /** + * Immediately schedule monitoring of this server. If there already an attempt being made + * this will be a no-op. + */ + requestCheck() { + this[kMonitor].requestCheck(); + } + + /** + * Execute a command + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {object} [options] Optional settings + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {ClientSession} [options.session] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + command(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { + callback(new MongoError('server is closed')); + return; + } + + const error = basicReadValidations(this, options); + if (error) { + return callback(error); + } + + // Clone the options + options = Object.assign({}, options, { wireProtocolCommand: false }); + + // Debug log + if (this.s.logger.isDebug()) { + this.s.logger.debug( + `executing command [${JSON.stringify({ + ns, + cmd, + options: debugOptions(DEBUG_FIELDS, options) + })}] against ${this.name}` + ); + } + + // error if collation not supported + if (collationNotSupported(this, cmd)) { + callback(new MongoError(`server ${this.name} does not support collation`)); + return; + } + + this.s.pool.withConnection((err, conn, cb) => { + if (err) { + markServerUnknown(this, err); + return cb(err); + } + + conn.command(ns, cmd, options, makeOperationHandler(this, conn, cmd, options, cb)); + }, callback); + } + + /** + * Execute a query against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command document for the query + * @param {object} options Optional settings + * @param {function} callback + */ + query(ns, cmd, cursorState, options, callback) { + if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { + callback(new MongoError('server is closed')); + return; + } + + this.s.pool.withConnection((err, conn, cb) => { + if (err) { + markServerUnknown(this, err); + return cb(err); + } + + conn.query(ns, cmd, cursorState, options, makeOperationHandler(this, conn, cmd, options, cb)); + }, callback); + } + + /** + * Execute a `getMore` against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cursorState State data associated with the cursor calling this method + * @param {object} options Optional settings + * @param {function} callback + */ + getMore(ns, cursorState, batchSize, options, callback) { + if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { + callback(new MongoError('server is closed')); + return; + } + + this.s.pool.withConnection((err, conn, cb) => { + if (err) { + markServerUnknown(this, err); + return cb(err); + } + + conn.getMore( + ns, + cursorState, + batchSize, + options, + makeOperationHandler(this, conn, null, options, cb) + ); + }, callback); + } + + /** + * Execute a `killCursors` command against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cursorState State data associated with the cursor calling this method + * @param {function} callback + */ + killCursors(ns, cursorState, callback) { + if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { + if (typeof callback === 'function') { + callback(new MongoError('server is closed')); + } + + return; + } + + this.s.pool.withConnection((err, conn, cb) => { + if (err) { + markServerUnknown(this, err); + return cb(err); + } + + conn.killCursors(ns, cursorState, makeOperationHandler(this, conn, null, undefined, cb)); + }, callback); + } + + /** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + insert(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback); + } + + /** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + update(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback); + } + + /** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + remove(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback); + } +} + +Object.defineProperty(Server.prototype, 'clusterTime', { + get: function() { + return this.s.topology.clusterTime; + }, + set: function(clusterTime) { + this.s.topology.clusterTime = clusterTime; + } +}); + +function supportsRetryableWrites(server) { + return ( + server.description.maxWireVersion >= 6 && + server.description.logicalSessionTimeoutMinutes && + server.description.type !== ServerType.Standalone + ); +} + +function calculateRoundTripTime(oldRtt, duration) { + if (oldRtt === -1) { + return duration; + } + + const alpha = 0.2; + return alpha * duration + (1 - alpha) * oldRtt; +} + +function basicReadValidations(server, options) { + if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { + return new MongoError('readPreference must be an instance of ReadPreference'); + } +} + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO [$5f5fbe42fcabad09c1c241a4]: once we drop Node 4, use destructuring either here or in arguments. + const server = args.server; + const op = args.op; + const ns = args.ns; + const ops = Array.isArray(args.ops) ? args.ops : [args.ops]; + + if (server.s.state === STATE_CLOSING || server.s.state === STATE_CLOSED) { + callback(new MongoError('server is closed')); + return; + } + + if (collationNotSupported(server, options)) { + callback(new MongoError(`server ${server.name} does not support collation`)); + return; + } + const unacknowledgedWrite = options.writeConcern && options.writeConcern.w === 0; + if (unacknowledgedWrite || maxWireVersion(server) < 5) { + if ((op === 'update' || op === 'remove') && ops.find(o => o.hint)) { + callback(new MongoError(`servers < 3.4 do not support hint on ${op}`)); + return; + } + } + + server.s.pool.withConnection((err, conn, cb) => { + if (err) { + markServerUnknown(server, err); + return cb(err); + } + + conn[op](ns, ops, options, makeOperationHandler(server, conn, ops, options, cb)); + }, callback); +} + +function markServerUnknown(server, error) { + if (error instanceof MongoNetworkError && !(error instanceof MongoNetworkTimeoutError)) { + server[kMonitor].reset(); + } + + server.emit( + 'descriptionReceived', + new ServerDescription(server.description.address, null, { + error, + topologyVersion: + error && error.topologyVersion ? error.topologyVersion : server.description.topologyVersion + }) + ); +} + +function connectionIsStale(pool, connection) { + return connection.generation !== pool.generation; +} + +function shouldHandleStateChangeError(server, err) { + const etv = err.topologyVersion; + const stv = server.description.topologyVersion; + + return compareTopologyVersion(stv, etv) < 0; +} + +function inActiveTransaction(session, cmd) { + return session && session.inTransaction() && !isTransactionCommand(cmd); +} + +function makeOperationHandler(server, connection, cmd, options, callback) { + const session = options && options.session; + + return function handleOperationResult(err, result) { + if (err && !connectionIsStale(server.s.pool, connection)) { + if (err instanceof MongoNetworkError) { + if (session && !session.hasEnded) { + session.serverSession.isDirty = true; + } + + if (supportsRetryableWrites(server) && !inActiveTransaction(session, cmd)) { + err.addErrorLabel('RetryableWriteError'); + } + + if (!(err instanceof MongoNetworkTimeoutError) || isNetworkErrorBeforeHandshake(err)) { + markServerUnknown(server, err); + server.s.pool.clear(); + } + } else { + // if pre-4.4 server, then add error label if its a retryable write error + if ( + maxWireVersion(server) < 9 && + isRetryableWriteError(err) && + !inActiveTransaction(session, cmd) + ) { + err.addErrorLabel('RetryableWriteError'); + } + + if (isSDAMUnrecoverableError(err)) { + if (shouldHandleStateChangeError(server, err)) { + if (maxWireVersion(server) <= 7 || isNodeShuttingDownError(err)) { + server.s.pool.clear(); + } + + markServerUnknown(server, err); + process.nextTick(() => server.requestCheck()); + } + } + } + } + + callback(err, result); + }; +} + +module.exports = { + Server +}; + + +/***/ }), + +/***/ 750: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const arrayStrictEqual = __webpack_require__(1178).arrayStrictEqual; +const tagsStrictEqual = __webpack_require__(1178).tagsStrictEqual; +const errorStrictEqual = __webpack_require__(1178).errorStrictEqual; +const ServerType = __webpack_require__(2291).ServerType; +const now = __webpack_require__(1371).now; + +const WRITABLE_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.Standalone, + ServerType.Mongos +]); + +const DATA_BEARING_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.RSSecondary, + ServerType.Mongos, + ServerType.Standalone +]); + +const ISMASTER_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'maxBsonObjectSize', + 'maxMessageSizeBytes', + 'maxWriteBatchSize', + 'compression', + 'me', + 'hosts', + 'passives', + 'arbiters', + 'tags', + 'setName', + 'setVersion', + 'electionId', + 'primary', + 'logicalSessionTimeoutMinutes', + 'saslSupportedMechs', + '__nodejs_mock_server__', + '$clusterTime' +]; + +/** + * The client's view of a single server, based on the most recent ismaster outcome. + * + * Internal type, not meant to be directly instantiated + */ +class ServerDescription { + /** + * Create a ServerDescription + * @param {String} address The address of the server + * @param {Object} [ismaster] An optional ismaster response for this server + * @param {Object} [options] Optional settings + * @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms) + * @param {Error} [options.error] An Error used for better reporting debugging + * @param {any} [options.topologyVersion] The topologyVersion + */ + constructor(address, ismaster, options) { + options = options || {}; + ismaster = Object.assign( + { + minWireVersion: 0, + maxWireVersion: 0, + hosts: [], + passives: [], + arbiters: [], + tags: [] + }, + ismaster + ); + + this.address = address; + this.error = options.error; + this.roundTripTime = options.roundTripTime || -1; + this.lastUpdateTime = now(); + this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null; + this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null; + this.type = parseServerType(ismaster); + this.topologyVersion = options.topologyVersion || ismaster.topologyVersion; + + // direct mappings + ISMASTER_FIELDS.forEach(field => { + if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field]; + }); + + // normalize case for hosts + if (this.me) this.me = this.me.toLowerCase(); + this.hosts = this.hosts.map(host => host.toLowerCase()); + this.passives = this.passives.map(host => host.toLowerCase()); + this.arbiters = this.arbiters.map(host => host.toLowerCase()); + } + + get allHosts() { + return this.hosts.concat(this.arbiters).concat(this.passives); + } + + /** + * @return {Boolean} Is this server available for reads + */ + get isReadable() { + return this.type === ServerType.RSSecondary || this.isWritable; + } + + /** + * @return {Boolean} Is this server data bearing + */ + get isDataBearing() { + return DATA_BEARING_SERVER_TYPES.has(this.type); + } + + /** + * @return {Boolean} Is this server available for writes + */ + get isWritable() { + return WRITABLE_SERVER_TYPES.has(this.type); + } + + get host() { + const chopLength = `:${this.port}`.length; + return this.address.slice(0, -chopLength); + } + + get port() { + const port = this.address.split(':').pop(); + return port ? Number.parseInt(port, 10) : port; + } + + /** + * Determines if another `ServerDescription` is equal to this one per the rules defined + * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} + * + * @param {ServerDescription} other + * @return {Boolean} + */ + equals(other) { + const topologyVersionsEqual = + this.topologyVersion === other.topologyVersion || + compareTopologyVersion(this.topologyVersion, other.topologyVersion) === 0; + + return ( + other != null && + errorStrictEqual(this.error, other.error) && + this.type === other.type && + this.minWireVersion === other.minWireVersion && + this.me === other.me && + arrayStrictEqual(this.hosts, other.hosts) && + tagsStrictEqual(this.tags, other.tags) && + this.setName === other.setName && + this.setVersion === other.setVersion && + (this.electionId + ? other.electionId && this.electionId.equals(other.electionId) + : this.electionId === other.electionId) && + this.primary === other.primary && + this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes && + topologyVersionsEqual + ); + } +} + +/** + * Parses an `ismaster` message and determines the server type + * + * @param {Object} ismaster The `ismaster` message to parse + * @return {ServerType} + */ +function parseServerType(ismaster) { + if (!ismaster || !ismaster.ok) { + return ServerType.Unknown; + } + + if (ismaster.isreplicaset) { + return ServerType.RSGhost; + } + + if (ismaster.msg && ismaster.msg === 'isdbgrid') { + return ServerType.Mongos; + } + + if (ismaster.setName) { + if (ismaster.hidden) { + return ServerType.RSOther; + } else if (ismaster.ismaster) { + return ServerType.RSPrimary; + } else if (ismaster.secondary) { + return ServerType.RSSecondary; + } else if (ismaster.arbiterOnly) { + return ServerType.RSArbiter; + } else { + return ServerType.RSOther; + } + } + + return ServerType.Standalone; +} + +/** + * Compares two topology versions. + * + * @param {object} lhs + * @param {object} rhs + * @returns A negative number if `lhs` is older than `rhs`; positive if `lhs` is newer than `rhs`; 0 if they are equivalent. + */ +function compareTopologyVersion(lhs, rhs) { + if (lhs == null || rhs == null) { + return -1; + } + + if (lhs.processId.equals(rhs.processId)) { + // TODO [$5f5fbe42fcabad09c1c241a5]: handle counters as Longs + if (lhs.counter === rhs.counter) { + return 0; + } else if (lhs.counter < rhs.counter) { + return -1; + } + + return 1; + } + + return -1; +} + +module.exports = { + ServerDescription, + parseServerType, + compareTopologyVersion +}; + + +/***/ }), + +/***/ 4547: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const ServerType = __webpack_require__(2291).ServerType; +const TopologyType = __webpack_require__(2291).TopologyType; +const ReadPreference = __webpack_require__(4485); +const MongoError = __webpack_require__(3111).MongoError; + +// max staleness constants +const IDLE_WRITE_PERIOD = 10000; +const SMALLEST_MAX_STALENESS_SECONDS = 90; + +/** + * Returns a server selector that selects for writable servers + */ +function writableServerSelector() { + return function(topologyDescription, servers) { + return latencyWindowReducer( + topologyDescription, + servers.filter(s => s.isWritable) + ); + }; +} + +/** + * Reduces the passed in array of servers by the rules of the "Max Staleness" specification + * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst + * + * @param {ReadPreference} readPreference The read preference providing max staleness guidance + * @param {topologyDescription} topologyDescription The topology description + * @param {ServerDescription[]} servers The list of server descriptions to be reduced + * @return {ServerDescription[]} The list of servers that satisfy the requirements of max staleness + */ +function maxStalenessReducer(readPreference, topologyDescription, servers) { + if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { + return servers; + } + + const maxStaleness = readPreference.maxStalenessSeconds; + const maxStalenessVariance = + (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; + if (maxStaleness < maxStalenessVariance) { + throw new MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`); + } + + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new MongoError( + `maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` + ); + } + + if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { + const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0]; + return servers.reduce((result, server) => { + const stalenessMS = + server.lastUpdateTime - + server.lastWriteDate - + (primary.lastUpdateTime - primary.lastWriteDate) + + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + if (staleness <= readPreference.maxStalenessSeconds) result.push(server); + return result; + }, []); + } + + if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { + if (servers.length === 0) { + return servers; + } + + const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max)); + return servers.reduce((result, server) => { + const stalenessMS = + sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + if (staleness <= readPreference.maxStalenessSeconds) result.push(server); + return result; + }, []); + } + + return servers; +} + +/** + * Determines whether a server's tags match a given set of tags + * + * @param {String[]} tagSet The requested tag set to match + * @param {String[]} serverTags The server's tags + */ +function tagSetMatch(tagSet, serverTags) { + const keys = Object.keys(tagSet); + const serverTagKeys = Object.keys(serverTags); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { + return false; + } + } + + return true; +} + +/** + * Reduces a set of server descriptions based on tags requested by the read preference + * + * @param {ReadPreference} readPreference The read preference providing the requested tags + * @param {ServerDescription[]} servers The list of server descriptions to reduce + * @return {ServerDescription[]} The list of servers matching the requested tags + */ +function tagSetReducer(readPreference, servers) { + if ( + readPreference.tags == null || + (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) + ) { + return servers; + } + + for (let i = 0; i < readPreference.tags.length; ++i) { + const tagSet = readPreference.tags[i]; + const serversMatchingTagset = servers.reduce((matched, server) => { + if (tagSetMatch(tagSet, server.tags)) matched.push(server); + return matched; + }, []); + + if (serversMatchingTagset.length) { + return serversMatchingTagset; + } + } + + return []; +} + +/** + * Reduces a list of servers to ensure they fall within an acceptable latency window. This is + * further specified in the "Server Selection" specification, found here: + * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst + * + * @param {topologyDescription} topologyDescription The topology description + * @param {ServerDescription[]} servers The list of servers to reduce + * @returns {ServerDescription[]} The servers which fall within an acceptable latency window + */ +function latencyWindowReducer(topologyDescription, servers) { + const low = servers.reduce( + (min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)), + -1 + ); + + const high = low + topologyDescription.localThresholdMS; + + return servers.reduce((result, server) => { + if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); + return result; + }, []); +} + +// filters +function primaryFilter(server) { + return server.type === ServerType.RSPrimary; +} + +function secondaryFilter(server) { + return server.type === ServerType.RSSecondary; +} + +function nearestFilter(server) { + return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; +} + +function knownFilter(server) { + return server.type !== ServerType.Unknown; +} + +/** + * Returns a function which selects servers based on a provided read preference + * + * @param {ReadPreference} readPreference The read preference to select with + */ +function readPreferenceServerSelector(readPreference) { + if (!readPreference.isValid()) { + throw new TypeError('Invalid read preference specified'); + } + + return function(topologyDescription, servers) { + const commonWireVersion = topologyDescription.commonWireVersion; + if ( + commonWireVersion && + readPreference.minWireVersion && + readPreference.minWireVersion > commonWireVersion + ) { + throw new MongoError( + `Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'` + ); + } + + if (topologyDescription.type === TopologyType.Unknown) { + return []; + } + + if ( + topologyDescription.type === TopologyType.Single || + topologyDescription.type === TopologyType.Sharded + ) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); + } + + const mode = readPreference.mode; + if (mode === ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); + } + + if (mode === ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } + } + + const filter = mode === ReadPreference.NEAREST ? nearestFilter : secondaryFilter; + const selectedServers = latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)) + ) + ); + + if (mode === ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { + return servers.filter(primaryFilter); + } + + return selectedServers; + }; +} + +module.exports = { + writableServerSelector, + readPreferenceServerSelector +}; + + +/***/ }), + +/***/ 9663: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +var __webpack_unused_export__; + + +const Logger = __webpack_require__(104); +const EventEmitter = __webpack_require__(8614).EventEmitter; +const dns = __webpack_require__(881); +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param {String} srvAddress The address to check against a domain + * @param {String} parentDomain The domain to check the provided address against + * @return {Boolean} Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress, parentDomain) { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} + +class SrvPollingEvent { + constructor(srvRecords) { + this.srvRecords = srvRecords; + } + + addresses() { + return new Set(this.srvRecords.map(record => `${record.name}:${record.port}`)); + } +} + +class SrvPoller extends EventEmitter { + /** + * @param {object} options + * @param {string} options.srvHost + * @param {number} [options.heartbeatFrequencyMS] + * @param {function} [options.logger] + * @param {string} [options.loggerLevel] + */ + constructor(options) { + super(); + + if (!options || !options.srvHost) { + throw new TypeError('options for SrvPoller must exist and include srvHost'); + } + + this.srvHost = options.srvHost; + this.rescanSrvIntervalMS = 60000; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + this.logger = Logger('srvPoller', options); + + this.haMode = false; + this.generation = 0; + + this._timeout = null; + } + + get srvAddress() { + return `_mongodb._tcp.${this.srvHost}`; + } + + get intervalMS() { + return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS; + } + + start() { + if (!this._timeout) { + this.schedule(); + } + } + + stop() { + if (this._timeout) { + clearTimeout(this._timeout); + this.generation += 1; + this._timeout = null; + } + } + + schedule() { + clearTimeout(this._timeout); + this._timeout = setTimeout(() => this._poll(), this.intervalMS); + } + + success(srvRecords) { + this.haMode = false; + this.schedule(); + this.emit('srvRecordDiscovery', new SrvPollingEvent(srvRecords)); + } + + failure(message, obj) { + this.logger.warn(message, obj); + this.haMode = true; + this.schedule(); + } + + parentDomainMismatch(srvRecord) { + this.logger.warn( + `parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`, + srvRecord + ); + } + + _poll() { + const generation = this.generation; + dns.resolveSrv(this.srvAddress, (err, srvRecords) => { + if (generation !== this.generation) { + return; + } + + if (err) { + this.failure('DNS error', err); + return; + } + + const finalAddresses = []; + srvRecords.forEach(record => { + if (matchesParentDomain(record.name, this.srvHost)) { + finalAddresses.push(record); + } else { + this.parentDomainMismatch(record); + } + }); + + if (!finalAddresses.length) { + this.failure('No valid addresses found at host'); + return; + } + + this.success(finalAddresses); + }); + } +} + +__webpack_unused_export__ = SrvPollingEvent; +module.exports.D = SrvPoller; + + +/***/ }), + +/***/ 4149: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const Denque = __webpack_require__(2342); +const EventEmitter = __webpack_require__(8614); +const ServerDescription = __webpack_require__(750).ServerDescription; +const ServerType = __webpack_require__(2291).ServerType; +const TopologyDescription = __webpack_require__(7962).TopologyDescription; +const TopologyType = __webpack_require__(2291).TopologyType; +const events = __webpack_require__(2785); +const Server = __webpack_require__(7062).Server; +const relayEvents = __webpack_require__(1178).relayEvents; +const ReadPreference = __webpack_require__(4485); +const isRetryableWritesSupported = __webpack_require__(2306).isRetryableWritesSupported; +const CoreCursor = __webpack_require__(4847).CoreCursor; +const deprecate = __webpack_require__(1669).deprecate; +const BSON = __webpack_require__(7746).retrieveBSON(); +const createCompressionInfo = __webpack_require__(2306).createCompressionInfo; +const ClientSession = __webpack_require__(5474).ClientSession; +const MongoError = __webpack_require__(3111).MongoError; +const MongoServerSelectionError = __webpack_require__(3111).MongoServerSelectionError; +const resolveClusterTime = __webpack_require__(2306).resolveClusterTime; +const SrvPoller = __webpack_require__(9663)/* .SrvPoller */ .D; +const getMMAPError = __webpack_require__(2306).getMMAPError; +const makeStateMachine = __webpack_require__(1178).makeStateMachine; +const eachAsync = __webpack_require__(1178).eachAsync; +const emitDeprecationWarning = __webpack_require__(1371).emitDeprecationWarning; +const ServerSessionPool = __webpack_require__(5474).ServerSessionPool; +const makeClientMetadata = __webpack_require__(1178).makeClientMetadata; +const CMAP_EVENT_NAMES = __webpack_require__(897).CMAP_EVENT_NAMES; +const compareTopologyVersion = __webpack_require__(750).compareTopologyVersion; + +const common = __webpack_require__(2291); +const drainTimerQueue = common.drainTimerQueue; +const clearAndRemoveTimerFrom = common.clearAndRemoveTimerFrom; + +const serverSelection = __webpack_require__(4547); +const readPreferenceServerSelector = serverSelection.readPreferenceServerSelector; +const writableServerSelector = serverSelection.writableServerSelector; + +// Global state +let globalTopologyCounter = 0; + +// events that we relay to the `Topology` +const SERVER_RELAY_EVENTS = [ + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + + // NOTE: Legacy events + 'monitoring' +].concat(CMAP_EVENT_NAMES); + +// all events we listen to from `Server` instances +const LOCAL_SERVER_EVENTS = ['connect', 'descriptionReceived', 'close', 'ended']; + +const STATE_CLOSING = common.STATE_CLOSING; +const STATE_CLOSED = common.STATE_CLOSED; +const STATE_CONNECTING = common.STATE_CONNECTING; +const STATE_CONNECTED = common.STATE_CONNECTED; +const stateTransition = makeStateMachine({ + [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], + [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], + [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], + [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] +}); + +const DEPRECATED_OPTIONS = new Set([ + 'autoReconnect', + 'reconnectTries', + 'reconnectInterval', + 'bufferMaxEntries' +]); + +const kCancelled = Symbol('cancelled'); +const kWaitQueue = Symbol('waitQueue'); + +/** + * A container of server instances representing a connection to a MongoDB topology. + * + * @fires Topology#serverOpening + * @fires Topology#serverClosed + * @fires Topology#serverDescriptionChanged + * @fires Topology#topologyOpening + * @fires Topology#topologyClosed + * @fires Topology#topologyDescriptionChanged + * @fires Topology#serverHeartbeatStarted + * @fires Topology#serverHeartbeatSucceeded + * @fires Topology#serverHeartbeatFailed + */ +class Topology extends EventEmitter { + /** + * Create a topology + * + * @param {Array|String} [seedlist] a string list, or array of Server instances to connect to + * @param {Object} [options] Optional settings + * @param {Number} [options.localThresholdMS=15] The size of the latency window for selecting among multiple suitable servers + * @param {Number} [options.serverSelectionTimeoutMS=30000] How long to block for server selection before throwing an error + * @param {Number} [options.heartbeatFrequencyMS=10000] The frequency with which topology updates are scheduled + */ + constructor(seedlist, options) { + super(); + if (typeof options === 'undefined' && typeof seedlist !== 'string') { + options = seedlist; + seedlist = []; + + // this is for legacy single server constructor support + if (options.host) { + seedlist.push({ host: options.host, port: options.port }); + } + } + + seedlist = seedlist || []; + if (typeof seedlist === 'string') { + seedlist = parseStringSeedlist(seedlist); + } + + options = Object.assign({}, common.TOPOLOGY_DEFAULTS, options); + options = Object.freeze( + Object.assign(options, { + metadata: makeClientMetadata(options), + compression: { compressors: createCompressionInfo(options) } + }) + ); + + DEPRECATED_OPTIONS.forEach(optionName => { + if (options[optionName]) { + emitDeprecationWarning( + `The option \`${optionName}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`, + 'DeprecationWarning' + ); + } + }); + + const topologyType = topologyTypeFromSeedlist(seedlist, options); + const topologyId = globalTopologyCounter++; + const serverDescriptions = seedlist.reduce((result, seed) => { + if (seed.domain_socket) seed.host = seed.domain_socket; + const address = seed.port ? `${seed.host}:${seed.port}` : `${seed.host}:27017`; + result.set(address, new ServerDescription(address)); + return result; + }, new Map()); + + this[kWaitQueue] = new Denque(); + this.s = { + // the id of this topology + id: topologyId, + // passed in options + options, + // initial seedlist of servers to connect to + seedlist: seedlist, + // initial state + state: STATE_CLOSED, + // the topology description + description: new TopologyDescription( + topologyType, + serverDescriptions, + options.replicaSet, + null, + null, + null, + options + ), + serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, + heartbeatFrequencyMS: options.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS, + // allow users to override the cursor factory + Cursor: options.cursorFactory || CoreCursor, + // the bson parser + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // a map of server instances to normalized addresses + servers: new Map(), + // Server Session Pool + sessionPool: new ServerSessionPool(this), + // Active client sessions + sessions: new Set(), + // Promise library + promiseLibrary: options.promiseLibrary || Promise, + credentials: options.credentials, + clusterTime: null, + + // timer management + connectionTimers: new Set() + }; + + if (options.srvHost) { + this.s.srvPoller = + options.srvPoller || + new SrvPoller({ + heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, + srvHost: options.srvHost, // TODO: GET THIS + logger: options.logger, + loggerLevel: options.loggerLevel + }); + this.s.detectTopologyDescriptionChange = ev => { + const previousType = ev.previousDescription.type; + const newType = ev.newDescription.type; + + if (previousType !== TopologyType.Sharded && newType === TopologyType.Sharded) { + this.s.handleSrvPolling = srvPollingHandler(this); + this.s.srvPoller.on('srvRecordDiscovery', this.s.handleSrvPolling); + this.s.srvPoller.start(); + } + }; + + this.on('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); + } + + // NOTE: remove this when NODE-1709 is resolved + this.setMaxListeners(Infinity); + } + + /** + * @return A `TopologyDescription` for this topology + */ + get description() { + return this.s.description; + } + + get parserType() { + return BSON.native ? 'c++' : 'js'; + } + + /** + * Initiate server connect + * + * @param {Object} [options] Optional settings + * @param {Array} [options.auth=null] Array of auth options to apply on connect + * @param {function} [callback] An optional callback called once on the first connected server + */ + connect(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + if (this.s.state === STATE_CONNECTED) { + if (typeof callback === 'function') { + callback(); + } + + return; + } + + stateTransition(this, STATE_CONNECTING); + + // emit SDAM monitoring events + this.emit('topologyOpening', new events.TopologyOpeningEvent(this.s.id)); + + // emit an event for the topology change + this.emit( + 'topologyDescriptionChanged', + new events.TopologyDescriptionChangedEvent( + this.s.id, + new TopologyDescription(TopologyType.Unknown), // initial is always Unknown + this.s.description + ) + ); + + // connect all known servers, then attempt server selection to connect + connectServers(this, Array.from(this.s.description.servers.values())); + + ReadPreference.translate(options); + const readPreference = options.readPreference || ReadPreference.primary; + const connectHandler = err => { + if (err) { + this.close(); + + if (typeof callback === 'function') { + callback(err); + } else { + this.emit('error', err); + } + + return; + } + + stateTransition(this, STATE_CONNECTED); + this.emit('open', err, this); + this.emit('connect', this); + + if (typeof callback === 'function') callback(err, this); + }; + + // TODO [$5f5fbe42fcabad09c1c241a6]: NODE-2471 + if (this.s.credentials) { + this.command('admin.$cmd', { ping: 1 }, { readPreference }, connectHandler); + return; + } + + this.selectServer(readPreferenceServerSelector(readPreference), options, connectHandler); + } + + /** + * Close this topology + */ + close(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + if (typeof options === 'boolean') { + options = { force: options }; + } + + options = options || {}; + if (this.s.state === STATE_CLOSED || this.s.state === STATE_CLOSING) { + if (typeof callback === 'function') { + callback(); + } + + return; + } + + stateTransition(this, STATE_CLOSING); + + drainWaitQueue(this[kWaitQueue], new MongoError('Topology closed')); + drainTimerQueue(this.s.connectionTimers); + + if (this.s.srvPoller) { + this.s.srvPoller.stop(); + if (this.s.handleSrvPolling) { + this.s.srvPoller.removeListener('srvRecordDiscovery', this.s.handleSrvPolling); + delete this.s.handleSrvPolling; + } + } + + if (this.s.detectTopologyDescriptionChange) { + this.removeListener('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); + delete this.s.detectTopologyDescriptionChange; + } + + this.s.sessions.forEach(session => session.endSession()); + this.s.sessionPool.endAllPooledSessions(() => { + eachAsync( + Array.from(this.s.servers.values()), + (server, cb) => destroyServer(server, this, options, cb), + err => { + this.s.servers.clear(); + + // emit an event for close + this.emit('topologyClosed', new events.TopologyClosedEvent(this.s.id)); + + stateTransition(this, STATE_CLOSED); + this.emit('close'); + + if (typeof callback === 'function') { + callback(err); + } + } + ); + }); + } + + /** + * Selects a server according to the selection predicate provided + * + * @param {function} [selector] An optional selector to select servers by, defaults to a random selection within a latency window + * @param {object} [options] Optional settings related to server selection + * @param {number} [options.serverSelectionTimeoutMS] How long to block for server selection before throwing an error + * @param {function} callback The callback used to indicate success or failure + * @return {Server} An instance of a `Server` meeting the criteria of the predicate provided + */ + selectServer(selector, options, callback) { + if (typeof options === 'function') { + callback = options; + if (typeof selector !== 'function') { + options = selector; + + let readPreference; + if (selector instanceof ReadPreference) { + readPreference = selector; + } else if (typeof selector === 'string') { + readPreference = new ReadPreference(selector); + } else { + ReadPreference.translate(options); + readPreference = options.readPreference || ReadPreference.primary; + } + + selector = readPreferenceServerSelector(readPreference); + } else { + options = {}; + } + } + + options = Object.assign( + {}, + { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, + options + ); + + const isSharded = this.description.type === TopologyType.Sharded; + const session = options.session; + const transaction = session && session.transaction; + + if (isSharded && transaction && transaction.server) { + callback(undefined, transaction.server); + return; + } + + // support server selection by options with readPreference + let serverSelector = selector; + if (typeof selector === 'object') { + const readPreference = selector.readPreference + ? selector.readPreference + : ReadPreference.primary; + + serverSelector = readPreferenceServerSelector(readPreference); + } + + const waitQueueMember = { + serverSelector, + transaction, + callback + }; + + const serverSelectionTimeoutMS = options.serverSelectionTimeoutMS; + if (serverSelectionTimeoutMS) { + waitQueueMember.timer = setTimeout(() => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timer = undefined; + const timeoutError = new MongoServerSelectionError( + `Server selection timed out after ${serverSelectionTimeoutMS} ms`, + this.description + ); + + waitQueueMember.callback(timeoutError); + }, serverSelectionTimeoutMS); + } + + this[kWaitQueue].push(waitQueueMember); + processWaitQueue(this); + } + + // Sessions related methods + + /** + * @return Whether the topology should initiate selection to determine session support + */ + shouldCheckForSessionSupport() { + if (this.description.type === TopologyType.Single) { + return !this.description.hasKnownServers; + } + + return !this.description.hasDataBearingServers; + } + + /** + * @return Whether sessions are supported on the current topology + */ + hasSessionSupport() { + return this.description.logicalSessionTimeoutMinutes != null; + } + + /** + * Start a logical session + */ + startSession(options, clientOptions) { + const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); + session.once('ended', () => { + this.s.sessions.delete(session); + }); + + this.s.sessions.add(session); + return session; + } + + /** + * Send endSessions command(s) with the given session ids + * + * @param {Array} sessions The sessions to end + * @param {function} [callback] + */ + endSessions(sessions, callback) { + if (!Array.isArray(sessions)) { + sessions = [sessions]; + } + + this.command( + 'admin.$cmd', + { endSessions: sessions }, + { readPreference: ReadPreference.primaryPreferred, noResponse: true }, + () => { + // intentionally ignored, per spec + if (typeof callback === 'function') callback(); + } + ); + } + + /** + * Update the internal TopologyDescription with a ServerDescription + * + * @param {object} serverDescription The server to update in the internal list of server descriptions + */ + serverUpdateHandler(serverDescription) { + if (!this.s.description.hasServer(serverDescription.address)) { + return; + } + + // ignore this server update if its from an outdated topologyVersion + if (isStaleServerDescription(this.s.description, serverDescription)) { + return; + } + + // these will be used for monitoring events later + const previousTopologyDescription = this.s.description; + const previousServerDescription = this.s.description.servers.get(serverDescription.address); + + // Driver Sessions Spec: "Whenever a driver receives a cluster time from + // a server it MUST compare it to the current highest seen cluster time + // for the deployment. If the new cluster time is higher than the + // highest seen cluster time it MUST become the new highest seen cluster + // time. Two cluster times are compared using only the BsonTimestamp + // value of the clusterTime embedded field." + const clusterTime = serverDescription.$clusterTime; + if (clusterTime) { + resolveClusterTime(this, clusterTime); + } + + // If we already know all the information contained in this updated description, then + // we don't need to emit SDAM events, but still need to update the description, in order + // to keep client-tracked attributes like last update time and round trip time up to date + const equalDescriptions = + previousServerDescription && previousServerDescription.equals(serverDescription); + + // first update the TopologyDescription + this.s.description = this.s.description.update(serverDescription); + if (this.s.description.compatibilityError) { + this.emit('error', new MongoError(this.s.description.compatibilityError)); + return; + } + + // emit monitoring events for this change + if (!equalDescriptions) { + this.emit( + 'serverDescriptionChanged', + new events.ServerDescriptionChangedEvent( + this.s.id, + serverDescription.address, + previousServerDescription, + this.s.description.servers.get(serverDescription.address) + ) + ); + } + + // update server list from updated descriptions + updateServers(this, serverDescription); + + // attempt to resolve any outstanding server selection attempts + if (this[kWaitQueue].length > 0) { + processWaitQueue(this); + } + + if (!equalDescriptions) { + this.emit( + 'topologyDescriptionChanged', + new events.TopologyDescriptionChangedEvent( + this.s.id, + previousTopologyDescription, + this.s.description + ) + ); + } + } + + auth(credentials, callback) { + if (typeof credentials === 'function') (callback = credentials), (credentials = null); + if (typeof callback === 'function') callback(null, true); + } + + logout(callback) { + if (typeof callback === 'function') callback(null, true); + } + + // Basic operation support. Eventually this should be moved into command construction + // during the command refactor. + + /** + * Insert one or more documents + * + * @param {String} ns The full qualified namespace for this operation + * @param {Array} ops An array of documents to insert + * @param {Boolean} [options.ordered=true] Execute in order or out of order + * @param {Object} [options.writeConcern] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {ClientSession} [options.session] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + insert(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'insert', ns, ops }, options, callback); + } + + /** + * Perform one or more update operations + * + * @param {string} ns The fully qualified namespace for this operation + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {ClientSession} [options.session] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + update(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'update', ns, ops }, options, callback); + } + + /** + * Perform one or more remove operations + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + remove(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'remove', ns, ops }, options, callback); + } + + /** + * Execute a command + * + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + command(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + ReadPreference.translate(options); + const readPreference = options.readPreference || ReadPreference.primary; + + this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { + if (err) { + callback(err); + return; + } + + const willRetryWrite = + !options.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(this) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!shouldRetryOperation(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, options, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + server.command(ns, cmd, options, cb); + }); + } + + /** + * Create a new cursor + * + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ + cursor(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + const CursorClass = options.cursorFactory || this.s.Cursor; + ReadPreference.translate(options); + + return new CursorClass(topology, ns, cmd, options); + } + + get clientMetadata() { + return this.s.options.metadata; + } + + isConnected() { + return this.s.state === STATE_CONNECTED; + } + + isDestroyed() { + return this.s.state === STATE_CLOSED; + } + + unref() { + console.log('not implemented: `unref`'); + } + + // NOTE: There are many places in code where we explicitly check the last isMaster + // to do feature support detection. This should be done any other way, but for + // now we will just return the first isMaster seen, which should suffice. + lastIsMaster() { + const serverDescriptions = Array.from(this.description.servers.values()); + if (serverDescriptions.length === 0) return {}; + + const sd = serverDescriptions.filter(sd => sd.type !== ServerType.Unknown)[0]; + const result = sd || { maxWireVersion: this.description.commonWireVersion }; + return result; + } + + get logicalSessionTimeoutMinutes() { + return this.description.logicalSessionTimeoutMinutes; + } + + get bson() { + return this.s.bson; + } +} + +Object.defineProperty(Topology.prototype, 'clusterTime', { + enumerable: true, + get: function() { + return this.s.clusterTime; + }, + set: function(clusterTime) { + this.s.clusterTime = clusterTime; + } +}); + +// legacy aliases +Topology.prototype.destroy = deprecate( + Topology.prototype.close, + 'destroy() is deprecated, please use close() instead' +); + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +function isStaleServerDescription(topologyDescription, incomingServerDescription) { + const currentServerDescription = topologyDescription.servers.get( + incomingServerDescription.address + ); + const currentTopologyVersion = currentServerDescription.topologyVersion; + return ( + compareTopologyVersion(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0 + ); +} + +/** + * Destroys a server, and removes all event listeners from the instance + * + * @param {Server} server + */ +function destroyServer(server, topology, options, callback) { + options = options || {}; + LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); + + server.destroy(options, () => { + topology.emit( + 'serverClosed', + new events.ServerClosedEvent(topology.s.id, server.description.address) + ); + + SERVER_RELAY_EVENTS.forEach(event => server.removeAllListeners(event)); + if (typeof callback === 'function') { + callback(); + } + }); +} + +/** + * Parses a basic seedlist in string form + * + * @param {string} seedlist The seedlist to parse + */ +function parseStringSeedlist(seedlist) { + return seedlist.split(',').map(seed => ({ + host: seed.split(':')[0], + port: seed.split(':')[1] || 27017 + })); +} + +function topologyTypeFromSeedlist(seedlist, options) { + if (options.directConnection) { + return TopologyType.Single; + } + + const replicaSet = options.replicaSet || options.setName || options.rs_name; + if (replicaSet == null) { + return TopologyType.Unknown; + } + + return TopologyType.ReplicaSetNoPrimary; +} + +function randomSelection(array) { + return array[Math.floor(Math.random() * array.length)]; +} + +function createAndConnectServer(topology, serverDescription, connectDelay) { + topology.emit( + 'serverOpening', + new events.ServerOpeningEvent(topology.s.id, serverDescription.address) + ); + + const server = new Server(serverDescription, topology.s.options, topology); + relayEvents(server, topology, SERVER_RELAY_EVENTS); + + server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); + + if (connectDelay) { + const connectTimer = setTimeout(() => { + clearAndRemoveTimerFrom(connectTimer, topology.s.connectionTimers); + server.connect(); + }, connectDelay); + + topology.s.connectionTimers.add(connectTimer); + return server; + } + + server.connect(); + return server; +} + +/** + * Create `Server` instances for all initially known servers, connect them, and assign + * them to the passed in `Topology`. + * + * @param {Topology} topology The topology responsible for the servers + * @param {ServerDescription[]} serverDescriptions A list of server descriptions to connect + */ +function connectServers(topology, serverDescriptions) { + topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => { + const server = createAndConnectServer(topology, serverDescription); + servers.set(serverDescription.address, server); + return servers; + }, new Map()); +} + +function updateServers(topology, incomingServerDescription) { + // update the internal server's description + if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { + const server = topology.s.servers.get(incomingServerDescription.address); + server.s.description = incomingServerDescription; + } + + // add new servers for all descriptions we currently don't know about locally + for (const serverDescription of topology.description.servers.values()) { + if (!topology.s.servers.has(serverDescription.address)) { + const server = createAndConnectServer(topology, serverDescription); + topology.s.servers.set(serverDescription.address, server); + } + } + + // for all servers no longer known, remove their descriptions and destroy their instances + for (const entry of topology.s.servers) { + const serverAddress = entry[0]; + if (topology.description.hasServer(serverAddress)) { + continue; + } + + const server = topology.s.servers.get(serverAddress); + topology.s.servers.delete(serverAddress); + + // prepare server for garbage collection + destroyServer(server, topology); + } +} + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO [$5f5fbe42fcabad09c1c241a7]: once we drop Node 4, use destructuring either here or in arguments. + const topology = args.topology; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + const willRetryWrite = + !args.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(topology) && + !options.session.inTransaction(); + + topology.selectServer(writableServerSelector(), options, (err, server) => { + if (err) { + callback(err, null); + return; + } + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!shouldRetryOperation(err)) { + err = getMMAPError(err); + return callback(err); + } + + if (willRetryWrite) { + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + } + + return callback(err); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // execute the write operation + server[op](ns, ops, options, handler); + }); +} + +function shouldRetryOperation(err) { + return err instanceof MongoError && err.hasErrorLabel('RetryableWriteError'); +} + +function srvPollingHandler(topology) { + return function handleSrvPolling(ev) { + const previousTopologyDescription = topology.s.description; + topology.s.description = topology.s.description.updateFromSrvPollingEvent(ev); + if (topology.s.description === previousTopologyDescription) { + // Nothing changed, so return + return; + } + + updateServers(topology); + + topology.emit( + 'topologyDescriptionChanged', + new events.TopologyDescriptionChangedEvent( + topology.s.id, + previousTopologyDescription, + topology.s.description + ) + ); + }; +} + +function drainWaitQueue(queue, err) { + while (queue.length) { + const waitQueueMember = queue.shift(); + clearTimeout(waitQueueMember.timer); + if (!waitQueueMember[kCancelled]) { + waitQueueMember.callback(err); + } + } +} + +function processWaitQueue(topology) { + if (topology.s.state === STATE_CLOSED) { + drainWaitQueue(topology[kWaitQueue], new MongoError('Topology is closed, please connect')); + return; + } + + const serverDescriptions = Array.from(topology.description.servers.values()); + const membersToProcess = topology[kWaitQueue].length; + for (let i = 0; i < membersToProcess && topology[kWaitQueue].length; ++i) { + const waitQueueMember = topology[kWaitQueue].shift(); + if (waitQueueMember[kCancelled]) { + continue; + } + + let selectedDescriptions; + try { + const serverSelector = waitQueueMember.serverSelector; + selectedDescriptions = serverSelector + ? serverSelector(topology.description, serverDescriptions) + : serverDescriptions; + } catch (e) { + clearTimeout(waitQueueMember.timer); + waitQueueMember.callback(e); + continue; + } + + if (selectedDescriptions.length === 0) { + topology[kWaitQueue].push(waitQueueMember); + continue; + } + + const selectedServerDescription = randomSelection(selectedDescriptions); + const selectedServer = topology.s.servers.get(selectedServerDescription.address); + const transaction = waitQueueMember.transaction; + const isSharded = topology.description.type === TopologyType.Sharded; + if (isSharded && transaction && transaction.isActive) { + transaction.pinServer(selectedServer); + } + + clearTimeout(waitQueueMember.timer); + waitQueueMember.callback(undefined, selectedServer); + } + + if (topology[kWaitQueue].length > 0) { + // ensure all server monitors attempt monitoring soon + topology.s.servers.forEach(server => process.nextTick(() => server.requestCheck())); + } +} + +/** + * A server opening SDAM monitoring event + * + * @event Topology#serverOpening + * @type {ServerOpeningEvent} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Topology#serverClosed + * @type {ServerClosedEvent} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Topology#serverDescriptionChanged + * @type {ServerDescriptionChangedEvent} + */ + +/** + * A topology open SDAM event + * + * @event Topology#topologyOpening + * @type {TopologyOpeningEvent} + */ + +/** + * A topology closed SDAM event + * + * @event Topology#topologyClosed + * @type {TopologyClosedEvent} + */ + +/** + * A topology structure SDAM change event + * + * @event Topology#topologyDescriptionChanged + * @type {TopologyDescriptionChangedEvent} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event Topology#serverHeartbeatStarted + * @type {ServerHeartbeatStartedEvent} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event Topology#serverHeartbeatFailed + * @type {ServerHearbeatFailedEvent} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event Topology#serverHeartbeatSucceeded + * @type {ServerHeartbeatSucceededEvent} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Topology#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Topology#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Topology#commandFailed + * @type {object} + */ + +module.exports = { + Topology +}; + + +/***/ }), + +/***/ 7962: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const ServerType = __webpack_require__(2291).ServerType; +const ServerDescription = __webpack_require__(750).ServerDescription; +const WIRE_CONSTANTS = __webpack_require__(7161); +const TopologyType = __webpack_require__(2291).TopologyType; + +// contstants related to compatability checks +const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; +const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; +const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; +const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; + +// Representation of a deployment of servers +class TopologyDescription { + /** + * Create a TopologyDescription + * + * @param {string} topologyType + * @param {Map} serverDescriptions the a map of address to ServerDescription + * @param {string} setName + * @param {number} maxSetVersion + * @param {ObjectId} maxElectionId + */ + constructor( + topologyType, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + options + ) { + options = options || {}; + + // TODO [$5f5fbe42fcabad09c1c241a8]: consider assigning all these values to a temporary value `s` which + // we use `Object.freeze` on, ensuring the internal state of this type + // is immutable. + this.type = topologyType || TopologyType.Unknown; + this.setName = setName || null; + this.maxSetVersion = maxSetVersion || null; + this.maxElectionId = maxElectionId || null; + this.servers = serverDescriptions || new Map(); + this.stale = false; + this.compatible = true; + this.compatibilityError = null; + this.logicalSessionTimeoutMinutes = null; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0; + this.localThresholdMS = options.localThresholdMS || 0; + this.commonWireVersion = commonWireVersion || null; + + // save this locally, but don't display when printing the instance out + Object.defineProperty(this, 'options', { value: options, enumberable: false }); + + // determine server compatibility + for (const serverDescription of this.servers.values()) { + if (serverDescription.type === ServerType.Unknown) continue; + + if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + } + + if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; + break; + } + } + + // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set + // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes + // value among ServerDescriptions of all data-bearing server types. If any have a null + // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be + // set to null. + const readableServers = Array.from(this.servers.values()).filter(s => s.isReadable); + this.logicalSessionTimeoutMinutes = readableServers.reduce((result, server) => { + if (server.logicalSessionTimeoutMinutes == null) return null; + if (result == null) return server.logicalSessionTimeoutMinutes; + return Math.min(result, server.logicalSessionTimeoutMinutes); + }, null); + } + + /** + * Returns a new TopologyDescription based on the SrvPollingEvent + * @param {SrvPollingEvent} ev The event + */ + updateFromSrvPollingEvent(ev) { + const newAddresses = ev.addresses(); + const serverDescriptions = new Map(this.servers); + for (const server of this.servers) { + if (newAddresses.has(server[0])) { + newAddresses.delete(server[0]); + } else { + serverDescriptions.delete(server[0]); + } + } + + if (serverDescriptions.size === this.servers.size && newAddresses.size === 0) { + return this; + } + + for (const address of newAddresses) { + serverDescriptions.set(address, new ServerDescription(address)); + } + + return new TopologyDescription( + this.type, + serverDescriptions, + this.setName, + this.maxSetVersion, + this.maxElectionId, + this.commonWireVersion, + this.options, + null + ); + } + + /** + * Returns a copy of this description updated with a given ServerDescription + * + * @param {ServerDescription} serverDescription + */ + update(serverDescription) { + const address = serverDescription.address; + // NOTE: there are a number of prime targets for refactoring here + // once we support destructuring assignments + + // potentially mutated values + let topologyType = this.type; + let setName = this.setName; + let maxSetVersion = this.maxSetVersion; + let maxElectionId = this.maxElectionId; + let commonWireVersion = this.commonWireVersion; + + if (serverDescription.setName && setName && serverDescription.setName !== setName) { + serverDescription = new ServerDescription(address, null); + } + + const serverType = serverDescription.type; + let serverDescriptions = new Map(this.servers); + + // update common wire version + if (serverDescription.maxWireVersion !== 0) { + if (commonWireVersion == null) { + commonWireVersion = serverDescription.maxWireVersion; + } else { + commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); + } + } + + // update the actual server description + serverDescriptions.set(address, serverDescription); + + if (topologyType === TopologyType.Single) { + // once we are defined as single, that never changes + return new TopologyDescription( + TopologyType.Single, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + this.options + ); + } + + if (topologyType === TopologyType.Unknown) { + if (serverType === ServerType.Standalone && this.servers.size !== 1) { + serverDescriptions.delete(address); + } else { + topologyType = topologyTypeForServerType(serverType); + } + } + + if (topologyType === TopologyType.Sharded) { + if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) { + serverDescriptions.delete(address); + } + } + + if (topologyType === TopologyType.ReplicaSetNoPrimary) { + if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { + serverDescriptions.delete(address); + } + + if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId + ); + + (topologyType = result[0]), + (setName = result[1]), + (maxSetVersion = result[2]), + (maxElectionId = result[3]); + } else if ( + [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 + ) { + const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription); + (topologyType = result[0]), (setName = result[1]); + } + } + + if (topologyType === TopologyType.ReplicaSetWithPrimary) { + if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { + serverDescriptions.delete(address); + topologyType = checkHasPrimary(serverDescriptions); + } else if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId + ); + + (topologyType = result[0]), + (setName = result[1]), + (maxSetVersion = result[2]), + (maxElectionId = result[3]); + } else if ( + [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 + ) { + topologyType = updateRsWithPrimaryFromMember( + serverDescriptions, + setName, + serverDescription + ); + } else { + topologyType = checkHasPrimary(serverDescriptions); + } + } + + return new TopologyDescription( + topologyType, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + this.options + ); + } + + get error() { + const descriptionsWithError = Array.from(this.servers.values()).filter(sd => sd.error); + if (descriptionsWithError.length > 0) { + return descriptionsWithError[0].error; + } + } + + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers() { + return Array.from(this.servers.values()).some(sd => sd.type !== ServerType.Unknown); + } + + /** + * Determines if this topology description has a data-bearing server available. + */ + get hasDataBearingServers() { + return Array.from(this.servers.values()).some(sd => sd.isDataBearing); + } + + /** + * Determines if the topology has a definition for the provided address + * + * @param {String} address + * @return {Boolean} Whether the topology knows about this server + */ + hasServer(address) { + return this.servers.has(address); + } +} + +function topologyTypeForServerType(serverType) { + if (serverType === ServerType.Standalone) { + return TopologyType.Single; + } + + if (serverType === ServerType.Mongos) { + return TopologyType.Sharded; + } + + if (serverType === ServerType.RSPrimary) { + return TopologyType.ReplicaSetWithPrimary; + } + + if (serverType === ServerType.RSGhost || serverType === ServerType.Unknown) { + return TopologyType.Unknown; + } + + return TopologyType.ReplicaSetNoPrimary; +} + +function compareObjectId(oid1, oid2) { + if (oid1 == null) { + return -1; + } + + if (oid2 == null) { + return 1; + } + + if (oid1.id instanceof Buffer && oid2.id instanceof Buffer) { + const oid1Buffer = oid1.id; + const oid2Buffer = oid2.id; + return oid1Buffer.compare(oid2Buffer); + } + + const oid1String = oid1.toString(); + const oid2String = oid2.toString(); + return oid1String.localeCompare(oid2String); +} + +function updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId +) { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + + const electionId = serverDescription.electionId ? serverDescription.electionId : null; + if (serverDescription.setVersion && electionId) { + if (maxSetVersion && maxElectionId) { + if ( + maxSetVersion > serverDescription.setVersion || + compareObjectId(maxElectionId, electionId) > 0 + ) { + // this primary is stale, we must remove it + serverDescriptions.set( + serverDescription.address, + new ServerDescription(serverDescription.address) + ); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + + maxElectionId = serverDescription.electionId; + } + + if ( + serverDescription.setVersion != null && + (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) + ) { + maxSetVersion = serverDescription.setVersion; + } + + // We've heard from the primary. Is it the same primary as before? + for (const address of serverDescriptions.keys()) { + const server = serverDescriptions.get(address); + + if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { + // Reset old primary's type to Unknown. + serverDescriptions.set(address, new ServerDescription(server.address)); + + // There can only be one primary + break; + } + } + + // Discover new hosts from this primary's response. + serverDescription.allHosts.forEach(address => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + // Remove hosts not in the response. + const currentAddresses = Array.from(serverDescriptions.keys()); + const responseAddresses = serverDescription.allHosts; + currentAddresses + .filter(addr => responseAddresses.indexOf(addr) === -1) + .forEach(address => { + serverDescriptions.delete(address); + }); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; +} + +function updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) { + if (setName == null) { + throw new TypeError('setName is required'); + } + + if ( + setName !== serverDescription.setName || + (serverDescription.me && serverDescription.address !== serverDescription.me) + ) { + serverDescriptions.delete(serverDescription.address); + } + + return checkHasPrimary(serverDescriptions); +} + +function updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) { + let topologyType = TopologyType.ReplicaSetNoPrimary; + + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [topologyType, setName]; + } + + serverDescription.allHosts.forEach(address => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + if (serverDescription.me && serverDescription.address !== serverDescription.me) { + serverDescriptions.delete(serverDescription.address); + } + + return [topologyType, setName]; +} + +function checkHasPrimary(serverDescriptions) { + for (const addr of serverDescriptions.keys()) { + if (serverDescriptions.get(addr).type === ServerType.RSPrimary) { + return TopologyType.ReplicaSetWithPrimary; + } + } + + return TopologyType.ReplicaSetNoPrimary; +} + +module.exports = { + TopologyDescription +}; + + +/***/ }), + +/***/ 5474: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const retrieveBSON = __webpack_require__(7746).retrieveBSON; +const EventEmitter = __webpack_require__(8614); +const BSON = retrieveBSON(); +const Binary = BSON.Binary; +const uuidV4 = __webpack_require__(1178).uuidV4; +const MongoError = __webpack_require__(3111).MongoError; +const isRetryableError = __webpack_require__(3111).isRetryableError; +const MongoNetworkError = __webpack_require__(3111).MongoNetworkError; +const MongoWriteConcernError = __webpack_require__(3111).MongoWriteConcernError; +const Transaction = __webpack_require__(1707).Transaction; +const TxnState = __webpack_require__(1707).TxnState; +const isPromiseLike = __webpack_require__(1178).isPromiseLike; +const ReadPreference = __webpack_require__(4485); +const maybePromise = __webpack_require__(1371).maybePromise; +const isTransactionCommand = __webpack_require__(1707).isTransactionCommand; +const resolveClusterTime = __webpack_require__(2306).resolveClusterTime; +const isSharded = __webpack_require__(7272).isSharded; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const now = __webpack_require__(1371).now; +const calculateDurationInMs = __webpack_require__(1371).calculateDurationInMs; +const minWireVersionForShardedTransactions = 8; + +function assertAlive(session, callback) { + if (session.serverSession == null) { + const error = new MongoError('Cannot use a session that has ended'); + if (typeof callback === 'function') { + callback(error, null); + return false; + } + + throw error; + } + + return true; +} + +/** + * Options to pass when creating a Client Session + * @typedef {Object} SessionOptions + * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session + * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session. + */ + +/** + * A BSON document reflecting the lsid of a {@link ClientSession} + * @typedef {Object} SessionId + */ + +const kServerSession = Symbol('serverSession'); + +/** + * A class representing a client session on the server + * WARNING: not meant to be instantiated directly. + * @class + * @hideconstructor + */ +class ClientSession extends EventEmitter { + /** + * Create a client session. + * WARNING: not meant to be instantiated directly + * + * @param {Topology} topology The current client's topology (Internal Class) + * @param {ServerSessionPool} sessionPool The server session pool (Internal Class) + * @param {SessionOptions} [options] Optional settings + * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver + */ + constructor(topology, sessionPool, options, clientOptions) { + super(); + + if (topology == null) { + throw new Error('ClientSession requires a topology'); + } + + if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { + throw new Error('ClientSession requires a ServerSessionPool'); + } + + options = options || {}; + clientOptions = clientOptions || {}; + + this.topology = topology; + this.sessionPool = sessionPool; + this.hasEnded = false; + this.clientOptions = clientOptions; + this[kServerSession] = undefined; + + this.supports = { + causalConsistency: + typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true + }; + + this.clusterTime = options.initialClusterTime; + + this.operationTime = null; + this.explicit = !!options.explicit; + this.owner = options.owner; + this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); + this.transaction = new Transaction(); + } + + /** + * The server id associated with this session + * @type {SessionId} + */ + get id() { + return this.serverSession.id; + } + + get serverSession() { + if (this[kServerSession] == null) { + this[kServerSession] = this.sessionPool.acquire(); + } + + return this[kServerSession]; + } + + /** + * Ends this session on the server + * + * @param {Object} [options] Optional settings. Currently reserved for future use + * @param {Function} [callback] Optional callback for completion of this operation + */ + endSession(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const session = this; + return maybePromise(this, callback, done => { + if (session.hasEnded) { + return done(); + } + + function completeEndSession() { + // release the server session back to the pool + session.sessionPool.release(session.serverSession); + session[kServerSession] = undefined; + + // mark the session as ended, and emit a signal + session.hasEnded = true; + session.emit('ended', session); + + // spec indicates that we should ignore all errors for `endSessions` + done(); + } + + if (session.serverSession && session.inTransaction()) { + session.abortTransaction(err => { + if (err) return done(err); + completeEndSession(); + }); + + return; + } + + completeEndSession(); + }); + } + + /** + * Advances the operationTime for a ClientSession. + * + * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime) { + if (this.operationTime == null) { + this.operationTime = operationTime; + return; + } + + if (operationTime.greaterThan(this.operationTime)) { + this.operationTime = operationTime; + } + } + + /** + * Used to determine if this session equals another + * @param {ClientSession} session + * @return {boolean} true if the sessions are equal + */ + equals(session) { + if (!(session instanceof ClientSession)) { + return false; + } + + return this.id.id.buffer.equals(session.id.id.buffer); + } + + /** + * Increment the transaction number on the internal ServerSession + */ + incrementTransactionNumber() { + this.serverSession.txnNumber++; + } + + /** + * @returns {boolean} whether this session is currently in a transaction or not + */ + inTransaction() { + return this.transaction.isActive; + } + + /** + * Starts a new transaction with the given options. + * + * @param {TransactionOptions} options Options for the transaction + */ + startTransaction(options) { + assertAlive(this); + if (this.inTransaction()) { + throw new MongoError('Transaction already in progress'); + } + + const topologyMaxWireVersion = maxWireVersion(this.topology); + if ( + isSharded(this.topology) && + topologyMaxWireVersion != null && + topologyMaxWireVersion < minWireVersionForShardedTransactions + ) { + throw new MongoError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); + } + + // increment txnNumber + this.incrementTransactionNumber(); + + // create transaction state + this.transaction = new Transaction( + Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions) + ); + + this.transaction.transition(TxnState.STARTING_TRANSACTION); + } + + /** + * Commits the currently active transaction in this session. + * + * @param {Function} [callback] optional callback for completion of this operation + * @return {Promise} A promise is returned if no callback is provided + */ + commitTransaction(callback) { + return maybePromise(this, callback, done => endTransaction(this, 'commitTransaction', done)); + } + + /** + * Aborts the currently active transaction in this session. + * + * @param {Function} [callback] optional callback for completion of this operation + * @return {Promise} A promise is returned if no callback is provided + */ + abortTransaction(callback) { + return maybePromise(this, callback, done => endTransaction(this, 'abortTransaction', done)); + } + + /** + * This is here to ensure that ClientSession is never serialized to BSON. + * @ignore + */ + toBSON() { + throw new Error('ClientSession cannot be serialized to BSON.'); + } + + /** + * A user provided function to be run within a transaction + * + * @callback WithTransactionCallback + * @param {ClientSession} session The parent session of the transaction running the operation. This should be passed into each operation within the lambda. + * @returns {Promise} The resulting Promise of operations run within this transaction + */ + + /** + * Runs a provided lambda within a transaction, retrying either the commit operation + * or entire transaction as needed (and when the error permits) to better ensure that + * the transaction can complete successfully. + * + * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not + * return a Promise will result in undefined behavior. + * + * @param {WithTransactionCallback} fn + * @param {TransactionOptions} [options] Optional settings for the transaction + */ + withTransaction(fn, options) { + const startTime = now(); + return attemptTransaction(this, startTime, fn, options); + } +} + +const MAX_WITH_TRANSACTION_TIMEOUT = 120000; +const UNSATISFIABLE_WRITE_CONCERN_CODE = 100; +const UNKNOWN_REPL_WRITE_CONCERN_CODE = 79; +const MAX_TIME_MS_EXPIRED_CODE = 50; +const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ + 'CannotSatisfyWriteConcern', + 'UnknownReplWriteConcern', + 'UnsatisfiableWriteConcern' +]); + +function hasNotTimedOut(startTime, max) { + return calculateDurationInMs(startTime) < max; +} + +function isUnknownTransactionCommitResult(err) { + return ( + isMaxTimeMSExpiredError(err) || + (!NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName) && + err.code !== UNSATISFIABLE_WRITE_CONCERN_CODE && + err.code !== UNKNOWN_REPL_WRITE_CONCERN_CODE) + ); +} + +function isMaxTimeMSExpiredError(err) { + if (err == null) return false; + return ( + err.code === MAX_TIME_MS_EXPIRED_CODE || + (err.writeConcernError && err.writeConcernError.code === MAX_TIME_MS_EXPIRED_CODE) + ); +} + +function attemptTransactionCommit(session, startTime, fn, options) { + return session.commitTransaction().catch(err => { + if ( + err instanceof MongoError && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && + !isMaxTimeMSExpiredError(err) + ) { + if (err.hasErrorLabel('UnknownTransactionCommitResult')) { + return attemptTransactionCommit(session, startTime, fn, options); + } + + if (err.hasErrorLabel('TransientTransactionError')) { + return attemptTransaction(session, startTime, fn, options); + } + } + + throw err; + }); +} + +const USER_EXPLICIT_TXN_END_STATES = new Set([ + TxnState.NO_TRANSACTION, + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_ABORTED +]); + +function userExplicitlyEndedTransaction(session) { + return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); +} + +function attemptTransaction(session, startTime, fn, options) { + session.startTransaction(options); + + let promise; + try { + promise = fn(session); + } catch (err) { + promise = Promise.reject(err); + } + + if (!isPromiseLike(promise)) { + session.abortTransaction(); + throw new TypeError('Function provided to `withTransaction` must return a Promise'); + } + + return promise + .then(() => { + if (userExplicitlyEndedTransaction(session)) { + return; + } + + return attemptTransactionCommit(session, startTime, fn, options); + }) + .catch(err => { + function maybeRetryOrThrow(err) { + if ( + err instanceof MongoError && + err.hasErrorLabel('TransientTransactionError') && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) + ) { + return attemptTransaction(session, startTime, fn, options); + } + + if (isMaxTimeMSExpiredError(err)) { + err.addErrorLabel('UnknownTransactionCommitResult'); + } + + throw err; + } + + if (session.transaction.isActive) { + return session.abortTransaction().then(() => maybeRetryOrThrow(err)); + } + + return maybeRetryOrThrow(err); + }); +} + +function endTransaction(session, commandName, callback) { + if (!assertAlive(session, callback)) { + // checking result in case callback was called + return; + } + + // handle any initial problematic cases + let txnState = session.transaction.state; + + if (txnState === TxnState.NO_TRANSACTION) { + callback(new MongoError('No transaction started')); + return; + } + + if (commandName === 'commitTransaction') { + if ( + txnState === TxnState.STARTING_TRANSACTION || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); + callback(null, null); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoError('Cannot call commitTransaction after calling abortTransaction')); + return; + } + } else { + if (txnState === TxnState.STARTING_TRANSACTION) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + callback(null, null); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoError('Cannot call abortTransaction twice')); + return; + } + + if ( + txnState === TxnState.TRANSACTION_COMMITTED || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + callback(new MongoError('Cannot call abortTransaction after calling commitTransaction')); + return; + } + } + + // construct and send the command + const command = { [commandName]: 1 }; + + // apply a writeConcern if specified + let writeConcern; + if (session.transaction.options.writeConcern) { + writeConcern = Object.assign({}, session.transaction.options.writeConcern); + } else if (session.clientOptions && session.clientOptions.w) { + writeConcern = { w: session.clientOptions.w }; + } + + if (txnState === TxnState.TRANSACTION_COMMITTED) { + writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' }); + } + + if (writeConcern) { + Object.assign(command, { writeConcern }); + } + + if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { + Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); + } + + function commandHandler(e, r) { + if (commandName === 'commitTransaction') { + session.transaction.transition(TxnState.TRANSACTION_COMMITTED); + + if ( + e && + (e instanceof MongoNetworkError || + e instanceof MongoWriteConcernError || + isRetryableError(e) || + isMaxTimeMSExpiredError(e)) + ) { + if (isUnknownTransactionCommitResult(e)) { + e.addErrorLabel('UnknownTransactionCommitResult'); + + // per txns spec, must unpin session in this case + session.transaction.unpinServer(); + } + } + } else { + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + } + + callback(e, r); + } + + // The spec indicates that we should ignore all errors on `abortTransaction` + function transactionError(err) { + return commandName === 'commitTransaction' ? err : null; + } + + if ( + // Assumption here that commandName is "commitTransaction" or "abortTransaction" + session.transaction.recoveryToken && + supportsRecoveryToken(session) + ) { + command.recoveryToken = session.transaction.recoveryToken; + } + + // send the command + session.topology.command('admin.$cmd', command, { session }, (err, reply) => { + if (err && isRetryableError(err)) { + // SPEC-1185: apply majority write concern when retrying commitTransaction + if (command.commitTransaction) { + // per txns spec, must unpin session in this case + session.transaction.unpinServer(); + + command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { + w: 'majority' + }); + } + + return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) => + commandHandler(transactionError(_err), _reply) + ); + } + + commandHandler(transactionError(err), reply); + }); +} + +function supportsRecoveryToken(session) { + const topology = session.topology; + return !!topology.s.options.useRecoveryToken; +} + +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @ignore + */ +class ServerSession { + constructor() { + this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; + this.lastUse = now(); + this.txnNumber = 0; + this.isDirty = false; + } + + /** + * Determines if the server session has timed out. + * @ignore + * @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes" + * @return {boolean} true if the session has timed out. + */ + hasTimedOut(sessionTimeoutMinutes) { + // Take the difference of the lastUse timestamp and now, which will result in a value in + // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` + const idleTimeMinutes = Math.round( + ((calculateDurationInMs(this.lastUse) % 86400000) % 3600000) / 60000 + ); + + return idleTimeMinutes > sessionTimeoutMinutes - 1; + } +} + +/** + * Maintains a pool of Server Sessions. + * For internal use only + * @ignore + */ +class ServerSessionPool { + constructor(topology) { + if (topology == null) { + throw new Error('ServerSessionPool requires a topology'); + } + + this.topology = topology; + this.sessions = []; + } + + /** + * Ends all sessions in the session pool. + * @ignore + */ + endAllPooledSessions(callback) { + if (this.sessions.length) { + this.topology.endSessions( + this.sessions.map(session => session.id), + () => { + this.sessions = []; + if (typeof callback === 'function') { + callback(); + } + } + ); + + return; + } + + if (typeof callback === 'function') { + callback(); + } + } + + /** + * Acquire a Server Session from the pool. + * Iterates through each session in the pool, removing any stale sessions + * along the way. The first non-stale session found is removed from the + * pool and returned. If no non-stale session is found, a new ServerSession + * is created. + * @ignore + * @returns {ServerSession} + */ + acquire() { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + while (this.sessions.length) { + const session = this.sessions.shift(); + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + return session; + } + } + + return new ServerSession(); + } + + /** + * Release a session to the session pool + * Adds the session back to the session pool if the session has not timed out yet. + * This method also removes any stale sessions from the pool. + * @ignore + * @param {ServerSession} session The session to release to the pool + */ + release(session) { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + while (this.sessions.length) { + const pooledSession = this.sessions[this.sessions.length - 1]; + if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { + this.sessions.pop(); + } else { + break; + } + } + + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + if (session.isDirty) { + return; + } + + // otherwise, readd this session to the session pool + this.sessions.unshift(session); + } + } +} + +// TODO [$5f5fbe42fcabad09c1c241a9]: this should be codified in command construction +// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern +function commandSupportsReadConcern(command, options) { + if ( + command.aggregate || + command.count || + command.distinct || + command.find || + command.parallelCollectionScan || + command.geoNear || + command.geoSearch + ) { + return true; + } + + if ( + command.mapReduce && + options && + options.out && + (options.out.inline === 1 || options.out === 'inline') + ) { + return true; + } + + return false; +} + +/** + * Optionally decorate a command with sessions specific keys + * + * @ignore + * @param {ClientSession} session the session tracking transaction state + * @param {Object} command the command to decorate + * @param {Object} topology the topology for tracking the cluster time + * @param {Object} [options] Optional settings passed to calling operation + * @return {MongoError|null} An error, if some error condition was met + */ +function applySession(session, command, options) { + if (session.hasEnded) { + // TODO [$5f5fbe42fcabad09c1c241aa]: merge this with `assertAlive`, did not want to throw a try/catch here + return new MongoError('Cannot use a session that has ended'); + } + + // SPEC-1019: silently ignore explicit session with unacknowledged write for backwards compatibility + if (options && options.writeConcern && options.writeConcern.w === 0) { + return; + } + + const serverSession = session.serverSession; + serverSession.lastUse = now(); + command.lsid = serverSession.id; + + // first apply non-transaction-specific sessions data + const inTransaction = session.inTransaction() || isTransactionCommand(command); + const isRetryableWrite = options.willRetryWrite; + const shouldApplyReadConcern = commandSupportsReadConcern(command, options); + + if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { + command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber); + } + + // now attempt to apply transaction-specific sessions data + if (!inTransaction) { + if (session.transaction.state !== TxnState.NO_TRANSACTION) { + session.transaction.transition(TxnState.NO_TRANSACTION); + } + + // TODO [$5f5fbe42fcabad09c1c241ab]: the following should only be applied to read operation per spec. + // for causal consistency + if (session.supports.causalConsistency && session.operationTime && shouldApplyReadConcern) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + + return; + } + + if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) { + return new MongoError( + `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` + ); + } + + // `autocommit` must always be false to differentiate from retryable writes + command.autocommit = false; + + if (session.transaction.state === TxnState.STARTING_TRANSACTION) { + session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); + command.startTransaction = true; + + const readConcern = + session.transaction.options.readConcern || session.clientOptions.readConcern; + if (readConcern) { + command.readConcern = readConcern; + } + + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + } +} + +function updateSessionFromResponse(session, document) { + if (document.$clusterTime) { + resolveClusterTime(session, document.$clusterTime); + } + + if (document.operationTime && session && session.supports.causalConsistency) { + session.advanceOperationTime(document.operationTime); + } + + if (document.recoveryToken && session && session.inTransaction()) { + session.transaction._recoveryToken = document.recoveryToken; + } +} + +module.exports = { + ClientSession, + ServerSession, + ServerSessionPool, + TxnState, + applySession, + updateSessionFromResponse, + commandSupportsReadConcern +}; + + +/***/ }), + +/***/ 8175: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const inherits = __webpack_require__(1669).inherits; +const f = __webpack_require__(1669).format; +const EventEmitter = __webpack_require__(8614).EventEmitter; +const CoreCursor = __webpack_require__(4847).CoreCursor; +const Logger = __webpack_require__(104); +const retrieveBSON = __webpack_require__(7746).retrieveBSON; +const MongoError = __webpack_require__(3111).MongoError; +const Server = __webpack_require__(6495); +const diff = __webpack_require__(2306).diff; +const cloneOptions = __webpack_require__(2306).cloneOptions; +const SessionMixins = __webpack_require__(2306).SessionMixins; +const isRetryableWritesSupported = __webpack_require__(2306).isRetryableWritesSupported; +const relayEvents = __webpack_require__(1178).relayEvents; +const BSON = retrieveBSON(); +const getMMAPError = __webpack_require__(2306).getMMAPError; +const makeClientMetadata = __webpack_require__(1178).makeClientMetadata; +const legacyIsRetryableWriteError = __webpack_require__(2306).legacyIsRetryableWriteError; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + */ + +// +// States +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var UNREFERENCED = 'unreferenced'; +var DESTROYING = 'destroying'; +var DESTROYED = 'destroyed'; + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYING, DESTROYED, DISCONNECTED], + connecting: [CONNECTING, DESTROYING, DESTROYED, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYING, DESTROYED, UNREFERENCED], + unreferenced: [UNREFERENCED, DESTROYING, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.state = newState; + } else { + self.s.logger.error( + f( + 'Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +// +// ReplSet instance id +var id = 1; +var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; + +/** + * Creates a new Mongos instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {Mongos} A cursor instance + * @fires Mongos#connect + * @fires Mongos#reconnect + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#failed + * @fires Mongos#fullsetup + * @fires Mongos#all + * @fires Mongos#serverHeartbeatStarted + * @fires Mongos#serverHeartbeatSucceeded + * @fires Mongos#serverHeartbeatFailed + * @fires Mongos#topologyOpening + * @fires Mongos#topologyClosed + * @fires Mongos#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var Mongos = function(seedlist, options) { + options = options || {}; + + // Get replSet Id + this.id = id++; + + // deduplicate seedlist + if (Array.isArray(seedlist)) { + seedlist = seedlist.reduce((seeds, seed) => { + if (seeds.find(s => s.host === seed.host && s.port === seed.port)) { + return seeds; + } + + seeds.push(seed); + return seeds; + }, []); + } + + // Internal state + this.s = { + options: Object.assign({ metadata: makeClientMetadata(options) }, options), + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Factory overrides + Cursor: options.cursorFactory || CoreCursor, + // Logger instance + logger: Logger('Mongos', options), + // Seedlist + seedlist: seedlist, + // Ha interval + haInterval: options.haInterval ? options.haInterval : 10000, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Server selection index + index: 0, + // Connect function options passed in + connectOptions: {}, + // Are we running in debug mode + debug: typeof options.debug === 'boolean' ? options.debug : false, + // localThresholdMS + localThresholdMS: options.localThresholdMS || 15 + }; + + // Log info warning if the socketTimeout < haInterval as it will cause + // a lot of recycled connections to happen. + if ( + this.s.logger.isWarn() && + this.s.options.socketTimeout !== 0 && + this.s.options.socketTimeout < this.s.haInterval + ) { + this.s.logger.warn( + f( + 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', + this.s.options.socketTimeout, + this.s.haInterval + ) + ); + } + + // Disconnected state + this.state = DISCONNECTED; + + // Current proxies we are connecting to + this.connectingProxies = []; + // Currently connected proxies + this.connectedProxies = []; + // Disconnected proxies + this.disconnectedProxies = []; + // Index of proxy to run operations against + this.index = 0; + // High availability timeout id + this.haTimeoutId = null; + // Last ismaster + this.ismaster = null; + + // Description of the Replicaset + this.topologyDescription = { + topologyType: 'Unknown', + servers: [] + }; + + // Highest clusterTime seen in responses from the current deployment + this.clusterTime = null; + + // Add event listener + EventEmitter.call(this); +}; + +inherits(Mongos, EventEmitter); +Object.assign(Mongos.prototype, SessionMixins); + +Object.defineProperty(Mongos.prototype, 'type', { + enumerable: true, + get: function() { + return 'mongos'; + } +}); + +Object.defineProperty(Mongos.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + if (!this.ismaster) return null; + return this.ismaster.logicalSessionTimeoutMinutes || null; + } +}); + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +const SERVER_EVENTS = ['serverDescriptionChanged', 'error', 'close', 'timeout', 'parseError']; +function destroyServer(server, options, callback) { + options = options || {}; + SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); + server.destroy(options, callback); +} + +/** + * Initiate server connect + */ +Mongos.prototype.connect = function(options) { + var self = this; + // Add any connect level options to the internal state + this.s.connectOptions = options || {}; + + // Set connecting state + stateTransition(this, CONNECTING); + + // Create server instances + var servers = this.s.seedlist.map(function(x) { + const server = new Server( + Object.assign({}, self.s.options, x, options, { + reconnect: false, + monitoring: false, + parent: self + }) + ); + + relayEvents(server, self, ['serverDescriptionChanged']); + return server; + }); + + // Emit the topology opening event + emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); + + // Start all server connections + connectProxies(self, servers); +}; + +/** + * Authenticate the topology. + * @method + * @param {MongoCredentials} credentials The credentials for authentication we are using + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.auth = function(credentials, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +function handleEvent(self) { + return function() { + if (self.state === DESTROYED || self.state === DESTROYING) { + return; + } + + // Move to list of disconnectedProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); + // Emit the initial topology + emitTopologyDescriptionChanged(self); + // Emit the left signal + self.emit('left', 'mongos', this); + // Emit the sdam event + self.emit('serverClosed', { + topologyId: self.id, + address: this.name + }); + }; +} + +function handleInitialConnectEvent(self, event) { + return function() { + var _this = this; + + // Destroy the instance + if (self.state === DESTROYED) { + // Emit the initial topology + emitTopologyDescriptionChanged(self); + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + return this.destroy(); + } + + // Check the type of server + if (event === 'connect') { + // Get last known ismaster + self.ismaster = _this.lastIsMaster(); + + // Is this not a proxy, remove t + if (self.ismaster.msg === 'isdbgrid') { + // Add to the connectd list + for (let i = 0; i < self.connectedProxies.length; i++) { + if (self.connectedProxies[i].name === _this.name) { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); + // Emit the initial topology + emitTopologyDescriptionChanged(self); + _this.destroy(); + return self.emit('failed', _this); + } + } + + // Remove the handlers + for (let i = 0; i < handlers.length; i++) { + _this.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _this.on('error', handleEvent(self, 'error')); + _this.on('close', handleEvent(self, 'close')); + _this.on('timeout', handleEvent(self, 'timeout')); + _this.on('parseError', handleEvent(self, 'parseError')); + + // Move from connecting proxies connected + moveServerFrom(self.connectingProxies, self.connectedProxies, _this); + // Emit the joined event + self.emit('joined', 'mongos', _this); + } else { + // Print warning if we did not find a mongos proxy + if (self.s.logger.isWarn()) { + var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; + // We have a standalone server + if (!self.ismaster.hosts) { + message = 'expected mongos proxy, but found standalone mongod for server %s'; + } + + self.s.logger.warn(f(message, _this.name)); + } + + // This is not a mongos proxy, destroy and remove it completely + _this.destroy(true); + removeProxyFrom(self.connectingProxies, _this); + // Emit the left event + self.emit('left', 'server', _this); + // Emit failed event + self.emit('failed', _this); + } + } else { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + // Emit the left event + self.emit('left', 'mongos', this); + // Emit failed event + self.emit('failed', this); + } + + // Emit the initial topology + emitTopologyDescriptionChanged(self); + + // Trigger topologyMonitor + if (self.connectingProxies.length === 0) { + // Emit connected if we are connected + if (self.connectedProxies.length > 0 && self.state === CONNECTING) { + // Set the state to connected + stateTransition(self, CONNECTED); + // Emit the connect event + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + } else if (self.disconnectedProxies.length === 0) { + // Print warning if we did not find a mongos proxy + if (self.s.logger.isWarn()) { + self.s.logger.warn( + f('no mongos proxies found in seed list, did you mean to connect to a replicaset') + ); + } + + // Emit the error that no proxies were found + return self.emit('error', new MongoError('no mongos proxies found in seed list')); + } + + // Topology monitor + topologyMonitor(self, { firstConnect: true }); + } + }; +} + +function connectProxies(self, servers) { + // Update connectingProxies + self.connectingProxies = self.connectingProxies.concat(servers); + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + // Emit opening server event + self.emit('serverOpening', { + topologyId: self.id, + address: server.name + }); + + // Emit the initial topology + emitTopologyDescriptionChanged(self); + + // Add event handlers + server.once('close', handleInitialConnectEvent(self, 'close')); + server.once('timeout', handleInitialConnectEvent(self, 'timeout')); + server.once('parseError', handleInitialConnectEvent(self, 'parseError')); + server.once('error', handleInitialConnectEvent(self, 'error')); + server.once('connect', handleInitialConnectEvent(self, 'connect')); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Start connection + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + + // Start all the servers + servers.forEach(server => connect(server, timeoutInterval++)); +} + +function pickProxy(self, session) { + // TODO [$5f5fbe42fcabad09c1c241ac]: Destructure :) + const transaction = session && session.transaction; + + if (transaction && transaction.server) { + if (transaction.server.isConnected()) { + return transaction.server; + } else { + transaction.unpinServer(); + } + } + + // Get the currently connected Proxies + var connectedProxies = self.connectedProxies.slice(0); + + // Set lower bound + var lowerBoundLatency = Number.MAX_VALUE; + + // Determine the lower bound for the Proxies + for (var i = 0; i < connectedProxies.length; i++) { + if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { + lowerBoundLatency = connectedProxies[i].lastIsMasterMS; + } + } + + // Filter out the possible servers + connectedProxies = connectedProxies.filter(function(server) { + if ( + server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS && + server.isConnected() + ) { + return true; + } + }); + + let proxy; + + // We have no connectedProxies pick first of the connected ones + if (connectedProxies.length === 0) { + proxy = self.connectedProxies[0]; + } else { + // Get proxy + proxy = connectedProxies[self.index % connectedProxies.length]; + // Update the index + self.index = (self.index + 1) % connectedProxies.length; + } + + if (transaction && transaction.isActive && proxy && proxy.isConnected()) { + transaction.pinServer(proxy); + } + + // Return the proxy + return proxy; +} + +function moveServerFrom(from, to, proxy) { + for (var i = 0; i < from.length; i++) { + if (from[i].name === proxy.name) { + from.splice(i, 1); + } + } + + for (i = 0; i < to.length; i++) { + if (to[i].name === proxy.name) { + to.splice(i, 1); + } + } + + to.push(proxy); +} + +function removeProxyFrom(from, proxy) { + for (var i = 0; i < from.length; i++) { + if (from[i].name === proxy.name) { + from.splice(i, 1); + } + } +} + +function reconnectProxies(self, proxies, callback) { + // Count lefts + var count = proxies.length; + + // Handle events + var _handleEvent = function(self, event) { + return function() { + var _self = this; + count = count - 1; + + // Destroyed + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + return this.destroy(); + } + + if (event === 'connect') { + // Destroyed + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + return _self.destroy(); + } + + // Remove the handlers + for (var i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + + // Move to the connected servers + moveServerFrom(self.connectingProxies, self.connectedProxies, _self); + // Emit topology Change + emitTopologyDescriptionChanged(self); + // Emit joined event + self.emit('joined', 'mongos', _self); + } else { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + this.destroy(); + } + + // Are we done finish up callback + if (count === 0) { + callback(); + } + }; + }; + + // No new servers + if (count === 0) { + return callback(); + } + + // Execute method + function execute(_server, i) { + setTimeout(function() { + // Destroyed + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + return; + } + + // Create a new server instance + var server = new Server( + Object.assign({}, self.s.options, { + host: _server.name.split(':')[0], + port: parseInt(_server.name.split(':')[1], 10), + reconnect: false, + monitoring: false, + parent: self + }) + ); + + destroyServer(_server, { force: true }); + removeProxyFrom(self.disconnectedProxies, _server); + + // Relay the server description change + relayEvents(server, self, ['serverDescriptionChanged']); + + // Emit opening server event + self.emit('serverOpening', { + topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id, + address: server.name + }); + + // Add temp handlers + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Connect to proxy + self.connectingProxies.push(server); + server.connect(self.s.connectOptions); + }, i); + } + + // Create new instances + for (var i = 0; i < proxies.length; i++) { + execute(proxies[i], i); + } +} + +function topologyMonitor(self, options) { + options = options || {}; + + // no need to set up the monitor if we're already closed + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + return; + } + + // Set momitoring timeout + self.haTimeoutId = setTimeout(function() { + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + return; + } + + // If we have a primary and a disconnect handler, execute + // buffered operations + if (self.isConnected() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } + + // Get the connectingServers + var proxies = self.connectedProxies.slice(0); + // Get the count + var count = proxies.length; + + // If the count is zero schedule a new fast + function pingServer(_self, _server, cb) { + // Measure running time + var start = new Date().getTime(); + + // Emit the server heartbeat start + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); + + // Execute ismaster + _server.command( + 'admin.$cmd', + { + ismaster: true + }, + { + monitoring: true, + socketTimeout: self.s.options.connectionTimeout || 2000 + }, + function(err, r) { + if ( + self.state === DESTROYED || + self.state === DESTROYING || + self.state === UNREFERENCED + ) { + // Move from connectingProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); + _server.destroy(); + return cb(err, r); + } + + // Calculate latency + var latencyMS = new Date().getTime() - start; + + // We had an error, remove it from the state + if (err) { + // Emit the server heartbeat failure + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: _server.name + }); + // Move from connected proxies to disconnected proxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); + } else { + // Update the server ismaster + _server.ismaster = r.result; + _server.lastIsMasterMS = latencyMS; + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: _server.name + }); + } + + cb(err, r); + } + ); + } + + // No proxies initiate monitor again + if (proxies.length === 0) { + // Emit close event if any listeners registered + if (self.listeners('close').length > 0 && self.state === CONNECTING) { + self.emit('error', new MongoError('no mongos proxy available')); + } else { + self.emit('close', self); + } + + // Attempt to connect to any unknown servers + return reconnectProxies(self, self.disconnectedProxies, function() { + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + return; + } + + // Are we connected ? emit connect event + if (self.state === CONNECTING && options.firstConnect) { + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + } else if (self.isConnected()) { + self.emit('reconnect', self); + } else if (!self.isConnected() && self.listeners('close').length > 0) { + self.emit('close', self); + } + + // Perform topology monitor + topologyMonitor(self); + }); + } + + // Ping all servers + for (var i = 0; i < proxies.length; i++) { + pingServer(self, proxies[i], function() { + count = count - 1; + + if (count === 0) { + if ( + self.state === DESTROYED || + self.state === DESTROYING || + self.state === UNREFERENCED + ) { + return; + } + + // Attempt to connect to any unknown servers + reconnectProxies(self, self.disconnectedProxies, function() { + if ( + self.state === DESTROYED || + self.state === DESTROYING || + self.state === UNREFERENCED + ) { + return; + } + + // Perform topology monitor + topologyMonitor(self); + }); + } + }); + } + }, self.s.haInterval); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Mongos.prototype.lastIsMaster = function() { + return this.ismaster; +}; + +/** + * Unref all connections belong to this server + * @method + */ +Mongos.prototype.unref = function() { + // Transition state + stateTransition(this, UNREFERENCED); + // Get all proxies + var proxies = this.connectedProxies.concat(this.connectingProxies); + proxies.forEach(function(x) { + x.unref(); + }); + + clearTimeout(this.haTimeoutId); +}; + +/** + * Destroy the server connection + * @param {boolean} [options.force=false] Force destroy the pool + * @method + */ +Mongos.prototype.destroy = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + + stateTransition(this, DESTROYING); + if (this.haTimeoutId) { + clearTimeout(this.haTimeoutId); + } + + const proxies = this.connectedProxies.concat(this.connectingProxies); + let serverCount = proxies.length; + const serverDestroyed = () => { + serverCount--; + if (serverCount > 0) { + return; + } + + emitTopologyDescriptionChanged(this); + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); + stateTransition(this, DESTROYED); + if (typeof callback === 'function') { + callback(null, null); + } + }; + + if (serverCount === 0) { + serverDestroyed(); + return; + } + + // Destroy all connecting servers + proxies.forEach(server => { + // Emit the sdam event + this.emit('serverClosed', { + topologyId: this.id, + address: server.name + }); + + destroyServer(server, options, serverDestroyed); + moveServerFrom(this.connectedProxies, this.disconnectedProxies, server); + }); +}; + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Mongos.prototype.isConnected = function() { + return this.connectedProxies.length > 0; +}; + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Mongos.prototype.isDestroyed = function() { + return this.state === DESTROYED; +}; + +// +// Operations +// + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO [$5f5fbe42fcabad09c1c241ad]: once we drop Node 4, use destructuring either here or in arguments. + const self = args.self; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + // Pick a server + let server = pickProxy(self, options.session); + // No server found error out + if (!server) return callback(new MongoError('no mongos proxy available')); + + const willRetryWrite = + !args.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction(); + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!legacyIsRetryableWriteError(err, self) || !willRetryWrite) { + err = getMMAPError(err); + return callback(err); + } + + // Pick another server + server = pickProxy(self, options.session); + + // No server found error out with original error + if (!server) { + return callback(err); + } + + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // rerun the operation + server[op](ns, ops, options, handler); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.insert = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.update = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.remove = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); +}; + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; + +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.command = function(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + var self = this; + + // Pick a proxy + var server = pickProxy(self, options.session); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // No server returned we had an error + if (server == null) { + return callback(new MongoError('no mongos proxy available')); + } + + // Cloned options + var clonedOptions = cloneOptions(options); + clonedOptions.topology = self; + + const willRetryWrite = + !options.retrying && + options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!legacyIsRetryableWriteError(err, self)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, clonedOptions, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + clonedOptions.session.incrementTransactionNumber(); + clonedOptions.willRetryWrite = willRetryWrite; + } + + // Execute the command + server.command(ns, cmd, clonedOptions, cb); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +Mongos.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(topology, ns, cmd, options); +}; + +/** + * Selects a server + * + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Unused + * @param {ClientSession} [options.session] Specify a session if it is being used + * @param {function} callback + */ +Mongos.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') + (callback = options), (options = selector), (selector = undefined); + options = options || {}; + + const server = pickProxy(this, options.session); + if (server == null) { + callback(new MongoError('server selection failed')); + return; + } + + if (this.s.debug) this.emit('pickedServer', null, server); + callback(null, server); +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Mongos.prototype.connections = function() { + var connections = []; + + for (var i = 0; i < this.connectedProxies.length; i++) { + connections = connections.concat(this.connectedProxies[i].connections()); + } + + return connections; +}; + +function emitTopologyDescriptionChanged(self) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + var topology = 'Unknown'; + if (self.connectedProxies.length > 0) { + topology = 'Sharded'; + } + + // Generate description + var description = { + topologyType: topology, + servers: [] + }; + + // All proxies + var proxies = self.disconnectedProxies.concat(self.connectingProxies); + + // Add all the disconnected proxies + description.servers = description.servers.concat( + proxies.map(function(x) { + var description = x.getDescription(); + description.type = 'Unknown'; + return description; + }) + ); + + // Add all the connected proxies + description.servers = description.servers.concat( + self.connectedProxies.map(function(x) { + var description = x.getDescription(); + description.type = 'Mongos'; + return description; + }) + ); + + // Get the diff + var diffResult = diff(self.topologyDescription, description); + + // Create the result + var result = { + topologyId: self.id, + previousDescription: self.topologyDescription, + newDescription: description, + diff: diffResult + }; + + // Emit the topologyDescription change + if (diffResult.servers.length > 0) { + self.emit('topologyDescriptionChanged', result); + } + + // Set the new description + self.topologyDescription = description; + } +} + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * A mongos reconnect event, used to verify that the mongos topology has reconnected + * + * @event Mongos#reconnect + * @type {Mongos} + */ + +/** + * A mongos fullsetup event, used to signal that all topology members have been contacted. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * A mongos all event, used to signal that all topology members have been contacted. + * + * @event Mongos#all + * @type {Mongos} + */ + +/** + * A server member left the mongos list + * + * @event Mongos#left + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos list + * + * @event Mongos#joined + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that joined + */ + +/** + * A server opening SDAM monitoring event + * + * @event Mongos#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Mongos#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Mongos#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event Mongos#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event Mongos#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event Mongos#topologyDescriptionChanged + * @type {object} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event Mongos#serverHeartbeatStarted + * @type {object} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event Mongos#serverHeartbeatFailed + * @type {object} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event Mongos#serverHeartbeatSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Mongos#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Mongos#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Mongos#commandFailed + * @type {object} + */ + +module.exports = Mongos; + + +/***/ }), + +/***/ 4485: +/***/ ((module) => { + +"use strict"; + + +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @class + * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param {array} tags The tags object + * @param {object} [options] Additional read preference options + * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds. + * @param {object} [options.hedge] Server mode in which the same query is dispatched in parallel to multiple replica set members. + * @param {boolean} [options.hedge.enabled] Explicitly enable or disable hedged reads. + * @see https://docs.mongodb.com/manual/core/read-preference/ + * @return {ReadPreference} + */ +const ReadPreference = function(mode, tags, options) { + if (!ReadPreference.isValid(mode)) { + throw new TypeError(`Invalid read preference mode ${mode}`); + } + + // TODO(major): tags MUST be an array of tagsets + if (tags && !Array.isArray(tags)) { + console.warn( + 'ReadPreference tags must be an array, this will change in the next major version' + ); + + const tagsHasMaxStalenessSeconds = typeof tags.maxStalenessSeconds !== 'undefined'; + const tagsHasHedge = typeof tags.hedge !== 'undefined'; + const tagsHasOptions = tagsHasMaxStalenessSeconds || tagsHasHedge; + if (tagsHasOptions) { + // this is likely an options object + options = tags; + tags = undefined; + } else { + tags = [tags]; + } + } + + this.mode = mode; + this.tags = tags; + this.hedge = options && options.hedge; + + options = options || {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new TypeError('maxStalenessSeconds must be a positive integer'); + } + + this.maxStalenessSeconds = options.maxStalenessSeconds; + + // NOTE: The minimum required wire version is 5 for this read preference. If the existing + // topology has a lower value then a MongoError will be thrown during server selection. + this.minWireVersion = 5; + } + + if (this.mode === ReadPreference.PRIMARY) { + if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { + throw new TypeError('Primary read preference cannot be combined with tags'); + } + + if (this.maxStalenessSeconds) { + throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds'); + } + + if (this.hedge) { + throw new TypeError('Primary read preference cannot be combined with hedge'); + } + } +}; + +// Support the deprecated `preference` property introduced in the porcelain layer +Object.defineProperty(ReadPreference.prototype, 'preference', { + enumerable: true, + get: function() { + return this.mode; + } +}); + +/* + * Read preference mode constants + */ +ReadPreference.PRIMARY = 'primary'; +ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; +ReadPreference.SECONDARY = 'secondary'; +ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; +ReadPreference.NEAREST = 'nearest'; + +const VALID_MODES = [ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + null +]; + +/** + * Construct a ReadPreference given an options object. + * + * @param {object} options The options object from which to extract the read preference. + * @return {ReadPreference} + */ +ReadPreference.fromOptions = function(options) { + if (!options) return null; + const readPreference = options.readPreference; + if (!readPreference) return null; + const readPreferenceTags = options.readPreferenceTags; + const maxStalenessSeconds = options.maxStalenessSeconds; + if (typeof readPreference === 'string') { + return new ReadPreference(readPreference, readPreferenceTags); + } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === 'string') { + return new ReadPreference(mode, readPreference.tags, { + maxStalenessSeconds: readPreference.maxStalenessSeconds || maxStalenessSeconds, + hedge: readPreference.hedge + }); + } + } + + return readPreference; +}; + +/** + * Resolves a read preference based on well-defined inheritance rules. This method will not only + * determine the read preference (if there is one), but will also ensure the returned value is a + * properly constructed instance of `ReadPreference`. + * + * @param {Collection|Db|MongoClient} parent The parent of the operation on which to determine the read + * preference, used for determining the inherited read preference. + * @param {object} options The options passed into the method, potentially containing a read preference + * @returns {(ReadPreference|null)} The resolved read preference + */ +ReadPreference.resolve = function(parent, options) { + options = options || {}; + const session = options.session; + + const inheritedReadPreference = parent && parent.readPreference; + + let readPreference; + if (options.readPreference) { + readPreference = ReadPreference.fromOptions(options); + } else if (session && session.inTransaction() && session.transaction.options.readPreference) { + // The transaction’s read preference MUST override all other user configurable read preferences. + readPreference = session.transaction.options.readPreference; + } else if (inheritedReadPreference != null) { + readPreference = inheritedReadPreference; + } else { + readPreference = ReadPreference.primary; + } + + return typeof readPreference === 'string' ? new ReadPreference(readPreference) : readPreference; +}; + +/** + * Replaces options.readPreference with a ReadPreference instance + */ +ReadPreference.translate = function(options) { + if (options.readPreference == null) return options; + const r = options.readPreference; + + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r); + } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } else if (!(r instanceof ReadPreference)) { + throw new TypeError('Invalid read preference: ' + r); + } + + return options; +}; + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} True if a mode is valid + */ +ReadPreference.isValid = function(mode) { + return VALID_MODES.indexOf(mode) !== -1; +}; + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} True if a mode is valid + */ +ReadPreference.prototype.isValid = function(mode) { + return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); +}; + +const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; + +/** + * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire + * @method + * @return {boolean} + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ +ReadPreference.prototype.slaveOk = function() { + return needSlaveOk.indexOf(this.mode) !== -1; +}; + +/** + * Are the two read preference equal + * @method + * @param {ReadPreference} readPreference The read preference with which to check equality + * @return {boolean} True if the two ReadPreferences are equivalent + */ +ReadPreference.prototype.equals = function(readPreference) { + return readPreference.mode === this.mode; +}; + +/** + * Return JSON representation + * @method + * @return {Object} A JSON representation of the ReadPreference + */ +ReadPreference.prototype.toJSON = function() { + const readPreference = { mode: this.mode }; + if (Array.isArray(this.tags)) readPreference.tags = this.tags; + if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + if (this.hedge) readPreference.hedge = this.hedge; + return readPreference; +}; + +/** + * Primary read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.primary = new ReadPreference('primary'); +/** + * Primary Preferred read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); +/** + * Secondary read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.secondary = new ReadPreference('secondary'); +/** + * Secondary Preferred read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); +/** + * Nearest read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.nearest = new ReadPreference('nearest'); + +module.exports = ReadPreference; + + +/***/ }), + +/***/ 1134: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const inherits = __webpack_require__(1669).inherits; +const f = __webpack_require__(1669).format; +const EventEmitter = __webpack_require__(8614).EventEmitter; +const ReadPreference = __webpack_require__(4485); +const CoreCursor = __webpack_require__(4847).CoreCursor; +const retrieveBSON = __webpack_require__(7746).retrieveBSON; +const Logger = __webpack_require__(104); +const MongoError = __webpack_require__(3111).MongoError; +const Server = __webpack_require__(6495); +const ReplSetState = __webpack_require__(8742); +const Timeout = __webpack_require__(2306).Timeout; +const Interval = __webpack_require__(2306).Interval; +const SessionMixins = __webpack_require__(2306).SessionMixins; +const isRetryableWritesSupported = __webpack_require__(2306).isRetryableWritesSupported; +const relayEvents = __webpack_require__(1178).relayEvents; +const BSON = retrieveBSON(); +const getMMAPError = __webpack_require__(2306).getMMAPError; +const makeClientMetadata = __webpack_require__(1178).makeClientMetadata; +const legacyIsRetryableWriteError = __webpack_require__(2306).legacyIsRetryableWriteError; +const now = __webpack_require__(1371).now; +const calculateDurationInMs = __webpack_require__(1371).calculateDurationInMs; + +// +// States +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var UNREFERENCED = 'unreferenced'; +var DESTROYED = 'destroyed'; + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYED, DISCONNECTED], + connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], + unreferenced: [UNREFERENCED, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.state = newState; + } else { + self.s.logger.error( + f( + 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +// +// ReplSet instance id +var id = 1; +var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; + +/** + * Creates a new Replset instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {boolean} options.setName The Replicaset set name + * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {ReplSet} A cursor instance + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#failed + * @fires ReplSet#fullsetup + * @fires ReplSet#all + * @fires ReplSet#error + * @fires ReplSet#serverHeartbeatStarted + * @fires ReplSet#serverHeartbeatSucceeded + * @fires ReplSet#serverHeartbeatFailed + * @fires ReplSet#topologyOpening + * @fires ReplSet#topologyClosed + * @fires ReplSet#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var ReplSet = function(seedlist, options) { + var self = this; + options = options || {}; + + // Validate seedlist + if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array'); + // Validate list + if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry'); + // Validate entries + seedlist.forEach(function(e) { + if (typeof e.host !== 'string' || typeof e.port !== 'number') + throw new MongoError('seedlist entry must contain a host and port'); + }); + + // Add event listener + EventEmitter.call(this); + + // Get replSet Id + this.id = id++; + + // Get the localThresholdMS + var localThresholdMS = options.localThresholdMS || 15; + // Backward compatibility + if (options.acceptableLatency) localThresholdMS = options.acceptableLatency; + + // Create a logger + var logger = Logger('ReplSet', options); + + // Internal state + this.s = { + options: Object.assign({ metadata: makeClientMetadata(options) }, options), + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Factory overrides + Cursor: options.cursorFactory || CoreCursor, + // Logger instance + logger: logger, + // Seedlist + seedlist: seedlist, + // Replicaset state + replicaSetState: new ReplSetState({ + id: this.id, + setName: options.setName, + acceptableLatency: localThresholdMS, + heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, + logger: logger + }), + // Current servers we are connecting to + connectingServers: [], + // Ha interval + haInterval: options.haInterval ? options.haInterval : 10000, + // Minimum heartbeat frequency used if we detect a server close + minHeartbeatFrequencyMS: 500, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Server selection index + index: 0, + // Connect function options passed in + connectOptions: {}, + // Are we running in debug mode + debug: typeof options.debug === 'boolean' ? options.debug : false + }; + + // Add handler for topology change + this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { + self.emit('topologyDescriptionChanged', r); + }); + + // Log info warning if the socketTimeout < haInterval as it will cause + // a lot of recycled connections to happen. + if ( + this.s.logger.isWarn() && + this.s.options.socketTimeout !== 0 && + this.s.options.socketTimeout < this.s.haInterval + ) { + this.s.logger.warn( + f( + 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', + this.s.options.socketTimeout, + this.s.haInterval + ) + ); + } + + // Add forwarding of events from state handler + var types = ['joined', 'left']; + types.forEach(function(x) { + self.s.replicaSetState.on(x, function(t, s) { + self.emit(x, t, s); + }); + }); + + // Connect stat + this.initialConnectState = { + connect: false, + fullsetup: false, + all: false + }; + + // Disconnected state + this.state = DISCONNECTED; + this.haTimeoutId = null; + // Last ismaster + this.ismaster = null; + // Contains the intervalId + this.intervalIds = []; + + // Highest clusterTime seen in responses from the current deployment + this.clusterTime = null; +}; + +inherits(ReplSet, EventEmitter); +Object.assign(ReplSet.prototype, SessionMixins); + +Object.defineProperty(ReplSet.prototype, 'type', { + enumerable: true, + get: function() { + return 'replset'; + } +}); + +Object.defineProperty(ReplSet.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + return this.s.replicaSetState.logicalSessionTimeoutMinutes || null; + } +}); + +function rexecuteOperations(self) { + // If we have a primary and a disconnect handler, execute + // buffered operations + if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executePrimary: true }); + } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executeSecondary: true }); + } +} + +function connectNewServers(self, servers, callback) { + // No new servers + if (servers.length === 0) { + return callback(); + } + + // Count lefts + var count = servers.length; + var error = null; + + function done() { + count = count - 1; + if (count === 0) { + callback(error); + } + } + + // Handle events + var _handleEvent = function(self, event) { + return function(err) { + var _self = this; + + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + this.destroy({ force: true }); + return done(); + } + + if (event === 'connect') { + // Update the state + var result = self.s.replicaSetState.update(_self); + // Update the state with the new server + if (result) { + // Primary lastIsMaster store it + if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) { + self.ismaster = _self.lastIsMaster(); + } + + // Remove the handlers + for (let i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + + // Enalbe the monitoring of the new server + monitorServer(_self.lastIsMaster().me, self, {}); + + // Rexecute any stalled operation + rexecuteOperations(self); + } else { + _self.destroy({ force: true }); + } + } else if (event === 'error') { + error = err; + } + + // Rexecute any stalled operation + rexecuteOperations(self); + done(); + }; + }; + + // Execute method + function execute(_server, i) { + setTimeout(function() { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + // remove existing connecting server if it's failed to connect, otherwise + // wait for that server to connect + const existingServerIdx = self.s.connectingServers.findIndex(s => s.name === _server); + if (existingServerIdx >= 0) { + const connectingServer = self.s.connectingServers[existingServerIdx]; + connectingServer.destroy({ force: true }); + + self.s.connectingServers.splice(existingServerIdx, 1); + return done(); + } + + // Create a new server instance + var server = new Server( + Object.assign({}, self.s.options, { + host: _server.split(':')[0], + port: parseInt(_server.split(':')[1], 10), + reconnect: false, + monitoring: false, + parent: self + }) + ); + + // Add temp handlers + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // SDAM Monitoring events + server.on('serverOpening', e => self.emit('serverOpening', e)); + server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); + server.on('serverClosed', e => self.emit('serverClosed', e)); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + self.s.connectingServers.push(server); + server.connect(self.s.connectOptions); + }, i); + } + + // Create new instances + for (var i = 0; i < servers.length; i++) { + execute(servers[i], i); + } +} + +// Ping the server +var pingServer = function(self, server, cb) { + // Measure running time + var start = new Date().getTime(); + + // Emit the server heartbeat start + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); + + // Execute ismaster + // Set the socketTimeout for a monitoring message to a low number + // Ensuring ismaster calls are timed out quickly + server.command( + 'admin.$cmd', + { + ismaster: true + }, + { + monitoring: true, + socketTimeout: self.s.options.connectionTimeout || 2000 + }, + function(err, r) { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + server.destroy({ force: true }); + return cb(err, r); + } + + // Calculate latency + var latencyMS = new Date().getTime() - start; + + // Set the last updatedTime + server.lastUpdateTime = now(); + + // We had an error, remove it from the state + if (err) { + // Emit the server heartbeat failure + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: server.name + }); + + // Remove server from the state + self.s.replicaSetState.remove(server); + } else { + // Update the server ismaster + server.ismaster = r.result; + + // Check if we have a lastWriteDate convert it to MS + // and store on the server instance for later use + if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { + server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); + } + + // Do we have a brand new server + if (server.lastIsMasterMS === -1) { + server.lastIsMasterMS = latencyMS; + } else if (server.lastIsMasterMS) { + // After the first measurement, average RTT MUST be computed using an + // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. + // If the prior average is denoted old_rtt, then the new average (new_rtt) is + // computed from a new RTT measurement (x) using the following formula: + // alpha = 0.2 + // new_rtt = alpha * x + (1 - alpha) * old_rtt + server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; + } + + if (self.s.replicaSetState.update(server)) { + // Primary lastIsMaster store it + if (server.lastIsMaster() && server.lastIsMaster().ismaster) { + self.ismaster = server.lastIsMaster(); + } + } + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: server.name + }); + } + + // Calculate the staleness for this server + self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); + + // Callback + cb(err, r); + } + ); +}; + +// Each server is monitored in parallel in their own timeout loop +var monitorServer = function(host, self, options) { + // If this is not the initial scan + // Is this server already being monitoried, then skip monitoring + if (!options.haInterval) { + for (var i = 0; i < self.intervalIds.length; i++) { + if (self.intervalIds[i].__host === host) { + return; + } + } + } + + // Get the haInterval + var _process = options.haInterval ? Timeout : Interval; + var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; + + // Create the interval + var intervalId = new _process(function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + // clearInterval(intervalId); + intervalId.stop(); + return; + } + + // Do we already have server connection available for this host + var _server = self.s.replicaSetState.get(host); + + // Check if we have a known server connection and reuse + if (_server) { + // Ping the server + return pingServer(self, _server, function(err) { + if (err) { + // NOTE: should something happen here? + return; + } + + if (self.state === DESTROYED || self.state === UNREFERENCED) { + intervalId.stop(); + return; + } + + // Filter out all called intervaliIds + self.intervalIds = self.intervalIds.filter(function(intervalId) { + return intervalId.isRunning(); + }); + + // Initial sweep + if (_process === Timeout) { + if ( + self.state === CONNECTING && + ((self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed) || + self.s.replicaSetState.hasPrimary()) + ) { + self.state = CONNECTED; + + // Emit connected sign + process.nextTick(function() { + self.emit('connect', self); + }); + + // Start topology interval check + topologyMonitor(self, {}); + } + } else { + if ( + self.state === DISCONNECTED && + ((self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed) || + self.s.replicaSetState.hasPrimary()) + ) { + self.state = CONNECTED; + + // Rexecute any stalled operation + rexecuteOperations(self); + + // Emit connected sign + process.nextTick(function() { + self.emit('reconnect', self); + }); + } + } + + if ( + self.initialConnectState.connect && + !self.initialConnectState.fullsetup && + self.s.replicaSetState.hasPrimaryAndSecondary() + ) { + // Set initial connect state + self.initialConnectState.fullsetup = true; + self.initialConnectState.all = true; + + process.nextTick(function() { + self.emit('fullsetup', self); + self.emit('all', self); + }); + } + }); + } + }, _haInterval); + + // Start the interval + intervalId.start(); + // Add the intervalId host name + intervalId.__host = host; + // Add the intervalId to our list of intervalIds + self.intervalIds.push(intervalId); +}; + +function topologyMonitor(self, options) { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + options = options || {}; + + // Get the servers + var servers = Object.keys(self.s.replicaSetState.set); + + // Get the haInterval + var _process = options.haInterval ? Timeout : Interval; + var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; + + if (_process === Timeout) { + return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { + // Don't emit errors if the connection was already + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { + if (err) { + return self.emit('error', err); + } + + self.emit( + 'error', + new MongoError('no primary found in replicaset or invalid replica set name') + ); + return self.destroy({ force: true }); + } else if ( + !self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed + ) { + if (err) { + return self.emit('error', err); + } + + self.emit( + 'error', + new MongoError('no secondary found in replicaset or invalid replica set name') + ); + return self.destroy({ force: true }); + } + + for (var i = 0; i < servers.length; i++) { + monitorServer(servers[i], self, options); + } + }); + } else { + for (var i = 0; i < servers.length; i++) { + monitorServer(servers[i], self, options); + } + } + + // Run the reconnect process + function executeReconnect(self) { + return function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + connectNewServers(self, self.s.replicaSetState.unknownServers, function() { + var monitoringFrequencey = self.s.replicaSetState.hasPrimary() + ? _haInterval + : self.s.minHeartbeatFrequencyMS; + + // Create a timeout + self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); + }); + }; + } + + // Decide what kind of interval to use + var intervalTime = !self.s.replicaSetState.hasPrimary() + ? self.s.minHeartbeatFrequencyMS + : _haInterval; + + self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); +} + +function addServerToList(list, server) { + for (var i = 0; i < list.length; i++) { + if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true; + } + + list.push(server); +} + +function handleEvent(self, event) { + return function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id) + ); + } + + // Remove from the replicaset state + self.s.replicaSetState.remove(this); + + // Are we in a destroyed state return + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + + // If no primary and secondary available + if ( + !self.s.replicaSetState.hasPrimary() && + !self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed + ) { + stateTransition(self, DISCONNECTED); + } else if (!self.s.replicaSetState.hasPrimary()) { + stateTransition(self, DISCONNECTED); + } + + addServerToList(self.s.connectingServers, this); + }; +} + +function shouldTriggerConnect(self) { + const isConnecting = self.state === CONNECTING; + const hasPrimary = self.s.replicaSetState.hasPrimary(); + const hasSecondary = self.s.replicaSetState.hasSecondary(); + const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed; + const readPreferenceSecondary = + self.s.connectOptions.readPreference && + self.s.connectOptions.readPreference.equals(ReadPreference.secondary); + + return ( + (isConnecting && + ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) || + (hasSecondary && secondaryOnlyConnectionAllowed) + ); +} + +function handleInitialConnectEvent(self, event) { + return function() { + var _this = this; + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f( + 'handleInitialConnectEvent %s from server %s in replset with id %s', + event, + this.name, + self.id + ) + ); + } + + // Destroy the instance + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return this.destroy({ force: true }); + } + + // Check the type of server + if (event === 'connect') { + // Update the state + var result = self.s.replicaSetState.update(_this); + if (result === true) { + // Primary lastIsMaster store it + if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) { + self.ismaster = _this.lastIsMaster(); + } + + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f( + 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', + event, + _this.name, + self.id, + JSON.stringify(self.s.replicaSetState.set) + ) + ); + } + + // Remove the handlers + for (let i = 0; i < handlers.length; i++) { + _this.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _this.on('error', handleEvent(self, 'error')); + _this.on('close', handleEvent(self, 'close')); + _this.on('timeout', handleEvent(self, 'timeout')); + _this.on('parseError', handleEvent(self, 'parseError')); + + // Do we have a primary or primaryAndSecondary + if (shouldTriggerConnect(self)) { + // We are connected + self.state = CONNECTED; + + // Set initial connect state + self.initialConnectState.connect = true; + // Emit connect event + process.nextTick(function() { + self.emit('connect', self); + }); + + topologyMonitor(self, {}); + } + } else if (result instanceof MongoError) { + _this.destroy({ force: true }); + self.destroy({ force: true }); + return self.emit('error', result); + } else { + _this.destroy({ force: true }); + } + } else { + // Emit failure to connect + self.emit('failed', this); + + addServerToList(self.s.connectingServers, this); + // Remove from the state + self.s.replicaSetState.remove(this); + } + + if ( + self.initialConnectState.connect && + !self.initialConnectState.fullsetup && + self.s.replicaSetState.hasPrimaryAndSecondary() + ) { + // Set initial connect state + self.initialConnectState.fullsetup = true; + self.initialConnectState.all = true; + + process.nextTick(function() { + self.emit('fullsetup', self); + self.emit('all', self); + }); + } + + // Remove from the list from connectingServers + for (var i = 0; i < self.s.connectingServers.length; i++) { + if (self.s.connectingServers[i].equals(this)) { + self.s.connectingServers.splice(i, 1); + } + } + + // Trigger topologyMonitor + if (self.s.connectingServers.length === 0 && self.state === CONNECTING) { + topologyMonitor(self, { haInterval: 1 }); + } + }; +} + +function connectServers(self, servers) { + // Update connectingServers + self.s.connectingServers = self.s.connectingServers.concat(servers); + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + // Add the server to the state + if (self.s.replicaSetState.update(server)) { + // Primary lastIsMaster store it + if (server.lastIsMaster() && server.lastIsMaster().ismaster) { + self.ismaster = server.lastIsMaster(); + } + } + + // Add event handlers + server.once('close', handleInitialConnectEvent(self, 'close')); + server.once('timeout', handleInitialConnectEvent(self, 'timeout')); + server.once('parseError', handleInitialConnectEvent(self, 'parseError')); + server.once('error', handleInitialConnectEvent(self, 'error')); + server.once('connect', handleInitialConnectEvent(self, 'connect')); + + // SDAM Monitoring events + server.on('serverOpening', e => self.emit('serverOpening', e)); + server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); + server.on('serverClosed', e => self.emit('serverClosed', e)); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Start connection + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + + // Start all the servers + while (servers.length > 0) { + connect(servers.shift(), timeoutInterval++); + } +} + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +/** + * Initiate server connect + */ +ReplSet.prototype.connect = function(options) { + var self = this; + // Add any connect level options to the internal state + this.s.connectOptions = options || {}; + + // Set connecting state + stateTransition(this, CONNECTING); + + // Create server instances + var servers = this.s.seedlist.map(function(x) { + return new Server( + Object.assign({}, self.s.options, x, options, { + reconnect: false, + monitoring: false, + parent: self + }) + ); + }); + + // Error out as high availbility interval must be < than socketTimeout + if ( + this.s.options.socketTimeout > 0 && + this.s.options.socketTimeout <= this.s.options.haInterval + ) { + return self.emit( + 'error', + new MongoError( + f( + 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS', + this.s.options.haInterval, + this.s.options.socketTimeout + ) + ) + ); + } + + // Emit the topology opening event + emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); + // Start all server connections + connectServers(self, servers); +}; + +/** + * Authenticate the topology. + * @method + * @param {MongoCredentials} credentials The credentials for authentication we are using + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.auth = function(credentials, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +/** + * Destroy the server connection + * @param {boolean} [options.force=false] Force destroy the pool + * @method + */ +ReplSet.prototype.destroy = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + + let destroyCount = this.s.connectingServers.length + 1; // +1 for the callback from `replicaSetState.destroy` + const serverDestroyed = () => { + destroyCount--; + if (destroyCount > 0) { + return; + } + + // Emit toplogy closing event + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); + + // Transition state + stateTransition(this, DESTROYED); + + if (typeof callback === 'function') { + callback(null, null); + } + }; + + // Clear out any monitoring process + if (this.haTimeoutId) clearTimeout(this.haTimeoutId); + + // Clear out all monitoring + for (var i = 0; i < this.intervalIds.length; i++) { + this.intervalIds[i].stop(); + } + + // Reset list of intervalIds + this.intervalIds = []; + + if (destroyCount === 0) { + serverDestroyed(); + return; + } + + // Destroy the replicaset + this.s.replicaSetState.destroy(options, serverDestroyed); + + // Destroy all connecting servers + this.s.connectingServers.forEach(function(x) { + x.destroy(options, serverDestroyed); + }); +}; + +/** + * Unref all connections belong to this server + * @method + */ +ReplSet.prototype.unref = function() { + // Transition state + stateTransition(this, UNREFERENCED); + + this.s.replicaSetState.allServers().forEach(function(x) { + x.unref(); + }); + + clearTimeout(this.haTimeoutId); +}; + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +ReplSet.prototype.lastIsMaster = function() { + // If secondaryOnlyConnectionAllowed and no primary but secondary + // return the secondaries ismaster result. + if ( + this.s.options.secondaryOnlyConnectionAllowed && + !this.s.replicaSetState.hasPrimary() && + this.s.replicaSetState.hasSecondary() + ) { + return this.s.replicaSetState.secondaries[0].lastIsMaster(); + } + + return this.s.replicaSetState.primary + ? this.s.replicaSetState.primary.lastIsMaster() + : this.ismaster; +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +ReplSet.prototype.connections = function() { + var servers = this.s.replicaSetState.allServers(); + var connections = []; + for (var i = 0; i < servers.length; i++) { + connections = connections.concat(servers[i].connections()); + } + + return connections; +}; + +/** + * Figure out if the server is connected + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {boolean} + */ +ReplSet.prototype.isConnected = function(options) { + options = options || {}; + + // If we specified a read preference check if we are connected to something + // than can satisfy this + if (options.readPreference && options.readPreference.equals(ReadPreference.secondary)) { + return this.s.replicaSetState.hasSecondary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) { + return this.s.replicaSetState.hasPrimary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) { + return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) { + return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); + } + + if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) { + return true; + } + + return this.s.replicaSetState.hasPrimary(); +}; + +/** + * Figure out if the replicaset instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +ReplSet.prototype.isDestroyed = function() { + return this.state === DESTROYED; +}; + +const SERVER_SELECTION_TIMEOUT_MS = 10000; // hardcoded `serverSelectionTimeoutMS` for legacy topology +const SERVER_SELECTION_INTERVAL_MS = 1000; // time to wait between selection attempts +/** + * Selects a server + * + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {ClientSession} [options.session] Unused + * @param {function} callback + */ +ReplSet.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') (callback = options), (options = selector); + options = options || {}; + + let readPreference; + if (selector instanceof ReadPreference) { + readPreference = selector; + } else { + readPreference = options.readPreference || ReadPreference.primary; + } + + let lastError; + const start = now(); + const _selectServer = () => { + if (calculateDurationInMs(start) >= SERVER_SELECTION_TIMEOUT_MS) { + if (lastError != null) { + callback(lastError, null); + } else { + callback(new MongoError('Server selection timed out')); + } + + return; + } + + const server = this.s.replicaSetState.pickServer(readPreference); + if (server == null) { + setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); + return; + } + + if (!(server instanceof Server)) { + lastError = server; + setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); + return; + } + + if (this.s.debug) this.emit('pickedServer', options.readPreference, server); + callback(null, server); + }; + + _selectServer(); +}; + +/** + * Get all connected servers + * @method + * @return {Server[]} + */ +ReplSet.prototype.getServers = function() { + return this.s.replicaSetState.allServers(); +}; + +// +// Execute write operation +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO [$5f5fbe42fcabad09c1c241ae]: once we drop Node 4, use destructuring either here or in arguments. + const self = args.self; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + if (self.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + const willRetryWrite = + !args.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction(); + + if (!self.s.replicaSetState.hasPrimary()) { + if (self.s.disconnectHandler) { + // Not connected but we have a disconnecthandler + return self.s.disconnectHandler.add(op, ns, ops, options, callback); + } else if (!willRetryWrite) { + // No server returned we had an error + return callback(new MongoError('no primary server found')); + } + } + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!legacyIsRetryableWriteError(err, self)) { + err = getMMAPError(err); + return callback(err); + } + + if (willRetryWrite) { + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + } + + // Per SDAM, remove primary from replicaset + if (self.s.replicaSetState.primary) { + self.s.replicaSetState.primary.destroy(); + self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); + } + + return callback(err); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + self.s.replicaSetState.primary[op](ns, ops, options, handler); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.insert = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.update = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.remove = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); +}; + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; + +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.command = function(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Establish readPreference + var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; + + // If the readPreference is primary and we have no primary, store it + if ( + readPreference.preference === 'primary' && + !this.s.replicaSetState.hasPrimary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } else if ( + readPreference.preference === 'secondary' && + !this.s.replicaSetState.hasSecondary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } else if ( + readPreference.preference !== 'primary' && + !this.s.replicaSetState.hasSecondary() && + !this.s.replicaSetState.hasPrimary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // Pick a server + var server = this.s.replicaSetState.pickServer(readPreference); + // We received an error, return it + if (!(server instanceof Server)) return callback(server); + // Emit debug event + if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); + + // No server returned we had an error + if (server == null) { + return callback( + new MongoError( + f('no server found that matches the provided readPreference %s', readPreference) + ) + ); + } + + const willRetryWrite = + !options.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!legacyIsRetryableWriteError(err, self)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, options, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + // Per SDAM, remove primary from replicaset + if (this.s.replicaSetState.primary) { + this.s.replicaSetState.primary.destroy(); + this.s.replicaSetState.remove(this.s.replicaSetState.primary, { force: true }); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // Execute the command + server.command(ns, cmd, options, cb); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +ReplSet.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(topology, ns, cmd, options); +}; + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * A replset reconnect event, used to verify that the topology reconnected + * + * @event ReplSet#reconnect + * @type {ReplSet} + */ + +/** + * A replset fullsetup event, used to signal that all topology members have been contacted. + * + * @event ReplSet#fullsetup + * @type {ReplSet} + */ + +/** + * A replset all event, used to signal that all topology members have been contacted. + * + * @event ReplSet#all + * @type {ReplSet} + */ + +/** + * A replset failed event, used to signal that initial replset connection failed. + * + * @event ReplSet#failed + * @type {ReplSet} + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * A server opening SDAM monitoring event + * + * @event ReplSet#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event ReplSet#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event ReplSet#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event ReplSet#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event ReplSet#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event ReplSet#topologyDescriptionChanged + * @type {object} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event ReplSet#serverHeartbeatStarted + * @type {object} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event ReplSet#serverHeartbeatFailed + * @type {object} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event ReplSet#serverHeartbeatSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event ReplSet#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event ReplSet#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event ReplSet#commandFailed + * @type {object} + */ + +module.exports = ReplSet; + + +/***/ }), + +/***/ 8742: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var inherits = __webpack_require__(1669).inherits, + f = __webpack_require__(1669).format, + diff = __webpack_require__(2306).diff, + EventEmitter = __webpack_require__(8614).EventEmitter, + Logger = __webpack_require__(104), + ReadPreference = __webpack_require__(4485), + MongoError = __webpack_require__(3111).MongoError, + Buffer = __webpack_require__(1867).Buffer; + +var TopologyType = { + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown' +}; + +var ServerType = { + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown' +}; + +var ReplSetState = function(options) { + options = options || {}; + // Add event listener + EventEmitter.call(this); + // Topology state + this.topologyType = TopologyType.ReplicaSetNoPrimary; + this.setName = options.setName; + + // Server set + this.set = {}; + + // Unpacked options + this.id = options.id; + this.setName = options.setName; + + // Replicaset logger + this.logger = options.logger || Logger('ReplSet', options); + + // Server selection index + this.index = 0; + // Acceptable latency + this.acceptableLatency = options.acceptableLatency || 15; + + // heartbeatFrequencyMS + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + + // Server side + this.primary = null; + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.ghosts = []; + // Current unknown hosts + this.unknownServers = []; + // In set status + this.set = {}; + // Status + this.maxElectionId = null; + this.maxSetVersion = 0; + // Description of the Replicaset + this.replicasetDescription = { + topologyType: 'Unknown', + servers: [] + }; + + this.logicalSessionTimeoutMinutes = undefined; +}; + +inherits(ReplSetState, EventEmitter); + +ReplSetState.prototype.hasPrimaryAndSecondary = function() { + return this.primary != null && this.secondaries.length > 0; +}; + +ReplSetState.prototype.hasPrimaryOrSecondary = function() { + return this.hasPrimary() || this.hasSecondary(); +}; + +ReplSetState.prototype.hasPrimary = function() { + return this.primary != null; +}; + +ReplSetState.prototype.hasSecondary = function() { + return this.secondaries.length > 0; +}; + +ReplSetState.prototype.get = function(host) { + var servers = this.allServers(); + + for (var i = 0; i < servers.length; i++) { + if (servers[i].name.toLowerCase() === host.toLowerCase()) { + return servers[i]; + } + } + + return null; +}; + +ReplSetState.prototype.allServers = function(options) { + options = options || {}; + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + if (!options.ignoreArbiters) servers = servers.concat(this.arbiters); + servers = servers.concat(this.passives); + return servers; +}; + +ReplSetState.prototype.destroy = function(options, callback) { + const serversToDestroy = this.secondaries + .concat(this.arbiters) + .concat(this.passives) + .concat(this.ghosts); + if (this.primary) serversToDestroy.push(this.primary); + + let serverCount = serversToDestroy.length; + const serverDestroyed = () => { + serverCount--; + if (serverCount > 0) { + return; + } + + // Clear out the complete state + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.ghosts = []; + this.unknownServers = []; + this.set = {}; + this.primary = null; + + // Emit the topology changed + emitTopologyDescriptionChanged(this); + + if (typeof callback === 'function') { + callback(null, null); + } + }; + + if (serverCount === 0) { + serverDestroyed(); + return; + } + + serversToDestroy.forEach(server => server.destroy(options, serverDestroyed)); +}; + +ReplSetState.prototype.remove = function(server, options) { + options = options || {}; + + // Get the server name and lowerCase it + var serverName = server.name.toLowerCase(); + + // Only remove if the current server is not connected + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + servers = servers.concat(this.arbiters); + servers = servers.concat(this.passives); + + // Check if it's active and this is just a failed connection attempt + for (var i = 0; i < servers.length; i++) { + if ( + !options.force && + servers[i].equals(server) && + servers[i].isConnected && + servers[i].isConnected() + ) { + return; + } + } + + // If we have it in the set remove it + if (this.set[serverName]) { + this.set[serverName].type = ServerType.Unknown; + this.set[serverName].electionId = null; + this.set[serverName].setName = null; + this.set[serverName].setVersion = null; + } + + // Remove type + var removeType = null; + + // Remove from any lists + if (this.primary && this.primary.equals(server)) { + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + removeType = 'primary'; + } + + // Remove from any other server lists + removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; + removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; + removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; + removeFrom(server, this.ghosts); + removeFrom(server, this.unknownServers); + + // Push to unknownServers + this.unknownServers.push(serverName); + + // Do we have a removeType + if (removeType) { + this.emit('left', removeType, server); + } +}; + +const isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName; + +ReplSetState.prototype.update = function(server) { + var self = this; + // Get the current ismaster + var ismaster = server.lastIsMaster(); + + // Get the server name and lowerCase it + var serverName = server.name.toLowerCase(); + + // + // Add any hosts + // + if (ismaster) { + // Join all the possible new hosts + var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; + hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); + hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); + hosts = hosts.map(function(s) { + return s.toLowerCase(); + }); + + // Add all hosts as unknownServers + for (var i = 0; i < hosts.length; i++) { + // Add to the list of unknown server + if ( + this.unknownServers.indexOf(hosts[i]) === -1 && + (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown) + ) { + this.unknownServers.push(hosts[i].toLowerCase()); + } + + if (!this.set[hosts[i]]) { + this.set[hosts[i]] = { + type: ServerType.Unknown, + electionId: null, + setName: null, + setVersion: null + }; + } + } + } + + // + // Unknown server + // + if (!ismaster && !inList(ismaster, server, this.unknownServers)) { + self.set[serverName] = { + type: ServerType.Unknown, + setVersion: null, + electionId: null, + setName: null + }; + // Update set information about the server instance + self.set[serverName].type = ServerType.Unknown; + self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; + self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; + self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; + + if (self.unknownServers.indexOf(server.name) === -1) { + self.unknownServers.push(serverName); + } + + // Set the topology + return false; + } + + // Update logicalSessionTimeoutMinutes + if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) { + if ( + self.logicalSessionTimeoutMinutes === undefined || + ismaster.logicalSessionTimeoutMinutes === null + ) { + self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; + } else { + self.logicalSessionTimeoutMinutes = Math.min( + self.logicalSessionTimeoutMinutes, + ismaster.logicalSessionTimeoutMinutes + ); + } + } + + // + // Is this a mongos + // + if (ismaster && ismaster.msg === 'isdbgrid') { + if (this.primary && this.primary.name === serverName) { + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + return false; + } + + // A RSGhost instance + if (ismaster.isreplicaset) { + self.set[serverName] = { + type: ServerType.RSGhost, + setVersion: null, + electionId: null, + setName: ismaster.setName + }; + + if (this.primary && this.primary.name === serverName) { + this.primary = null; + } + + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + + // Set the topology + return false; + } + + // A RSOther instance + if ( + (ismaster.setName && ismaster.hidden) || + (ismaster.setName && + !ismaster.ismaster && + !ismaster.secondary && + !ismaster.arbiterOnly && + !ismaster.passive) + ) { + self.set[serverName] = { + type: ServerType.RSOther, + setVersion: null, + electionId: null, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + return false; + } + + // + // Standalone server, destroy and return + // + if (ismaster && ismaster.ismaster && !ismaster.setName) { + this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; + this.remove(server, { force: true }); + return false; + } + + // + // Server in maintanance mode + // + if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { + this.remove(server, { force: true }); + return false; + } + + // + // If the .me field does not match the passed in server + // + if (ismaster.me && ismaster.me.toLowerCase() !== serverName) { + if (this.logger.isWarn()) { + this.logger.warn( + f( + 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s', + server.name, + ismaster.me + ) + ); + } + + // Delete from the set + delete this.set[serverName]; + // Delete unknown servers + removeFrom(server, self.unknownServers); + + // Destroy the instance + server.destroy({ force: true }); + + // Set the type of topology we have + if (this.primary && !this.primary.equals(server)) { + this.topologyType = TopologyType.ReplicaSetWithPrimary; + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + // + // We have a potential primary + // + if (!this.primary && ismaster.primary) { + this.set[ismaster.primary.toLowerCase()] = { + type: ServerType.PossiblePrimary, + setName: null, + electionId: null, + setVersion: null + }; + } + + return false; + } + + // + // Primary handling + // + if (!this.primary && ismaster.ismaster && ismaster.setName) { + var ismasterElectionId = server.lastIsMaster().electionId; + if (this.setName && this.setName !== ismaster.setName) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return new MongoError( + f( + 'setName from ismaster does not match provided connection setName [%s] != [%s]', + ismaster.setName, + this.setName + ) + ); + } + + if (!this.maxElectionId && ismasterElectionId) { + this.maxElectionId = ismasterElectionId; + } else if (this.maxElectionId && ismasterElectionId) { + var result = compareObjectIds(this.maxElectionId, ismasterElectionId); + // Get the electionIds + var ismasterSetVersion = server.lastIsMaster().setVersion; + + if (result === 1) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } else if (result === 0 && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } + } + + this.maxSetVersion = ismasterSetVersion; + this.maxElectionId = ismasterElectionId; + } + + // Hande normalization of server names + var normalizedHosts = ismaster.hosts.map(function(x) { + return x.toLowerCase(); + }); + var locationIndex = normalizedHosts.indexOf(serverName); + + // Validate that the server exists in the host list + if (locationIndex !== -1) { + self.primary = server; + self.set[serverName] = { + type: ServerType.RSPrimary, + setVersion: ismaster.setVersion, + electionId: ismaster.electionId, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = TopologyType.ReplicaSetWithPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + removeFrom(server, self.secondaries); + removeFrom(server, self.passives); + self.emit('joined', 'primary', server); + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + emitTopologyDescriptionChanged(self); + return true; + } else if (ismaster.ismaster && ismaster.setName) { + // Get the electionIds + var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; + var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; + var currentSetName = self.set[self.primary.name.toLowerCase()].setName; + ismasterElectionId = server.lastIsMaster().electionId; + ismasterSetVersion = server.lastIsMaster().setVersion; + var ismasterSetName = server.lastIsMaster().setName; + + // Is it the same server instance + if (this.primary.equals(server) && currentSetName === ismasterSetName) { + return false; + } + + // If we do not have the same rs name + if (currentSetName && currentSetName !== ismasterSetName) { + if (!this.primary.equals(server)) { + this.topologyType = TopologyType.ReplicaSetWithPrimary; + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + return false; + } + + // Check if we need to replace the server + if (currentElectionId && ismasterElectionId) { + result = compareObjectIds(currentElectionId, ismasterElectionId); + + if (result === 1) { + return false; + } else if (result === 0 && currentSetVersion > ismasterSetVersion) { + return false; + } + } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } + + if (!this.maxElectionId && ismasterElectionId) { + this.maxElectionId = ismasterElectionId; + } else if (this.maxElectionId && ismasterElectionId) { + result = compareObjectIds(this.maxElectionId, ismasterElectionId); + + if (result === 1) { + return false; + } else if (result === 0 && currentSetVersion && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } else { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } + + this.maxElectionId = ismasterElectionId; + this.maxSetVersion = ismasterSetVersion; + } else { + this.maxSetVersion = ismasterSetVersion; + } + + // Modify the entry to unknown + self.set[self.primary.name.toLowerCase()] = { + type: ServerType.Unknown, + setVersion: null, + electionId: null, + setName: null + }; + + // Signal primary left + self.emit('left', 'primary', this.primary); + // Destroy the instance + self.primary.destroy({ force: true }); + // Set the new instance + self.primary = server; + // Set the set information + self.set[serverName] = { + type: ServerType.RSPrimary, + setVersion: ismaster.setVersion, + electionId: ismaster.electionId, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = TopologyType.ReplicaSetWithPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + removeFrom(server, self.secondaries); + removeFrom(server, self.passives); + self.emit('joined', 'primary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // A possible instance + if (!this.primary && ismaster.primary) { + self.set[ismaster.primary.toLowerCase()] = { + type: ServerType.PossiblePrimary, + setVersion: null, + electionId: null, + setName: null + }; + } + + // + // Secondary handling + // + if ( + ismaster.secondary && + ismaster.setName && + !inList(ismaster, server, this.secondaries) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + + // Remove primary + if (this.primary && this.primary.name.toLowerCase() === serverName) { + server.destroy({ force: true }); + this.primary = null; + self.emit('left', 'primary', server); + } + + // Emit secondary joined replicaset + self.emit('joined', 'secondary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Arbiter handling + // + if ( + isArbiter(ismaster) && + !inList(ismaster, server, this.arbiters) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + self.emit('joined', 'arbiter', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Passive handling + // + if ( + ismaster.passive && + ismaster.setName && + !inList(ismaster, server, this.passives) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + + // Remove primary + if (this.primary && this.primary.name.toLowerCase() === serverName) { + server.destroy({ force: true }); + this.primary = null; + self.emit('left', 'primary', server); + } + + self.emit('joined', 'secondary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Remove the primary + // + if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) { + self.emit('left', 'primary', this.primary); + this.primary.destroy({ force: true }); + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } + + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + return false; +}; + +/** + * Recalculate single server max staleness + * @method + */ +ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { + // Locate the max secondary lastwrite + var max = 0; + // Go over all secondaries + for (var i = 0; i < this.secondaries.length; i++) { + max = Math.max(max, this.secondaries[i].lastWriteDate); + } + + // Perform this servers staleness calculation + if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) { + server.staleness = + server.lastUpdateTime - + server.lastWriteDate - + (this.primary.lastUpdateTime - this.primary.lastWriteDate) + + haInterval; + } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) { + server.staleness = max - server.lastWriteDate + haInterval; + } +}; + +/** + * Recalculate all the staleness values for secodaries + * @method + */ +ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { + for (var i = 0; i < this.secondaries.length; i++) { + this.updateServerMaxStaleness(this.secondaries[i], haInterval); + } +}; + +/** + * Pick a server by the passed in ReadPreference + * @method + * @param {ReadPreference} readPreference The ReadPreference instance to use + */ +ReplSetState.prototype.pickServer = function(readPreference) { + // If no read Preference set to primary by default + readPreference = readPreference || ReadPreference.primary; + + // maxStalenessSeconds is not allowed with a primary read + if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) { + return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); + } + + // Check if we have any non compatible servers for maxStalenessSeconds + var allservers = this.primary ? [this.primary] : []; + allservers = allservers.concat(this.secondaries); + + // Does any of the servers not support the right wire protocol version + // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out + if (readPreference.maxStalenessSeconds != null) { + for (var i = 0; i < allservers.length; i++) { + if (allservers[i].ismaster.maxWireVersion < 5) { + return new MongoError( + 'maxStalenessSeconds not supported by at least one of the replicaset members' + ); + } + } + } + + // Do we have the nearest readPreference + if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) { + return pickNearest(this, readPreference); + } else if ( + readPreference.preference === 'nearest' && + readPreference.maxStalenessSeconds != null + ) { + return pickNearestMaxStalenessSeconds(this, readPreference); + } + + // Get all the secondaries + var secondaries = this.secondaries; + + // Check if we can satisfy and of the basic read Preferences + if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) { + return new MongoError('no secondary server available'); + } + + if ( + readPreference.equals(ReadPreference.secondaryPreferred) && + secondaries.length === 0 && + this.primary == null + ) { + return new MongoError('no secondary or primary server available'); + } + + if (readPreference.equals(ReadPreference.primary) && this.primary == null) { + return new MongoError('no primary server available'); + } + + // Secondary preferred or just secondaries + if ( + readPreference.equals(ReadPreference.secondaryPreferred) || + readPreference.equals(ReadPreference.secondary) + ) { + if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { + // Pick nearest of any other servers available + var server = pickNearest(this, readPreference); + // No server in the window return primary + if (server) { + return server; + } + } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { + // Pick nearest of any other servers available + server = pickNearestMaxStalenessSeconds(this, readPreference); + // No server in the window return primary + if (server) { + return server; + } + } + + if (readPreference.equals(ReadPreference.secondaryPreferred)) { + return this.primary; + } + + return null; + } + + // Primary preferred + if (readPreference.equals(ReadPreference.primaryPreferred)) { + server = null; + + // We prefer the primary if it's available + if (this.primary) { + return this.primary; + } + + // Pick a secondary + if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { + server = pickNearest(this, readPreference); + } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { + server = pickNearestMaxStalenessSeconds(this, readPreference); + } + + // Did we find a server + if (server) return server; + } + + // Return the primary + return this.primary; +}; + +// +// Filter serves by tags +var filterByTags = function(readPreference, servers) { + if (readPreference.tags == null) return servers; + var filteredServers = []; + var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; + + // Iterate over the tags + for (var j = 0; j < tagsArray.length; j++) { + var tags = tagsArray[j]; + + // Iterate over all the servers + for (var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + + // Did we find the a matching server + var found = true; + // Check if the server is valid + for (var name in tags) { + if (serverTag[name] !== tags[name]) { + found = false; + } + } + + // Add to candidate list + if (found) { + filteredServers.push(servers[i]); + } + } + } + + // Returned filtered servers + return filteredServers; +}; + +function pickNearestMaxStalenessSeconds(self, readPreference) { + // Only get primary and secondaries as seeds + var servers = []; + + // Get the maxStalenessMS + var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; + + // Check if the maxStalenessMS > 90 seconds + if (maxStalenessMS < 90 * 1000) { + return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); + } + + // Add primary to list if not a secondary read preference + if ( + self.primary && + readPreference.preference !== 'secondary' && + readPreference.preference !== 'secondaryPreferred' + ) { + servers.push(self.primary); + } + + // Add all the secondaries + for (var i = 0; i < self.secondaries.length; i++) { + servers.push(self.secondaries[i]); + } + + // If we have a secondaryPreferred readPreference and no server add the primary + if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') { + servers.push(self.primary); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Filter by latency + servers = servers.filter(function(s) { + return s.staleness <= maxStalenessMS; + }); + + // Sort by time + servers.sort(function(a, b) { + return a.lastIsMasterMS - b.lastIsMasterMS; + }); + + // No servers, default to primary + if (servers.length === 0) { + return null; + } + + // Ensure index does not overflow the number of available servers + self.index = self.index % servers.length; + + // Get the server + var server = servers[self.index]; + // Add to the index + self.index = self.index + 1; + // Return the first server of the sorted and filtered list + return server; +} + +function pickNearest(self, readPreference) { + // Only get primary and secondaries as seeds + var servers = []; + + // Add primary to list if not a secondary read preference + if ( + self.primary && + readPreference.preference !== 'secondary' && + readPreference.preference !== 'secondaryPreferred' + ) { + servers.push(self.primary); + } + + // Add all the secondaries + for (var i = 0; i < self.secondaries.length; i++) { + servers.push(self.secondaries[i]); + } + + // If we have a secondaryPreferred readPreference and no server add the primary + if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') { + servers.push(self.primary); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Sort by time + servers.sort(function(a, b) { + return a.lastIsMasterMS - b.lastIsMasterMS; + }); + + // Locate lowest time (picked servers are lowest time + acceptable Latency margin) + var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; + + // Filter by latency + servers = servers.filter(function(s) { + return s.lastIsMasterMS <= lowest + self.acceptableLatency; + }); + + // No servers, default to primary + if (servers.length === 0) { + return null; + } + + // Ensure index does not overflow the number of available servers + self.index = self.index % servers.length; + // Get the server + var server = servers[self.index]; + // Add to the index + self.index = self.index + 1; + // Return the first server of the sorted and filtered list + return server; +} + +function inList(ismaster, server, list) { + for (var i = 0; i < list.length; i++) { + if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase()) + return true; + } + + return false; +} + +function addToList(self, type, ismaster, server, list) { + var serverName = server.name.toLowerCase(); + // Update set information about the server instance + self.set[serverName].type = type; + self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; + self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; + self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; + // Add to the list + list.push(server); +} + +function compareObjectIds(id1, id2) { + var a = Buffer.from(id1.toHexString(), 'hex'); + var b = Buffer.from(id2.toHexString(), 'hex'); + + if (a === b) { + return 0; + } + + if (typeof Buffer.compare === 'function') { + return Buffer.compare(a, b); + } + + var x = a.length; + var y = b.length; + var len = Math.min(x, y); + + for (var i = 0; i < len; i++) { + if (a[i] !== b[i]) { + break; + } + } + + if (i !== len) { + x = a[i]; + y = b[i]; + } + + return x < y ? -1 : y < x ? 1 : 0; +} + +function removeFrom(server, list) { + for (var i = 0; i < list.length; i++) { + if (list[i].equals && list[i].equals(server)) { + list.splice(i, 1); + return true; + } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) { + list.splice(i, 1); + return true; + } + } + + return false; +} + +function emitTopologyDescriptionChanged(self) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + var topology = 'Unknown'; + var setName = self.setName; + + if (self.hasPrimaryAndSecondary()) { + topology = 'ReplicaSetWithPrimary'; + } else if (!self.hasPrimary() && self.hasSecondary()) { + topology = 'ReplicaSetNoPrimary'; + } + + // Generate description + var description = { + topologyType: topology, + setName: setName, + servers: [] + }; + + // Add the primary to the list + if (self.hasPrimary()) { + var desc = self.primary.getDescription(); + desc.type = 'RSPrimary'; + description.servers.push(desc); + } + + // Add all the secondaries + description.servers = description.servers.concat( + self.secondaries.map(function(x) { + var description = x.getDescription(); + description.type = 'RSSecondary'; + return description; + }) + ); + + // Add all the arbiters + description.servers = description.servers.concat( + self.arbiters.map(function(x) { + var description = x.getDescription(); + description.type = 'RSArbiter'; + return description; + }) + ); + + // Add all the passives + description.servers = description.servers.concat( + self.passives.map(function(x) { + var description = x.getDescription(); + description.type = 'RSSecondary'; + return description; + }) + ); + + // Get the diff + var diffResult = diff(self.replicasetDescription, description); + + // Create the result + var result = { + topologyId: self.id, + previousDescription: self.replicasetDescription, + newDescription: description, + diff: diffResult + }; + + // Emit the topologyDescription change + // if(diffResult.servers.length > 0) { + self.emit('topologyDescriptionChanged', result); + // } + + // Set the new description + self.replicasetDescription = description; + } +} + +module.exports = ReplSetState; + + +/***/ }), + +/***/ 6495: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var inherits = __webpack_require__(1669).inherits, + f = __webpack_require__(1669).format, + EventEmitter = __webpack_require__(8614).EventEmitter, + ReadPreference = __webpack_require__(4485), + Logger = __webpack_require__(104), + debugOptions = __webpack_require__(7746).debugOptions, + retrieveBSON = __webpack_require__(7746).retrieveBSON, + Pool = __webpack_require__(5500), + MongoError = __webpack_require__(3111).MongoError, + MongoNetworkError = __webpack_require__(3111).MongoNetworkError, + wireProtocol = __webpack_require__(9206), + CoreCursor = __webpack_require__(4847).CoreCursor, + sdam = __webpack_require__(2306), + createCompressionInfo = __webpack_require__(2306).createCompressionInfo, + resolveClusterTime = __webpack_require__(2306).resolveClusterTime, + SessionMixins = __webpack_require__(2306).SessionMixins, + relayEvents = __webpack_require__(1178).relayEvents; + +const collationNotSupported = __webpack_require__(1178).collationNotSupported; +const makeClientMetadata = __webpack_require__(1178).makeClientMetadata; + +// Used for filtering out fields for loggin +var debugFields = [ + 'reconnect', + 'reconnectTries', + 'reconnectInterval', + 'emitError', + 'cursorFactory', + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'checkServerIdentity', + 'socketTimeout', + 'ssl', + 'ca', + 'crl', + 'cert', + 'key', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'servername' +]; + +// Server instance id +var id = 0; +var serverAccounting = false; +var servers = {}; +var BSON = retrieveBSON(); + +function topologyId(server) { + return server.s.parent == null ? server.id : server.s.parent.id; +} + +/** + * Creates a new Server instance + * @class + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) + * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {Server} A cursor instance + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @fires Server#reconnectFailed + * @fires Server#serverHeartbeatStarted + * @fires Server#serverHeartbeatSucceeded + * @fires Server#serverHeartbeatFailed + * @fires Server#topologyOpening + * @fires Server#topologyClosed + * @fires Server#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var Server = function(options) { + options = options || {}; + + // Add event listener + EventEmitter.call(this); + + // Server instance id + this.id = id++; + + // Internal state + this.s = { + // Options + options: Object.assign({ metadata: makeClientMetadata(options) }, options), + // Logger + logger: Logger('Server', options), + // Factory overrides + Cursor: options.cursorFactory || CoreCursor, + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Pool + pool: null, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Monitor thread (keeps the connection alive) + monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, + // Is the server in a topology + inTopology: !!options.parent, + // Monitoring timeout + monitoringInterval: + typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, + compression: { compressors: createCompressionInfo(options) }, + // Optional parent topology + parent: options.parent + }; + + // If this is a single deployment we need to track the clusterTime here + if (!this.s.parent) { + this.s.clusterTime = null; + } + + // Curent ismaster + this.ismaster = null; + // Current ping time + this.lastIsMasterMS = -1; + // The monitoringProcessId + this.monitoringProcessId = null; + // Initial connection + this.initialConnect = true; + // Default type + this._type = 'server'; + + // Max Stalleness values + // last time we updated the ismaster state + this.lastUpdateTime = 0; + // Last write time + this.lastWriteDate = 0; + // Stalleness + this.staleness = 0; +}; + +inherits(Server, EventEmitter); +Object.assign(Server.prototype, SessionMixins); + +Object.defineProperty(Server.prototype, 'type', { + enumerable: true, + get: function() { + return this._type; + } +}); + +Object.defineProperty(Server.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + if (!this.ismaster) return null; + return this.ismaster.logicalSessionTimeoutMinutes || null; + } +}); + +Object.defineProperty(Server.prototype, 'clientMetadata', { + enumerable: true, + get: function() { + return this.s.options.metadata; + } +}); + +// In single server deployments we track the clusterTime directly on the topology, however +// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the +// tracking objects so we can ensure we are gossiping the maximum time received from the +// server. +Object.defineProperty(Server.prototype, 'clusterTime', { + enumerable: true, + set: function(clusterTime) { + const settings = this.s.parent ? this.s.parent : this.s; + resolveClusterTime(settings, clusterTime); + }, + get: function() { + const settings = this.s.parent ? this.s.parent : this.s; + return settings.clusterTime || null; + } +}); + +Server.enableServerAccounting = function() { + serverAccounting = true; + servers = {}; +}; + +Server.disableServerAccounting = function() { + serverAccounting = false; +}; + +Server.servers = function() { + return servers; +}; + +Object.defineProperty(Server.prototype, 'name', { + enumerable: true, + get: function() { + return this.s.options.host + ':' + this.s.options.port; + } +}); + +function disconnectHandler(self, type, ns, cmd, options, callback) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if ( + !self.s.pool.isConnected() && + self.s.options.reconnect && + self.s.disconnectHandler != null && + !options.monitoring + ) { + self.s.disconnectHandler.add(type, ns, cmd, options, callback); + return true; + } + + // If we have no connection error + if (!self.s.pool.isConnected()) { + callback(new MongoError(f('no connection available to server %s', self.name))); + return true; + } +} + +function monitoringProcess(self) { + return function() { + // Pool was destroyed do not continue process + if (self.s.pool.isDestroyed()) return; + // Emit monitoring Process event + self.emit('monitoring', self); + // Perform ismaster call + // Get start time + var start = new Date().getTime(); + + // Execute the ismaster query + self.command( + 'admin.$cmd', + { ismaster: true }, + { + socketTimeout: + typeof self.s.options.connectionTimeout !== 'number' + ? 2000 + : self.s.options.connectionTimeout, + monitoring: true + }, + (err, result) => { + // Set initial lastIsMasterMS + self.lastIsMasterMS = new Date().getTime() - start; + if (self.s.pool.isDestroyed()) return; + // Update the ismaster view if we have a result + if (result) { + self.ismaster = result.result; + } + // Re-schedule the monitoring process + self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); + } + ); + }; +} + +var eventHandler = function(self, event) { + return function(err, conn) { + // Log information of received information if in info mode + if (self.s.logger.isInfo()) { + var object = err instanceof MongoError ? JSON.stringify(err) : {}; + self.s.logger.info( + f('server %s fired event %s out with message %s', self.name, event, object) + ); + } + + // Handle connect event + if (event === 'connect') { + self.initialConnect = false; + self.ismaster = conn.ismaster; + self.lastIsMasterMS = conn.lastIsMasterMS; + if (conn.agreedCompressor) { + self.s.pool.options.agreedCompressor = conn.agreedCompressor; + } + + if (conn.zlibCompressionLevel) { + self.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; + } + + if (conn.ismaster.$clusterTime) { + const $clusterTime = conn.ismaster.$clusterTime; + self.clusterTime = $clusterTime; + } + + // It's a proxy change the type so + // the wireprotocol will send $readPreference + if (self.ismaster.msg === 'isdbgrid') { + self._type = 'mongos'; + } + + // Have we defined self monitoring + if (self.s.monitoring) { + self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); + } + + // Emit server description changed if something listening + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + }); + + if (!self.s.inTopology) { + // Emit topology description changed if something listening + sdam.emitTopologyDescriptionChanged(self, { + topologyType: 'Single', + servers: [ + { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + } + ] + }); + } + + // Log the ismaster if available + if (self.s.logger.isInfo()) { + self.s.logger.info( + f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster)) + ); + } + + // Emit connect + self.emit('connect', self); + } else if ( + event === 'error' || + event === 'parseError' || + event === 'close' || + event === 'timeout' || + event === 'reconnect' || + event === 'attemptReconnect' || + 'reconnectFailed' + ) { + // Remove server instance from accounting + if ( + serverAccounting && + ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1 + ) { + // Emit toplogy opening event if not in topology + if (!self.s.inTopology) { + self.emit('topologyOpening', { topologyId: self.id }); + } + + delete servers[self.id]; + } + + if (event === 'close') { + // Closing emits a server description changed event going to unknown. + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + }); + } + + // Reconnect failed return error + if (event === 'reconnectFailed') { + self.emit('reconnectFailed', err); + // Emit error if any listeners + if (self.listeners('error').length > 0) { + self.emit('error', err); + } + // Terminate + return; + } + + // On first connect fail + if ( + ['disconnected', 'connecting'].indexOf(self.s.pool.state) !== -1 && + self.initialConnect && + ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1 + ) { + self.initialConnect = false; + return self.emit( + 'error', + new MongoNetworkError( + f('failed to connect to server [%s] on first connect [%s]', self.name, err) + ) + ); + } + + // Reconnect event, emit the server + if (event === 'reconnect') { + // Reconnecting emits a server description changed event going from unknown to the + // current server type. + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + }); + return self.emit(event, self); + } + + // Emit the event + self.emit(event, err); + } + }; +}; + +/** + * Initiate server connect + */ +Server.prototype.connect = function(options) { + var self = this; + options = options || {}; + + // Set the connections + if (serverAccounting) servers[this.id] = this; + + // Do not allow connect to be called on anything that's not disconnected + if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { + throw new MongoError(f('server instance in invalid state %s', self.s.pool.state)); + } + + // Create a pool + self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson })); + + // Set up listeners + self.s.pool.on('close', eventHandler(self, 'close')); + self.s.pool.on('error', eventHandler(self, 'error')); + self.s.pool.on('timeout', eventHandler(self, 'timeout')); + self.s.pool.on('parseError', eventHandler(self, 'parseError')); + self.s.pool.on('connect', eventHandler(self, 'connect')); + self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); + self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); + + // Set up listeners for command monitoring + relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Emit toplogy opening event if not in topology + if (!self.s.inTopology) { + this.emit('topologyOpening', { topologyId: topologyId(self) }); + } + + // Emit opening server event + self.emit('serverOpening', { topologyId: topologyId(self), address: self.name }); + + self.s.pool.connect(); +}; + +/** + * Authenticate the topology. + * @method + * @param {MongoCredentials} credentials The credentials for authentication we are using + * @param {authResultCallback} callback A callback function + */ +Server.prototype.auth = function(credentials, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +/** + * Get the server description + * @method + * @return {object} + */ +Server.prototype.getDescription = function() { + var ismaster = this.ismaster || {}; + var description = { + type: sdam.getTopologyType(this), + address: this.name + }; + + // Add fields if available + if (ismaster.hosts) description.hosts = ismaster.hosts; + if (ismaster.arbiters) description.arbiters = ismaster.arbiters; + if (ismaster.passives) description.passives = ismaster.passives; + if (ismaster.setName) description.setName = ismaster.setName; + return description; +}; + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Server.prototype.lastIsMaster = function() { + return this.ismaster; +}; + +/** + * Unref all connections belong to this server + * @method + */ +Server.prototype.unref = function() { + this.s.pool.unref(); +}; + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Server.prototype.isConnected = function() { + if (!this.s.pool) return false; + return this.s.pool.isConnected(); +}; + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Server.prototype.isDestroyed = function() { + if (!this.s.pool) return false; + return this.s.pool.isDestroyed(); +}; + +function basicWriteValidations(self) { + if (!self.s.pool) return new MongoError('server instance is not connected'); + if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed'); +} + +function basicReadValidations(self, options) { + basicWriteValidations(self, options); + + if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { + throw new Error('readPreference must be an instance of ReadPreference'); + } +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.command = function(ns, cmd, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicReadValidations(self, options); + if (result) return callback(result); + + // Clone the options + options = Object.assign({}, options, { wireProtocolCommand: false }); + + // Debug log + if (self.s.logger.isDebug()) + self.s.logger.debug( + f( + 'executing command [%s] against %s', + JSON.stringify({ + ns: ns, + cmd: cmd, + options: debugOptions(debugFields, options) + }), + self.name + ) + ); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, cmd)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + wireProtocol.command(self, ns, cmd, options, callback); +}; + +/** + * Execute a query against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command document for the query + * @param {object} options Optional settings + * @param {function} callback + */ +Server.prototype.query = function(ns, cmd, cursorState, options, callback) { + wireProtocol.query(this, ns, cmd, cursorState, options, callback); +}; + +/** + * Execute a `getMore` against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cursorState State data associated with the cursor calling this method + * @param {object} options Optional settings + * @param {function} callback + */ +Server.prototype.getMore = function(ns, cursorState, batchSize, options, callback) { + wireProtocol.getMore(this, ns, cursorState, batchSize, options, callback); +}; + +/** + * Execute a `killCursors` command against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cursorState State data associated with the cursor calling this method + * @param {function} callback + */ +Server.prototype.killCursors = function(ns, cursorState, callback) { + wireProtocol.killCursors(this, ns, cursorState, callback); +}; + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.insert = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return; + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + + // Execute write + return wireProtocol.insert(self, ns, ops, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.update = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'update', ns, ops, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, options)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return wireProtocol.update(self, ns, ops, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.remove = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, options)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return wireProtocol.remove(self, ns, ops, options, callback); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +Server.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(topology, ns, cmd, options); +}; + +/** + * Compare two server instances + * @method + * @param {Server} server Server to compare equality against + * @return {boolean} + */ +Server.prototype.equals = function(server) { + if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase(); + if (server.name) return this.name.toLowerCase() === server.name.toLowerCase(); + return false; +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Server.prototype.connections = function() { + return this.s.pool.allConnections(); +}; + +/** + * Selects a server + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Unused + * @param {ClientSession} [options.session] Unused + * @return {Server} + */ +Server.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') + (callback = options), (options = selector), (selector = undefined); + + callback(null, this); +}; + +var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; + +/** + * Destroy the server connection + * @method + * @param {boolean} [options.emitClose=false] Emit close event on destroy + * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy + * @param {boolean} [options.force=false] Force destroy the pool + */ +Server.prototype.destroy = function(options, callback) { + if (this._destroyed) { + if (typeof callback === 'function') callback(null, null); + return; + } + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + var self = this; + + // Set the connections + if (serverAccounting) delete servers[this.id]; + + // Destroy the monitoring process if any + if (this.monitoringProcessId) { + clearTimeout(this.monitoringProcessId); + } + + // No pool, return + if (!self.s.pool) { + this._destroyed = true; + if (typeof callback === 'function') callback(null, null); + return; + } + + // Emit close event + if (options.emitClose) { + self.emit('close', self); + } + + // Emit destroy event + if (options.emitDestroy) { + self.emit('destroy', self); + } + + // Remove all listeners + listeners.forEach(function(event) { + self.s.pool.removeAllListeners(event); + }); + + // Emit opening server event + if (self.listeners('serverClosed').length > 0) + self.emit('serverClosed', { topologyId: topologyId(self), address: self.name }); + + // Emit toplogy opening event if not in topology + if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { + self.emit('topologyClosed', { topologyId: topologyId(self) }); + } + + if (self.s.logger.isDebug()) { + self.s.logger.debug(f('destroy called on server %s', self.name)); + } + + // Destroy the pool + this.s.pool.destroy(options.force, callback); + this._destroyed = true; +}; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Server#connect + * @type {Server} + */ + +/** + * A server reconnect event, used to verify that the server topology has reconnected + * + * @event Server#reconnect + * @type {Server} + */ + +/** + * A server opening SDAM monitoring event + * + * @event Server#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Server#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Server#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event Server#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event Server#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event Server#topologyDescriptionChanged + * @type {object} + */ + +/** + * Server reconnect failed + * + * @event Server#reconnectFailed + * @type {Error} + */ + +/** + * Server connection pool closed + * + * @event Server#close + * @type {object} + */ + +/** + * Server connection pool caused an error + * + * @event Server#error + * @type {Error} + */ + +/** + * Server destroyed was called + * + * @event Server#destroy + * @type {Server} + */ + +module.exports = Server; + + +/***/ }), + +/***/ 2306: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const ReadPreference = __webpack_require__(4485); +const TopologyType = __webpack_require__(2291).TopologyType; +const MongoError = __webpack_require__(3111).MongoError; +const isRetryableWriteError = __webpack_require__(3111).isRetryableWriteError; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const MongoNetworkError = __webpack_require__(3111).MongoNetworkError; +const MMAPv1_RETRY_WRITES_ERROR_CODE = 20; + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +function createCompressionInfo(options) { + if (!options.compression || !options.compression.compressors) { + return []; + } + + // Check that all supplied compressors are valid + options.compression.compressors.forEach(function(compressor) { + if (compressor !== 'snappy' && compressor !== 'zlib') { + throw new Error('compressors must be at least one of snappy or zlib'); + } + }); + + return options.compression.compressors; +} + +function clone(object) { + return JSON.parse(JSON.stringify(object)); +} + +var getPreviousDescription = function(self) { + if (!self.s.serverDescription) { + self.s.serverDescription = { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + }; + } + + return self.s.serverDescription; +}; + +var emitServerDescriptionChanged = function(self, description) { + if (self.listeners('serverDescriptionChanged').length > 0) { + // Emit the server description changed events + self.emit('serverDescriptionChanged', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name, + previousDescription: getPreviousDescription(self), + newDescription: description + }); + + self.s.serverDescription = description; + } +}; + +var getPreviousTopologyDescription = function(self) { + if (!self.s.topologyDescription) { + self.s.topologyDescription = { + topologyType: 'Unknown', + servers: [ + { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + } + ] + }; + } + + return self.s.topologyDescription; +}; + +var emitTopologyDescriptionChanged = function(self, description) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + // Emit the server description changed events + self.emit('topologyDescriptionChanged', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name, + previousDescription: getPreviousTopologyDescription(self), + newDescription: description + }); + + self.s.serverDescription = description; + } +}; + +var changedIsMaster = function(self, currentIsmaster, ismaster) { + var currentType = getTopologyType(self, currentIsmaster); + var newType = getTopologyType(self, ismaster); + if (newType !== currentType) return true; + return false; +}; + +var getTopologyType = function(self, ismaster) { + if (!ismaster) { + ismaster = self.ismaster; + } + + if (!ismaster) return 'Unknown'; + if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos'; + if (ismaster.ismaster && !ismaster.hosts) return 'Standalone'; + if (ismaster.ismaster) return 'RSPrimary'; + if (ismaster.secondary) return 'RSSecondary'; + if (ismaster.arbiterOnly) return 'RSArbiter'; + return 'Unknown'; +}; + +var inquireServerState = function(self) { + return function(callback) { + if (self.s.state === 'destroyed') return; + // Record response time + var start = new Date().getTime(); + + // emitSDAMEvent + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); + + // Attempt to execute ismaster command + self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) { + if (!err) { + // Legacy event sender + self.emit('ismaster', r, self); + + // Calculate latencyMS + var latencyMS = new Date().getTime() - start; + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: self.name + }); + + // Did the server change + if (changedIsMaster(self, self.s.ismaster, r.result)) { + // Emit server description changed if something listening + emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) + }); + } + + // Updat ismaster view + self.s.ismaster = r.result; + + // Set server response time + self.s.isMasterLatencyMS = latencyMS; + } else { + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: self.name + }); + } + + // Peforming an ismaster monitoring callback operation + if (typeof callback === 'function') { + return callback(err, r); + } + + // Perform another sweep + self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); + }); + }; +}; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for (var name in options) { + opts[name] = options[name]; + } + return opts; +}; + +function Interval(fn, time) { + var timer = false; + + this.start = function() { + if (!this.isRunning()) { + timer = setInterval(fn, time); + } + + return this; + }; + + this.stop = function() { + clearInterval(timer); + timer = false; + return this; + }; + + this.isRunning = function() { + return timer !== false; + }; +} + +function Timeout(fn, time) { + var timer = false; + var func = () => { + if (timer) { + clearTimeout(timer); + timer = false; + + fn(); + } + }; + + this.start = function() { + if (!this.isRunning()) { + timer = setTimeout(func, time); + } + return this; + }; + + this.stop = function() { + clearTimeout(timer); + timer = false; + return this; + }; + + this.isRunning = function() { + return timer !== false; + }; +} + +function diff(previous, current) { + // Difference document + var diff = { + servers: [] + }; + + // Previous entry + if (!previous) { + previous = { servers: [] }; + } + + // Check if we have any previous servers missing in the current ones + for (var i = 0; i < previous.servers.length; i++) { + var found = false; + + for (var j = 0; j < current.servers.length; j++) { + if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) { + found = true; + break; + } + } + + if (!found) { + // Add to the diff + diff.servers.push({ + address: previous.servers[i].address, + from: previous.servers[i].type, + to: 'Unknown' + }); + } + } + + // Check if there are any severs that don't exist + for (j = 0; j < current.servers.length; j++) { + found = false; + + // Go over all the previous servers + for (i = 0; i < previous.servers.length; i++) { + if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) { + found = true; + break; + } + } + + // Add the server to the diff + if (!found) { + diff.servers.push({ + address: current.servers[j].address, + from: 'Unknown', + to: current.servers[j].type + }); + } + } + + // Got through all the servers + for (i = 0; i < previous.servers.length; i++) { + var prevServer = previous.servers[i]; + + // Go through all current servers + for (j = 0; j < current.servers.length; j++) { + var currServer = current.servers[j]; + + // Matching server + if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { + // We had a change in state + if (prevServer.type !== currServer.type) { + diff.servers.push({ + address: prevServer.address, + from: prevServer.type, + to: currServer.type + }); + } + } + } + } + + // Return difference + return diff; +} + +/** + * Shared function to determine clusterTime for a given topology + * + * @param {*} topology + * @param {*} clusterTime + */ +function resolveClusterTime(topology, $clusterTime) { + if (topology.clusterTime == null) { + topology.clusterTime = $clusterTime; + } else { + if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { + topology.clusterTime = $clusterTime; + } + } +} + +// NOTE: this is a temporary move until the topologies can be more formally refactored +// to share code. +const SessionMixins = { + endSessions: function(sessions, callback) { + if (!Array.isArray(sessions)) { + sessions = [sessions]; + } + + // TODO [$5f5fbe42fcabad09c1c241af]: + // When connected to a sharded cluster the endSessions command + // can be sent to any mongos. When connected to a replica set the + // endSessions command MUST be sent to the primary if the primary + // is available, otherwise it MUST be sent to any available secondary. + // Is it enough to use: ReadPreference.primaryPreferred ? + this.command( + 'admin.$cmd', + { endSessions: sessions }, + { readPreference: ReadPreference.primaryPreferred }, + () => { + // intentionally ignored, per spec + if (typeof callback === 'function') callback(); + } + ); + } +}; + +function topologyType(topology) { + if (topology.description) { + return topology.description.type; + } + + if (topology.type === 'mongos') { + return TopologyType.Sharded; + } else if (topology.type === 'replset') { + return TopologyType.ReplicaSetWithPrimary; + } + + return TopologyType.Single; +} + +const RETRYABLE_WIRE_VERSION = 6; + +/** + * Determines whether the provided topology supports retryable writes + * + * @param {Mongos|Replset} topology + */ +const isRetryableWritesSupported = function(topology) { + const maxWireVersion = topology.lastIsMaster().maxWireVersion; + if (maxWireVersion < RETRYABLE_WIRE_VERSION) { + return false; + } + + if (!topology.logicalSessionTimeoutMinutes) { + return false; + } + + if (topologyType(topology) === TopologyType.Single) { + return false; + } + + return true; +}; + +const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = + 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; + +function getMMAPError(err) { + if (err.code !== MMAPv1_RETRY_WRITES_ERROR_CODE || !err.errmsg.includes('Transaction numbers')) { + return err; + } + + // According to the retryable writes spec, we must replace the error message in this case. + // We need to replace err.message so the thrown message is correct and we need to replace err.errmsg to meet the spec requirement. + const newErr = new MongoError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError: err + }); + return newErr; +} + +// NOTE: only used for legacy topology types +function legacyIsRetryableWriteError(err, topology) { + if (!(err instanceof MongoError)) { + return false; + } + + // if pre-4.4 server, then add error label if its a retryable write error + if ( + isRetryableWritesSupported(topology) && + (err instanceof MongoNetworkError || + (maxWireVersion(topology) < 9 && isRetryableWriteError(err))) + ) { + err.addErrorLabel('RetryableWriteError'); + } + + return err.hasErrorLabel('RetryableWriteError'); +} + +module.exports = { + SessionMixins, + resolveClusterTime, + inquireServerState, + getTopologyType, + emitServerDescriptionChanged, + emitTopologyDescriptionChanged, + cloneOptions, + createCompressionInfo, + clone, + diff, + Interval, + Timeout, + isRetryableWritesSupported, + getMMAPError, + topologyType, + legacyIsRetryableWriteError +}; + + +/***/ }), + +/***/ 1707: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const MongoError = __webpack_require__(3111).MongoError; +const ReadPreference = __webpack_require__(4485); +const ReadConcern = __webpack_require__(7289); +const WriteConcern = __webpack_require__(2481); + +let TxnState; +let stateMachine; + +(() => { + const NO_TRANSACTION = 'NO_TRANSACTION'; + const STARTING_TRANSACTION = 'STARTING_TRANSACTION'; + const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS'; + const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED'; + const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY'; + const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED'; + + TxnState = { + NO_TRANSACTION, + STARTING_TRANSACTION, + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + TRANSACTION_ABORTED + }; + + stateMachine = { + [NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION], + [STARTING_TRANSACTION]: [ + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + TRANSACTION_ABORTED + ], + [TRANSACTION_IN_PROGRESS]: [ + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_ABORTED + ], + [TRANSACTION_COMMITTED]: [ + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + STARTING_TRANSACTION, + NO_TRANSACTION + ], + [TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION], + [TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION] + }; +})(); + +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @typedef {Object} ReadConcern + * @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level + * @see https://docs.mongodb.com/manual/reference/read-concern/ + */ + +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @typedef {Object} WriteConcern + * @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has + * propagated to a specified number of mongod hosts + * @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has + * been written to the journal + * @property {number} [wtimeout] a time limit, in milliseconds, for the write concern + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ + +/** + * Configuration options for a transaction. + * @typedef {Object} TransactionOptions + * @property {ReadConcern} [readConcern] A default read concern for commands in this transaction + * @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction + * @property {ReadPreference} [readPreference] A default read preference for commands in this transaction + */ + +/** + * A class maintaining state related to a server transaction. Internal Only + * @ignore + */ +class Transaction { + /** + * Create a transaction + * + * @ignore + * @param {TransactionOptions} [options] Optional settings + */ + constructor(options) { + options = options || {}; + + this.state = TxnState.NO_TRANSACTION; + this.options = {}; + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern) { + if (writeConcern.w <= 0) { + throw new MongoError('Transactions do not support unacknowledged write concern'); + } + + this.options.writeConcern = writeConcern; + } + + if (options.readConcern) { + this.options.readConcern = ReadConcern.fromOptions(options); + } + + if (options.readPreference) { + this.options.readPreference = ReadPreference.fromOptions(options); + } + + if (options.maxCommitTimeMS) { + this.options.maxTimeMS = options.maxCommitTimeMS; + } + + // TODO [$5f5fbe42fcabad09c1c241b0]: This isn't technically necessary + this._pinnedServer = undefined; + this._recoveryToken = undefined; + } + + get server() { + return this._pinnedServer; + } + + get recoveryToken() { + return this._recoveryToken; + } + + get isPinned() { + return !!this.server; + } + + /** + * @ignore + * @return Whether this session is presently in a transaction + */ + get isActive() { + return ( + [TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1 + ); + } + + /** + * Transition the transaction in the state machine + * @ignore + * @param {TxnState} state The new state to transition to + */ + transition(nextState) { + const nextStates = stateMachine[this.state]; + if (nextStates && nextStates.indexOf(nextState) !== -1) { + this.state = nextState; + if (this.state === TxnState.NO_TRANSACTION || this.state === TxnState.STARTING_TRANSACTION) { + this.unpinServer(); + } + return; + } + + throw new MongoError( + `Attempted illegal state transition from [${this.state}] to [${nextState}]` + ); + } + + pinServer(server) { + if (this.isActive) { + this._pinnedServer = server; + } + } + + unpinServer() { + this._pinnedServer = undefined; + } +} + +function isTransactionCommand(command) { + return !!(command.commitTransaction || command.abortTransaction); +} + +module.exports = { TxnState, Transaction, isTransactionCommand }; + + +/***/ }), + +/***/ 8767: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const URL = __webpack_require__(8835); +const qs = __webpack_require__(1191); +const dns = __webpack_require__(881); +const MongoParseError = __webpack_require__(3111).MongoParseError; +const ReadPreference = __webpack_require__(4485); + +/** + * The following regular expression validates a connection string and breaks the + * provide string into the following capture groups: [protocol, username, password, hosts] + */ +const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; + +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param {String} srvAddress The address to check against a domain + * @param {String} parentDomain The domain to check the provided address against + * @return {Boolean} Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress, parentDomain) { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} + +/** + * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal + * connection string. + * + * @param {string} uri The connection string to parse + * @param {object} options Optional user provided connection string options + * @param {function} callback + */ +function parseSrvConnectionString(uri, options, callback) { + const result = URL.parse(uri, true); + + if (options.directConnection || options.directconnection) { + return callback(new MongoParseError('directConnection not supported with SRV URI')); + } + + if (result.hostname.split('.').length < 3) { + return callback(new MongoParseError('URI does not have hostname, domain name and tld')); + } + + result.domainLength = result.hostname.split('.').length; + if (result.pathname && result.pathname.match(',')) { + return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); + } + + if (result.port) { + return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); + } + + // Resolve the SRV record and use the result as the list of hosts to connect to. + const lookupAddress = result.host; + dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { + if (err) return callback(err); + + if (addresses.length === 0) { + return callback(new MongoParseError('No addresses found at host')); + } + + for (let i = 0; i < addresses.length; i++) { + if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { + return callback( + new MongoParseError('Server record does not share hostname with parent URI') + ); + } + } + + // Convert the original URL to a non-SRV URL. + result.protocol = 'mongodb'; + result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); + + // Default to SSL true if it's not specified. + if ( + !('ssl' in options) && + (!result.search || !('ssl' in result.query) || result.query.ssl === null) + ) { + result.query.ssl = true; + } + + // Resolve TXT record and add options from there if they exist. + dns.resolveTxt(lookupAddress, (err, record) => { + if (err) { + if (err.code !== 'ENODATA') { + return callback(err); + } + record = null; + } + + if (record) { + if (record.length > 1) { + return callback(new MongoParseError('Multiple text records not allowed')); + } + + record = qs.parse(record[0].join('')); + if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { + return callback( + new MongoParseError('Text record must only set `authSource` or `replicaSet`') + ); + } + + result.query = Object.assign({}, record, result.query); + } + + // Set completed options back into the URL object. + result.search = qs.stringify(result.query); + + const finalString = URL.format(result); + parseConnectionString(finalString, options, (err, ret) => { + if (err) { + callback(err); + return; + } + + callback(null, Object.assign({}, ret, { srvHost: lookupAddress })); + }); + }); + }); +} + +/** + * Parses a query string item according to the connection string spec + * + * @param {string} key The key for the parsed value + * @param {Array|String} value The value to parse + * @return {Array|Object|String} The parsed value + */ +function parseQueryStringItemValue(key, value) { + if (Array.isArray(value)) { + // deduplicate and simplify arrays + value = value.filter((v, idx) => value.indexOf(v) === idx); + if (value.length === 1) value = value[0]; + } else if (value.indexOf(':') > 0) { + value = value.split(',').reduce((result, pair) => { + const parts = pair.split(':'); + result[parts[0]] = parseQueryStringItemValue(key, parts[1]); + return result; + }, {}); + } else if (value.indexOf(',') > 0) { + value = value.split(',').map(v => { + return parseQueryStringItemValue(key, v); + }); + } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { + value = value.toLowerCase() === 'true'; + } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { + const numericValue = parseFloat(value); + if (!Number.isNaN(numericValue)) { + value = parseFloat(value); + } + } + + return value; +} + +// Options that are known boolean types +const BOOLEAN_OPTIONS = new Set([ + 'slaveok', + 'slave_ok', + 'sslvalidate', + 'fsync', + 'safe', + 'retrywrites', + 'j' +]); + +// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue` +const STRING_OPTIONS = new Set(['authsource', 'replicaset']); + +// Supported text representations of auth mechanisms +// NOTE: this list exists in native already, if it is merged here we should deduplicate +const AUTH_MECHANISMS = new Set([ + 'GSSAPI', + 'MONGODB-AWS', + 'MONGODB-X509', + 'MONGODB-CR', + 'DEFAULT', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256', + 'PLAIN' +]); + +// Lookup table used to translate normalized (lower-cased) forms of connection string +// options to their expected camelCase version +const CASE_TRANSLATION = { + replicaset: 'replicaSet', + connecttimeoutms: 'connectTimeoutMS', + sockettimeoutms: 'socketTimeoutMS', + maxpoolsize: 'maxPoolSize', + minpoolsize: 'minPoolSize', + maxidletimems: 'maxIdleTimeMS', + waitqueuemultiple: 'waitQueueMultiple', + waitqueuetimeoutms: 'waitQueueTimeoutMS', + wtimeoutms: 'wtimeoutMS', + readconcern: 'readConcern', + readconcernlevel: 'readConcernLevel', + readpreference: 'readPreference', + maxstalenessseconds: 'maxStalenessSeconds', + readpreferencetags: 'readPreferenceTags', + authsource: 'authSource', + authmechanism: 'authMechanism', + authmechanismproperties: 'authMechanismProperties', + gssapiservicename: 'gssapiServiceName', + localthresholdms: 'localThresholdMS', + serverselectiontimeoutms: 'serverSelectionTimeoutMS', + serverselectiontryonce: 'serverSelectionTryOnce', + heartbeatfrequencyms: 'heartbeatFrequencyMS', + retrywrites: 'retryWrites', + uuidrepresentation: 'uuidRepresentation', + zlibcompressionlevel: 'zlibCompressionLevel', + tlsallowinvalidcertificates: 'tlsAllowInvalidCertificates', + tlsallowinvalidhostnames: 'tlsAllowInvalidHostnames', + tlsinsecure: 'tlsInsecure', + tlscafile: 'tlsCAFile', + tlscertificatekeyfile: 'tlsCertificateKeyFile', + tlscertificatekeyfilepassword: 'tlsCertificateKeyFilePassword', + wtimeout: 'wTimeoutMS', + j: 'journal', + directconnection: 'directConnection' +}; + +/** + * Sets the value for `key`, allowing for any required translation + * + * @param {object} obj The object to set the key on + * @param {string} key The key to set the value for + * @param {*} value The value to set + * @param {object} options The options used for option parsing + */ +function applyConnectionStringOption(obj, key, value, options) { + // simple key translation + if (key === 'journal') { + key = 'j'; + } else if (key === 'wtimeoutms') { + key = 'wtimeout'; + } + + // more complicated translation + if (BOOLEAN_OPTIONS.has(key)) { + value = value === 'true' || value === true; + } else if (key === 'appname') { + value = decodeURIComponent(value); + } else if (key === 'readconcernlevel') { + obj['readConcernLevel'] = value; + key = 'readconcern'; + value = { level: value }; + } + + // simple validation + if (key === 'compressors') { + value = Array.isArray(value) ? value : [value]; + + if (!value.every(c => c === 'snappy' || c === 'zlib')) { + throw new MongoParseError( + 'Value for `compressors` must be at least one of: `snappy`, `zlib`' + ); + } + } + + if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { + throw new MongoParseError( + `Value for authMechanism must be one of: ${Array.from(AUTH_MECHANISMS).join( + ', ' + )}, found: ${value}` + ); + } + + if (key === 'readpreference' && !ReadPreference.isValid(value)) { + throw new MongoParseError( + 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' + ); + } + + if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { + throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); + } + + // special cases + if (key === 'compressors' || key === 'zlibcompressionlevel') { + obj.compression = obj.compression || {}; + obj = obj.compression; + } + + if (key === 'authmechanismproperties') { + if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; + if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; + if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { + obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; + } + } + + if (key === 'readpreferencetags') { + value = Array.isArray(value) ? splitArrayOfMultipleReadPreferenceTags(value) : [value]; + } + + // set the actual value + if (options.caseTranslate && CASE_TRANSLATION[key]) { + obj[CASE_TRANSLATION[key]] = value; + return; + } + + obj[key] = value; +} + +const USERNAME_REQUIRED_MECHANISMS = new Set([ + 'GSSAPI', + 'MONGODB-CR', + 'PLAIN', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256' +]); + +function splitArrayOfMultipleReadPreferenceTags(value) { + const parsedTags = []; + + for (let i = 0; i < value.length; i++) { + parsedTags[i] = {}; + value[i].split(',').forEach(individualTag => { + const splitTag = individualTag.split(':'); + parsedTags[i][splitTag[0]] = splitTag[1]; + }); + } + + return parsedTags; +} + +/** + * Modifies the parsed connection string object taking into account expectations we + * have for authentication-related options. + * + * @param {object} parsed The parsed connection string result + * @return The parsed connection string result possibly modified for auth expectations + */ +function applyAuthExpectations(parsed) { + if (parsed.options == null) { + return; + } + + const options = parsed.options; + const authSource = options.authsource || options.authSource; + if (authSource != null) { + parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); + } + + const authMechanism = options.authmechanism || options.authMechanism; + if (authMechanism != null) { + if ( + USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && + (!parsed.auth || parsed.auth.username == null) + ) { + throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); + } + + if (authMechanism === 'GSSAPI') { + if (authSource != null && authSource !== '$external') { + throw new MongoParseError( + `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` + ); + } + + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + + if (authMechanism === 'MONGODB-AWS') { + if (authSource != null && authSource !== '$external') { + throw new MongoParseError( + `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` + ); + } + + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + + if (authMechanism === 'MONGODB-X509') { + if (parsed.auth && parsed.auth.password != null) { + throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); + } + + if (authSource != null && authSource !== '$external') { + throw new MongoParseError( + `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` + ); + } + + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + + if (authMechanism === 'PLAIN') { + if (parsed.auth && parsed.auth.db == null) { + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + } + } + + // default to `admin` if nothing else was resolved + if (parsed.auth && parsed.auth.db == null) { + parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); + } + + return parsed; +} + +/** + * Parses a query string according the connection string spec. + * + * @param {String} query The query string to parse + * @param {object} [options] The options used for options parsing + * @return {Object|Error} The parsed query string as an object, or an error if one was encountered + */ +function parseQueryString(query, options) { + const result = {}; + let parsedQueryString = qs.parse(query); + + checkTLSOptions(parsedQueryString); + + for (const key in parsedQueryString) { + const value = parsedQueryString[key]; + if (value === '' || value == null) { + throw new MongoParseError('Incomplete key value pair for option'); + } + + const normalizedKey = key.toLowerCase(); + const parsedValue = parseQueryStringItemValue(normalizedKey, value); + applyConnectionStringOption(result, normalizedKey, parsedValue, options); + } + + // special cases for known deprecated options + if (result.wtimeout && result.wtimeoutms) { + delete result.wtimeout; + console.warn('Unsupported option `wtimeout` specified'); + } + + return Object.keys(result).length ? result : null; +} + +/// Adds support for modern `tls` variants of out `ssl` options +function translateTLSOptions(queryString) { + if (queryString.tls) { + queryString.ssl = queryString.tls; + } + + if (queryString.tlsInsecure) { + queryString.checkServerIdentity = false; + queryString.sslValidate = false; + } else { + Object.assign(queryString, { + checkServerIdentity: queryString.tlsAllowInvalidHostnames ? false : true, + sslValidate: queryString.tlsAllowInvalidCertificates ? false : true + }); + } + + if (queryString.tlsCAFile) { + queryString.ssl = true; + queryString.sslCA = queryString.tlsCAFile; + } + + if (queryString.tlsCertificateKeyFile) { + queryString.ssl = true; + if (queryString.tlsCertificateFile) { + queryString.sslCert = queryString.tlsCertificateFile; + queryString.sslKey = queryString.tlsCertificateKeyFile; + } else { + queryString.sslKey = queryString.tlsCertificateKeyFile; + queryString.sslCert = queryString.tlsCertificateKeyFile; + } + } + + if (queryString.tlsCertificateKeyFilePassword) { + queryString.ssl = true; + queryString.sslPass = queryString.tlsCertificateKeyFilePassword; + } + + return queryString; +} + +/** + * Checks a query string for invalid tls options according to the URI options spec. + * + * @param {string} queryString The query string to check + * @throws {MongoParseError} + */ +function checkTLSOptions(queryString) { + const queryStringKeys = Object.keys(queryString); + if ( + queryStringKeys.indexOf('tlsInsecure') !== -1 && + (queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 || + queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1) + ) { + throw new MongoParseError( + 'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.' + ); + } + + const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys); + const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys); + + if (tlsValue != null && sslValue != null) { + if (tlsValue !== sslValue) { + throw new MongoParseError('All values of `tls` and `ssl` must be the same.'); + } + } +} + +/** + * Checks a query string to ensure all tls/ssl options are the same. + * + * @param {string} key The key (tls or ssl) to check + * @param {string} queryString The query string to check + * @throws {MongoParseError} + * @return The value of the tls/ssl option + */ +function assertTlsOptionsAreEqual(optionName, queryString, queryStringKeys) { + const queryStringHasTLSOption = queryStringKeys.indexOf(optionName) !== -1; + + let optionValue; + if (Array.isArray(queryString[optionName])) { + optionValue = queryString[optionName][0]; + } else { + optionValue = queryString[optionName]; + } + + if (queryStringHasTLSOption) { + if (Array.isArray(queryString[optionName])) { + const firstValue = queryString[optionName][0]; + queryString[optionName].forEach(tlsValue => { + if (tlsValue !== firstValue) { + throw new MongoParseError(`All values of ${optionName} must be the same.`); + } + }); + } + } + + return optionValue; +} + +const PROTOCOL_MONGODB = 'mongodb'; +const PROTOCOL_MONGODB_SRV = 'mongodb+srv'; +const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV]; + +/** + * Parses a MongoDB connection string + * + * @param {*} uri the MongoDB connection string to parse + * @param {object} [options] Optional settings. + * @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization + * @param {parseCallback} callback + */ +function parseConnectionString(uri, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { caseTranslate: true }, options); + + // Check for bad uris before we parse + try { + URL.parse(uri); + } catch (e) { + return callback(new MongoParseError('URI malformed, cannot be parsed')); + } + + const cap = uri.match(HOSTS_RX); + if (!cap) { + return callback(new MongoParseError('Invalid connection string')); + } + + const protocol = cap[1]; + if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { + return callback(new MongoParseError('Invalid protocol provided')); + } + + const dbAndQuery = cap[4].split('?'); + const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null; + const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null; + + let parsedOptions; + try { + parsedOptions = parseQueryString(query, options); + } catch (parseError) { + return callback(parseError); + } + + parsedOptions = Object.assign({}, parsedOptions, options); + + if (protocol === PROTOCOL_MONGODB_SRV) { + return parseSrvConnectionString(uri, parsedOptions, callback); + } + + const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; + if (parsedOptions.auth) { + // maintain support for legacy options passed into `MongoClient` + if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username; + if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user; + if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password; + } else { + if (parsedOptions.username) auth.username = parsedOptions.username; + if (parsedOptions.user) auth.username = parsedOptions.user; + if (parsedOptions.password) auth.password = parsedOptions.password; + } + + if (cap[4].split('?')[0].indexOf('@') !== -1) { + return callback(new MongoParseError('Unescaped slash in userinfo section')); + } + + const authorityParts = cap[3].split('@'); + if (authorityParts.length > 2) { + return callback(new MongoParseError('Unescaped at-sign in authority section')); + } + + if (authorityParts[0] == null || authorityParts[0] === '') { + return callback(new MongoParseError('No username provided in authority section')); + } + + if (authorityParts.length > 1) { + const authParts = authorityParts.shift().split(':'); + if (authParts.length > 2) { + return callback(new MongoParseError('Unescaped colon in authority section')); + } + + if (authParts[0] === '') { + return callback(new MongoParseError('Invalid empty username provided')); + } + + if (!auth.username) auth.username = qs.unescape(authParts[0]); + if (!auth.password) auth.password = authParts[1] ? qs.unescape(authParts[1]) : null; + } + + let hostParsingError = null; + const hosts = authorityParts + .shift() + .split(',') + .map(host => { + let parsedHost = URL.parse(`mongodb://${host}`); + if (parsedHost.path === '/:') { + hostParsingError = new MongoParseError('Double colon in host identifier'); + return null; + } + + // heuristically determine if we're working with a domain socket + if (host.match(/\.sock/)) { + parsedHost.hostname = qs.unescape(host); + parsedHost.port = null; + } + + if (Number.isNaN(parsedHost.port)) { + hostParsingError = new MongoParseError('Invalid port (non-numeric string)'); + return; + } + + const result = { + host: parsedHost.hostname, + port: parsedHost.port ? parseInt(parsedHost.port) : 27017 + }; + + if (result.port === 0) { + hostParsingError = new MongoParseError('Invalid port (zero) with hostname'); + return; + } + + if (result.port > 65535) { + hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname'); + return; + } + + if (result.port < 0) { + hostParsingError = new MongoParseError('Invalid port (negative number)'); + return; + } + + return result; + }) + .filter(host => !!host); + + if (hostParsingError) { + return callback(hostParsingError); + } + + if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) { + return callback(new MongoParseError('No hostname or hostnames provided in connection string')); + } + + const directConnection = !!parsedOptions.directConnection; + if (directConnection && hosts.length !== 1) { + // If the option is set to true, the driver MUST validate that there is exactly one host given + // in the host list in the URI, and fail client creation otherwise. + return callback(new MongoParseError('directConnection option requires exactly one host')); + } + + // NOTE: this behavior will go away in v4.0, we will always auto discover there + if ( + parsedOptions.directConnection == null && + hosts.length === 1 && + parsedOptions.replicaSet == null + ) { + parsedOptions.directConnection = true; + } + + const result = { + hosts: hosts, + auth: auth.db || auth.username ? auth : null, + options: Object.keys(parsedOptions).length ? parsedOptions : null + }; + + if (result.auth && result.auth.db) { + result.defaultDatabase = result.auth.db; + } else { + result.defaultDatabase = 'test'; + } + + // support modern `tls` variants to SSL options + result.options = translateTLSOptions(result.options); + + try { + applyAuthExpectations(result); + } catch (authError) { + return callback(authError); + } + + callback(null, result); +} + +module.exports = parseConnectionString; + + +/***/ }), + +/***/ 1178: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const os = __webpack_require__(2087); +const crypto = __webpack_require__(6417); +const requireOptional = __webpack_require__(6985); + +/** + * Generate a UUIDv4 + */ +const uuidV4 = () => { + const result = crypto.randomBytes(16); + result[6] = (result[6] & 0x0f) | 0x40; + result[8] = (result[8] & 0x3f) | 0x80; + return result; +}; + +/** + * Relays events for a given listener and emitter + * + * @param {EventEmitter} listener the EventEmitter to listen to the events from + * @param {EventEmitter} emitter the EventEmitter to relay the events to + */ +function relayEvents(listener, emitter, events) { + events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); +} + +function retrieveKerberos() { + let kerberos; + + try { + kerberos = requireOptional('kerberos'); + } catch (err) { + if (err.code === 'MODULE_NOT_FOUND') { + throw new Error('The `kerberos` module was not found. Please install it and try again.'); + } + + throw err; + } + + return kerberos; +} + +// Throw an error if an attempt to use EJSON is made when it is not installed +const noEJSONError = function() { + throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.'); +}; + +// Facilitate loading EJSON optionally +function retrieveEJSON() { + let EJSON = null; + try { + EJSON = requireOptional('mongodb-extjson'); + } catch (error) {} // eslint-disable-line + if (!EJSON) { + EJSON = { + parse: noEJSONError, + deserialize: noEJSONError, + serialize: noEJSONError, + stringify: noEJSONError, + setBSONModule: noEJSONError, + BSON: noEJSONError + }; + } + + return EJSON; +} + +/** + * A helper function for determining `maxWireVersion` between legacy and new topology + * instances + * + * @private + * @param {(Topology|Server)} topologyOrServer + */ +function maxWireVersion(topologyOrServer) { + if (topologyOrServer) { + if (topologyOrServer.ismaster) { + return topologyOrServer.ismaster.maxWireVersion; + } + + if (typeof topologyOrServer.lastIsMaster === 'function') { + const lastIsMaster = topologyOrServer.lastIsMaster(); + if (lastIsMaster) { + return lastIsMaster.maxWireVersion; + } + } + + if (topologyOrServer.description) { + return topologyOrServer.description.maxWireVersion; + } + } + + return 0; +} + +/* + * Checks that collation is supported by server. + * + * @param {Server} [server] to check against + * @param {object} [cmd] object where collation may be specified + * @param {function} [callback] callback function + * @return true if server does not support collation + */ +function collationNotSupported(server, cmd) { + return cmd && cmd.collation && maxWireVersion(server) < 5; +} + +/** + * Checks if a given value is a Promise + * + * @param {*} maybePromise + * @return true if the provided value is a Promise + */ +function isPromiseLike(maybePromise) { + return maybePromise && typeof maybePromise.then === 'function'; +} + +/** + * Applies the function `eachFn` to each item in `arr`, in parallel. + * + * @param {array} arr an array of items to asynchronusly iterate over + * @param {function} eachFn A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete. + * @param {function} callback The callback called after every item has been iterated + */ +function eachAsync(arr, eachFn, callback) { + arr = arr || []; + + let idx = 0; + let awaiting = 0; + for (idx = 0; idx < arr.length; ++idx) { + awaiting++; + eachFn(arr[idx], eachCallback); + } + + if (awaiting === 0) { + callback(); + return; + } + + function eachCallback(err) { + awaiting--; + if (err) { + callback(err); + return; + } + + if (idx === arr.length && awaiting <= 0) { + callback(); + } + } +} + +function eachAsyncSeries(arr, eachFn, callback) { + arr = arr || []; + + let idx = 0; + let awaiting = arr.length; + if (awaiting === 0) { + callback(); + return; + } + + function eachCallback(err) { + idx++; + awaiting--; + if (err) { + callback(err); + return; + } + + if (idx === arr.length && awaiting <= 0) { + callback(); + return; + } + + eachFn(arr[idx], eachCallback); + } + + eachFn(arr[idx], eachCallback); +} + +function isUnifiedTopology(topology) { + return topology.description != null; +} + +function arrayStrictEqual(arr, arr2) { + if (!Array.isArray(arr) || !Array.isArray(arr2)) { + return false; + } + + return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]); +} + +function tagsStrictEqual(tags, tags2) { + const tagsKeys = Object.keys(tags); + const tags2Keys = Object.keys(tags2); + return tagsKeys.length === tags2Keys.length && tagsKeys.every(key => tags2[key] === tags[key]); +} + +function errorStrictEqual(lhs, rhs) { + if (lhs === rhs) { + return true; + } + + if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) { + return false; + } + + if (lhs.constructor.name !== rhs.constructor.name) { + return false; + } + + if (lhs.message !== rhs.message) { + return false; + } + + return true; +} + +function makeStateMachine(stateTable) { + return function stateTransition(target, newState) { + const legalStates = stateTable[target.s.state]; + if (legalStates && legalStates.indexOf(newState) < 0) { + throw new TypeError( + `illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]` + ); + } + + target.emit('stateChanged', target.s.state, newState); + target.s.state = newState; + }; +} + +function makeClientMetadata(options) { + options = options || {}; + + const metadata = { + driver: { + name: 'nodejs', + version: __webpack_require__(3225)/* .version */ .i8 + }, + os: { + type: os.type(), + name: process.platform, + architecture: process.arch, + version: os.release() + }, + platform: `'Node.js ${process.version}, ${os.endianness} (${ + options.useUnifiedTopology ? 'unified' : 'legacy' + })` + }; + + // support optionally provided wrapping driver info + if (options.driverInfo) { + if (options.driverInfo.name) { + metadata.driver.name = `${metadata.driver.name}|${options.driverInfo.name}`; + } + + if (options.driverInfo.version) { + metadata.version = `${metadata.driver.version}|${options.driverInfo.version}`; + } + + if (options.driverInfo.platform) { + metadata.platform = `${metadata.platform}|${options.driverInfo.platform}`; + } + } + + if (options.appname) { + // MongoDB requires the appname not exceed a byte length of 128 + const buffer = Buffer.from(options.appname); + metadata.application = { + name: buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname + }; + } + + return metadata; +} + +const noop = () => {}; + +module.exports = { + uuidV4, + relayEvents, + collationNotSupported, + retrieveEJSON, + retrieveKerberos, + maxWireVersion, + isPromiseLike, + eachAsync, + eachAsyncSeries, + isUnifiedTopology, + arrayStrictEqual, + tagsStrictEqual, + errorStrictEqual, + makeStateMachine, + makeClientMetadata, + noop +}; + + +/***/ }), + +/***/ 7276: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Query = __webpack_require__(9814).Query; +const Msg = __webpack_require__(8988).Msg; +const MongoError = __webpack_require__(3111).MongoError; +const getReadPreference = __webpack_require__(7272).getReadPreference; +const isSharded = __webpack_require__(7272).isSharded; +const databaseNamespace = __webpack_require__(7272).databaseNamespace; +const isTransactionCommand = __webpack_require__(1707).isTransactionCommand; +const applySession = __webpack_require__(5474).applySession; +const MongoNetworkError = __webpack_require__(3111).MongoNetworkError; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; + +function isClientEncryptionEnabled(server) { + const wireVersion = maxWireVersion(server); + return wireVersion && server.autoEncrypter; +} + +function command(server, ns, cmd, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (cmd == null) { + return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); + } + + if (!isClientEncryptionEnabled(server)) { + _command(server, ns, cmd, options, callback); + return; + } + + const wireVersion = maxWireVersion(server); + if (typeof wireVersion !== 'number' || wireVersion < 8) { + callback(new MongoError('Auto-encryption requires a minimum MongoDB version of 4.2')); + return; + } + + _cryptCommand(server, ns, cmd, options, callback); +} + +function _command(server, ns, cmd, options, callback) { + const bson = server.s.bson; + const pool = server.s.pool; + const readPreference = getReadPreference(cmd, options); + const shouldUseOpMsg = supportsOpMsg(server); + const session = options.session; + + let clusterTime = server.clusterTime; + let finalCmd = Object.assign({}, cmd); + if (hasSessionSupport(server) && session) { + if ( + session.clusterTime && + session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime) + ) { + clusterTime = session.clusterTime; + } + + const err = applySession(session, finalCmd, options); + if (err) { + return callback(err); + } + } + + // if we have a known cluster time, gossip it + if (clusterTime) { + finalCmd.$clusterTime = clusterTime; + } + + if (isSharded(server) && !shouldUseOpMsg && readPreference && readPreference.mode !== 'primary') { + finalCmd = { + $query: finalCmd, + $readPreference: readPreference.toJSON() + }; + } + + const commandOptions = Object.assign( + { + command: true, + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false + }, + options + ); + + // This value is not overridable + commandOptions.slaveOk = readPreference.slaveOk(); + + const cmdNs = `${databaseNamespace(ns)}.$cmd`; + const message = shouldUseOpMsg + ? new Msg(bson, cmdNs, finalCmd, commandOptions) + : new Query(bson, cmdNs, finalCmd, commandOptions); + + const inTransaction = session && (session.inTransaction() || isTransactionCommand(finalCmd)); + const commandResponseHandler = inTransaction + ? function(err) { + // We need to add a TransientTransactionError errorLabel, as stated in the transaction spec. + if ( + err && + err instanceof MongoNetworkError && + !err.hasErrorLabel('TransientTransactionError') + ) { + err.addErrorLabel('TransientTransactionError'); + } + + if ( + !cmd.commitTransaction && + err && + err instanceof MongoError && + err.hasErrorLabel('TransientTransactionError') + ) { + session.transaction.unpinServer(); + } + + return callback.apply(null, arguments); + } + : callback; + + try { + pool.write(message, commandOptions, commandResponseHandler); + } catch (err) { + commandResponseHandler(err); + } +} + +function hasSessionSupport(topology) { + if (topology == null) return false; + if (topology.description) { + return topology.description.maxWireVersion >= 6; + } + + return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6; +} + +function supportsOpMsg(topologyOrServer) { + const description = topologyOrServer.ismaster + ? topologyOrServer.ismaster + : topologyOrServer.description; + + if (description == null) { + return false; + } + + return description.maxWireVersion >= 6 && description.__nodejs_mock_server__ == null; +} + +function _cryptCommand(server, ns, cmd, options, callback) { + const autoEncrypter = server.autoEncrypter; + function commandResponseHandler(err, response) { + if (err || response == null) { + callback(err, response); + return; + } + + autoEncrypter.decrypt(response.result, options, (err, decrypted) => { + if (err) { + callback(err, null); + return; + } + + response.result = decrypted; + response.message.documents = [decrypted]; + callback(null, response); + }); + } + + autoEncrypter.encrypt(ns, cmd, options, (err, encrypted) => { + if (err) { + callback(err, null); + return; + } + + _command(server, ns, encrypted, options, commandResponseHandler); + }); +} + +module.exports = command; + + +/***/ }), + +/***/ 7793: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Snappy = __webpack_require__(7746).retrieveSnappy(); +const zlib = __webpack_require__(8761); + +const compressorIDs = { + snappy: 1, + zlib: 2 +}; + +const uncompressibleCommands = new Set([ + 'ismaster', + 'saslStart', + 'saslContinue', + 'getnonce', + 'authenticate', + 'createUser', + 'updateUser', + 'copydbSaslStart', + 'copydbgetnonce', + 'copydb' +]); + +// Facilitate compressing a message using an agreed compressor +function compress(self, dataToBeCompressed, callback) { + switch (self.options.agreedCompressor) { + case 'snappy': + Snappy.compress(dataToBeCompressed, callback); + break; + case 'zlib': + // Determine zlibCompressionLevel + var zlibOptions = {}; + if (self.options.zlibCompressionLevel) { + zlibOptions.level = self.options.zlibCompressionLevel; + } + zlib.deflate(dataToBeCompressed, zlibOptions, callback); + break; + default: + throw new Error( + 'Attempt to compress message using unknown compressor "' + + self.options.agreedCompressor + + '".' + ); + } +} + +// Decompress a message using the given compressor +function decompress(compressorID, compressedData, callback) { + if (compressorID < 0 || compressorID > compressorIDs.length) { + throw new Error( + 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' + + compressorID + + ')' + ); + } + switch (compressorID) { + case compressorIDs.snappy: + Snappy.uncompress(compressedData, callback); + break; + case compressorIDs.zlib: + zlib.inflate(compressedData, callback); + break; + default: + callback(null, compressedData); + } +} + +module.exports = { + compressorIDs, + uncompressibleCommands, + compress, + decompress +}; + + +/***/ }), + +/***/ 7161: +/***/ ((module) => { + +"use strict"; + + +const MIN_SUPPORTED_SERVER_VERSION = '2.6'; +const MAX_SUPPORTED_SERVER_VERSION = '4.4'; +const MIN_SUPPORTED_WIRE_VERSION = 2; +const MAX_SUPPORTED_WIRE_VERSION = 9; + +module.exports = { + MIN_SUPPORTED_SERVER_VERSION, + MAX_SUPPORTED_SERVER_VERSION, + MIN_SUPPORTED_WIRE_VERSION, + MAX_SUPPORTED_WIRE_VERSION +}; + + +/***/ }), + +/***/ 2845: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const GetMore = __webpack_require__(9814).GetMore; +const retrieveBSON = __webpack_require__(7746).retrieveBSON; +const MongoError = __webpack_require__(3111).MongoError; +const MongoNetworkError = __webpack_require__(3111).MongoNetworkError; +const BSON = retrieveBSON(); +const Long = BSON.Long; +const collectionNamespace = __webpack_require__(7272).collectionNamespace; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const applyCommonQueryOptions = __webpack_require__(7272).applyCommonQueryOptions; +const command = __webpack_require__(7276); + +function getMore(server, ns, cursorState, batchSize, options, callback) { + options = options || {}; + + const wireVersion = maxWireVersion(server); + function queryCallback(err, result) { + if (err) return callback(err); + const response = result.message; + + // If we have a timed out query or a cursor that was killed + if (response.cursorNotFound) { + return callback(new MongoNetworkError('cursor killed or timed out'), null); + } + + if (wireVersion < 4) { + const cursorId = + typeof response.cursorId === 'number' + ? Long.fromNumber(response.cursorId) + : response.cursorId; + + cursorState.documents = response.documents; + cursorState.cursorId = cursorId; + + callback(null, null, response.connection); + return; + } + + // We have an error detected + if (response.documents[0].ok === 0) { + return callback(new MongoError(response.documents[0])); + } + + // Ensure we have a Long valid cursor id + const cursorId = + typeof response.documents[0].cursor.id === 'number' + ? Long.fromNumber(response.documents[0].cursor.id) + : response.documents[0].cursor.id; + + cursorState.documents = response.documents[0].cursor.nextBatch; + cursorState.cursorId = cursorId; + + callback(null, response.documents[0], response.connection); + } + + if (wireVersion < 4) { + const bson = server.s.bson; + const getMoreOp = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize }); + const queryOptions = applyCommonQueryOptions({}, cursorState); + server.s.pool.write(getMoreOp, queryOptions, queryCallback); + return; + } + + const cursorId = + cursorState.cursorId instanceof Long + ? cursorState.cursorId + : Long.fromNumber(cursorState.cursorId); + + const getMoreCmd = { + getMore: cursorId, + collection: collectionNamespace(ns), + batchSize: Math.abs(batchSize) + }; + + if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; + } + + const commandOptions = Object.assign( + { + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch' + }, + options + ); + + if (cursorState.session) { + commandOptions.session = cursorState.session; + } + + command(server, ns, getMoreCmd, commandOptions, queryCallback); +} + +module.exports = getMore; + + +/***/ }), + +/***/ 9206: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const writeCommand = __webpack_require__(779); + +module.exports = { + insert: function insert(server, ns, ops, options, callback) { + writeCommand(server, 'insert', 'documents', ns, ops, options, callback); + }, + update: function update(server, ns, ops, options, callback) { + writeCommand(server, 'update', 'updates', ns, ops, options, callback); + }, + remove: function remove(server, ns, ops, options, callback) { + writeCommand(server, 'delete', 'deletes', ns, ops, options, callback); + }, + killCursors: __webpack_require__(6044), + getMore: __webpack_require__(2845), + query: __webpack_require__(1820), + command: __webpack_require__(7276) +}; + + +/***/ }), + +/***/ 6044: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const KillCursor = __webpack_require__(9814).KillCursor; +const MongoError = __webpack_require__(3111).MongoError; +const MongoNetworkError = __webpack_require__(3111).MongoNetworkError; +const collectionNamespace = __webpack_require__(7272).collectionNamespace; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const command = __webpack_require__(7276); + +function killCursors(server, ns, cursorState, callback) { + callback = typeof callback === 'function' ? callback : () => {}; + const cursorId = cursorState.cursorId; + + if (maxWireVersion(server) < 4) { + const bson = server.s.bson; + const pool = server.s.pool; + const killCursor = new KillCursor(bson, ns, [cursorId]); + const options = { + immediateRelease: true, + noResponse: true + }; + + if (typeof cursorState.session === 'object') { + options.session = cursorState.session; + } + + if (pool && pool.isConnected()) { + try { + pool.write(killCursor, options, callback); + } catch (err) { + if (typeof callback === 'function') { + callback(err, null); + } else { + console.warn(err); + } + } + } + + return; + } + + const killCursorCmd = { + killCursors: collectionNamespace(ns), + cursors: [cursorId] + }; + + const options = {}; + if (typeof cursorState.session === 'object') options.session = cursorState.session; + + command(server, ns, killCursorCmd, options, (err, result) => { + if (err) { + return callback(err); + } + + const response = result.message; + if (response.cursorNotFound) { + return callback(new MongoNetworkError('cursor killed or timed out'), null); + } + + if (!Array.isArray(response.documents) || response.documents.length === 0) { + return callback( + new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`) + ); + } + + callback(null, response.documents[0]); + }); +} + +module.exports = killCursors; + + +/***/ }), + +/***/ 1820: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Query = __webpack_require__(9814).Query; +const MongoError = __webpack_require__(3111).MongoError; +const getReadPreference = __webpack_require__(7272).getReadPreference; +const collectionNamespace = __webpack_require__(7272).collectionNamespace; +const isSharded = __webpack_require__(7272).isSharded; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const applyCommonQueryOptions = __webpack_require__(7272).applyCommonQueryOptions; +const command = __webpack_require__(7276); + +function query(server, ns, cmd, cursorState, options, callback) { + options = options || {}; + if (cursorState.cursorId != null) { + return callback(); + } + + if (cmd == null) { + return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); + } + + if (maxWireVersion(server) < 4) { + const query = prepareLegacyFindQuery(server, ns, cmd, cursorState, options); + const queryOptions = applyCommonQueryOptions({}, cursorState); + if (typeof query.documentsReturnedIn === 'string') { + queryOptions.documentsReturnedIn = query.documentsReturnedIn; + } + + server.s.pool.write(query, queryOptions, callback); + return; + } + + const readPreference = getReadPreference(cmd, options); + const findCmd = prepareFindCommand(server, ns, cmd, cursorState, options); + + // NOTE: This actually modifies the passed in cmd, and our code _depends_ on this + // side-effect. Change this ASAP + cmd.virtual = false; + + const commandOptions = Object.assign( + { + documentsReturnedIn: 'firstBatch', + numberToReturn: 1, + slaveOk: readPreference.slaveOk() + }, + options + ); + + if (cmd.readPreference) { + commandOptions.readPreference = readPreference; + } + + if (cursorState.session) { + commandOptions.session = cursorState.session; + } + + command(server, ns, findCmd, commandOptions, callback); +} + +function prepareFindCommand(server, ns, cmd, cursorState) { + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + let findCmd = { + find: collectionNamespace(ns) + }; + + if (cmd.query) { + if (cmd.query['$query']) { + findCmd.filter = cmd.query['$query']; + } else { + findCmd.filter = cmd.query; + } + } + + let sortValue = cmd.sort; + if (Array.isArray(sortValue)) { + const sortObject = {}; + + if (sortValue.length > 0 && !Array.isArray(sortValue[0])) { + let sortDirection = sortValue[1]; + if (sortDirection === 'asc') { + sortDirection = 1; + } else if (sortDirection === 'desc') { + sortDirection = -1; + } + + sortObject[sortValue[0]] = sortDirection; + } else { + for (let i = 0; i < sortValue.length; i++) { + let sortDirection = sortValue[i][1]; + if (sortDirection === 'asc') { + sortDirection = 1; + } else if (sortDirection === 'desc') { + sortDirection = -1; + } + + sortObject[sortValue[i][0]] = sortDirection; + } + } + + sortValue = sortObject; + } + + if (typeof cmd.allowDiskUse === 'boolean') { + findCmd.allowDiskUse = cmd.allowDiskUse; + } + + if (cmd.sort) findCmd.sort = sortValue; + if (cmd.fields) findCmd.projection = cmd.fields; + if (cmd.hint) findCmd.hint = cmd.hint; + if (cmd.skip) findCmd.skip = cmd.skip; + if (cmd.limit) findCmd.limit = cmd.limit; + if (cmd.limit < 0) { + findCmd.limit = Math.abs(cmd.limit); + findCmd.singleBatch = true; + } + + if (typeof cmd.batchSize === 'number') { + if (cmd.batchSize < 0) { + if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { + findCmd.limit = Math.abs(cmd.batchSize); + } + + findCmd.singleBatch = true; + } + + findCmd.batchSize = Math.abs(cmd.batchSize); + } + + if (cmd.comment) findCmd.comment = cmd.comment; + if (cmd.maxScan) findCmd.maxScan = cmd.maxScan; + if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; + if (cmd.min) findCmd.min = cmd.min; + if (cmd.max) findCmd.max = cmd.max; + findCmd.returnKey = cmd.returnKey ? cmd.returnKey : false; + findCmd.showRecordId = cmd.showDiskLoc ? cmd.showDiskLoc : false; + if (cmd.snapshot) findCmd.snapshot = cmd.snapshot; + if (cmd.tailable) findCmd.tailable = cmd.tailable; + if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; + if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; + if (cmd.awaitData) findCmd.awaitData = cmd.awaitData; + if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; + if (cmd.partial) findCmd.partial = cmd.partial; + if (cmd.collation) findCmd.collation = cmd.collation; + if (cmd.readConcern) findCmd.readConcern = cmd.readConcern; + + // If we have explain, we need to rewrite the find command + // to wrap it in the explain command + if (cmd.explain) { + findCmd = { + explain: findCmd + }; + } + + return findCmd; +} + +function prepareLegacyFindQuery(server, ns, cmd, cursorState, options) { + options = options || {}; + const bson = server.s.bson; + const readPreference = getReadPreference(cmd, options); + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + + let numberToReturn = 0; + if ( + cursorState.limit < 0 || + (cursorState.limit !== 0 && cursorState.limit < cursorState.batchSize) || + (cursorState.limit > 0 && cursorState.batchSize === 0) + ) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + const numberToSkip = cursorState.skip || 0; + + const findCmd = {}; + if (isSharded(server) && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + } + + if (cmd.sort) findCmd['$orderby'] = cmd.sort; + if (cmd.hint) findCmd['$hint'] = cmd.hint; + if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot; + if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey; + if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan; + if (cmd.min) findCmd['$min'] = cmd.min; + if (cmd.max) findCmd['$max'] = cmd.max; + if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc; + if (cmd.comment) findCmd['$comment'] = cmd.comment; + if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS; + if (cmd.explain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(cmd.limit || 0); + findCmd['$explain'] = true; + } + + findCmd['$query'] = cmd.query; + if (cmd.readConcern && cmd.readConcern.level !== 'local') { + throw new MongoError( + `server find command does not support a readConcern level of ${cmd.readConcern.level}` + ); + } + + if (cmd.readConcern) { + cmd = Object.assign({}, cmd); + delete cmd['readConcern']; + } + + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + + const query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, + numberToReturn: numberToReturn, + pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined, + checkKeys: false, + returnFieldSelector: cmd.fields, + serializeFunctions: serializeFunctions, + ignoreUndefined: ignoreUndefined + }); + + if (typeof cmd.tailable === 'boolean') query.tailable = cmd.tailable; + if (typeof cmd.oplogReplay === 'boolean') query.oplogReplay = cmd.oplogReplay; + if (typeof cmd.noCursorTimeout === 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if (typeof cmd.awaitData === 'boolean') query.awaitData = cmd.awaitData; + if (typeof cmd.partial === 'boolean') query.partial = cmd.partial; + + query.slaveOk = readPreference.slaveOk(); + return query; +} + +module.exports = query; + + +/***/ }), + +/***/ 7272: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const ReadPreference = __webpack_require__(4485); +const MongoError = __webpack_require__(3111).MongoError; +const ServerType = __webpack_require__(2291).ServerType; +const TopologyDescription = __webpack_require__(7962).TopologyDescription; + +const MESSAGE_HEADER_SIZE = 16; +const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID + +// OPCODE Numbers +// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes +var opcodes = { + OP_REPLY: 1, + OP_UPDATE: 2001, + OP_INSERT: 2002, + OP_QUERY: 2004, + OP_GETMORE: 2005, + OP_DELETE: 2006, + OP_KILL_CURSORS: 2007, + OP_COMPRESSED: 2012, + OP_MSG: 2013 +}; + +var getReadPreference = function(cmd, options) { + // Default to command version of the readPreference + var readPreference = cmd.readPreference || new ReadPreference('primary'); + // If we have an option readPreference override the command one + if (options.readPreference) { + readPreference = options.readPreference; + } + + if (typeof readPreference === 'string') { + readPreference = new ReadPreference(readPreference); + } + + if (!(readPreference instanceof ReadPreference)) { + throw new MongoError('read preference must be a ReadPreference instance'); + } + + return readPreference; +}; + +// Parses the header of a wire protocol message +var parseHeader = function(message) { + return { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; +}; + +function applyCommonQueryOptions(queryOptions, options) { + Object.assign(queryOptions, { + raw: typeof options.raw === 'boolean' ? options.raw : false, + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, + fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false + }); + + if (typeof options.socketTimeout === 'number') { + queryOptions.socketTimeout = options.socketTimeout; + } + + if (options.session) { + queryOptions.session = options.session; + } + + if (typeof options.documentsReturnedIn === 'string') { + queryOptions.documentsReturnedIn = options.documentsReturnedIn; + } + + return queryOptions; +} + +function isSharded(topologyOrServer) { + if (topologyOrServer.type === 'mongos') return true; + if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) { + return true; + } + + // NOTE: This is incredibly inefficient, and should be removed once command construction + // happens based on `Server` not `Topology`. + if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) { + const servers = Array.from(topologyOrServer.description.servers.values()); + return servers.some(server => server.type === ServerType.Mongos); + } + + return false; +} + +function databaseNamespace(ns) { + return ns.split('.')[0]; +} +function collectionNamespace(ns) { + return ns + .split('.') + .slice(1) + .join('.'); +} + +module.exports = { + getReadPreference, + MESSAGE_HEADER_SIZE, + COMPRESSION_DETAILS_SIZE, + opcodes, + parseHeader, + applyCommonQueryOptions, + isSharded, + databaseNamespace, + collectionNamespace +}; + + +/***/ }), + +/***/ 779: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const MongoError = __webpack_require__(3111).MongoError; +const collectionNamespace = __webpack_require__(7272).collectionNamespace; +const command = __webpack_require__(7276); + +function writeCommand(server, type, opsField, ns, ops, options, callback) { + if (ops.length === 0) throw new MongoError(`${type} must contain at least one document`); + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const writeConcern = options.writeConcern; + + const writeCommand = {}; + writeCommand[type] = collectionNamespace(ns); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + if (writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + if (options.collation) { + for (let i = 0; i < writeCommand[opsField].length; i++) { + if (!writeCommand[opsField][i].collation) { + writeCommand[opsField][i].collation = options.collation; + } + } + } + + if (options.bypassDocumentValidation === true) { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + const commandOptions = Object.assign( + { + checkKeys: type === 'insert', + numberToReturn: 1 + }, + options + ); + + command(server, ns, writeCommand, commandOptions, callback); +} + +module.exports = writeCommand; + + +/***/ }), + +/***/ 7159: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Transform = __webpack_require__(2413).Transform; +const PassThrough = __webpack_require__(2413).PassThrough; +const deprecate = __webpack_require__(1669).deprecate; +const handleCallback = __webpack_require__(1371).handleCallback; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const MongoError = __webpack_require__(3994).MongoError; +const CoreCursor = __webpack_require__(4847).CoreCursor; +const CursorState = __webpack_require__(4847).CursorState; +const Map = __webpack_require__(3994).BSON.Map; +const maybePromise = __webpack_require__(1371).maybePromise; +const executeOperation = __webpack_require__(2548); +const formattedOrderClause = __webpack_require__(1371).formattedOrderClause; + +const each = __webpack_require__(3554).each; +const CountOperation = __webpack_require__(7885); + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * + * **CURSORS Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the code module + * @external CoreCursor + * @external Readable + */ + +// Flags allowed for cursor +const flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; +const fields = ['numberOfRetries', 'tailableRetryInterval']; + +/** + * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class Cursor + * @extends external:CoreCursor + * @extends external:Readable + * @property {string} sortValue Cursor query sort setting. + * @property {boolean} timeout Is Cursor able to time out. + * @property {ReadPreference} readPreference Get cursor ReadPreference. + * @fires Cursor#data + * @fires Cursor#end + * @fires Cursor#close + * @fires Cursor#readable + * @return {Cursor} a Cursor instance. + * @example + * Cursor cursor options. + * + * collection.find({}).project({a:1}) // Create a projection of field a + * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 + * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 + * collection.find({}).filter({a:1}) // Set query on the cursor + * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries + * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable + * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout + * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData + * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial + * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} + * collection.find({}).max(10) // Set the cursor max + * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS + * collection.find({}).min(100) // Set the cursor min + * collection.find({}).returnKey(true) // Set the cursor returnKey + * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference + * collection.find({}).showRecordId(true) // Set the cursor showRecordId + * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query + * collection.find({}).hint('a_1') // Set the cursor hint + * + * All options are chainable, so one can do the following. + * + * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) + */ +class Cursor extends CoreCursor { + constructor(topology, ns, cmd, options) { + super(topology, ns, cmd, options); + if (this.operation) { + options = this.operation.options; + } + + // Tailable cursor options + const numberOfRetries = options.numberOfRetries || 5; + const tailableRetryInterval = options.tailableRetryInterval || 500; + const currentNumberOfRetries = numberOfRetries; + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Internal cursor state + this.s = { + // Tailable cursor options + numberOfRetries: numberOfRetries, + tailableRetryInterval: tailableRetryInterval, + currentNumberOfRetries: currentNumberOfRetries, + // State + state: CursorState.INIT, + // Promise library + promiseLibrary, + // explicitlyIgnoreSession + explicitlyIgnoreSession: !!options.explicitlyIgnoreSession + }; + + // Optional ClientSession + if (!options.explicitlyIgnoreSession && options.session) { + this.cursorState.session = options.session; + } + + // Translate correctly + if (this.options.noCursorTimeout === true) { + this.addCursorFlag('noCursorTimeout', true); + } + + // Get the batchSize + let batchSize = 1000; + if (this.cmd.cursor && this.cmd.cursor.batchSize) { + batchSize = this.cmd.cursor.batchSize; + } else if (options.cursor && options.cursor.batchSize) { + batchSize = options.cursor.batchSize; + } else if (typeof options.batchSize === 'number') { + batchSize = options.batchSize; + } + + // Set the batchSize + this.setCursorBatchSize(batchSize); + } + + get readPreference() { + if (this.operation) { + return this.operation.readPreference; + } + + return this.options.readPreference; + } + + get sortValue() { + return this.cmd.sort; + } + + _initializeCursor(callback) { + if (this.operation && this.operation.session != null) { + this.cursorState.session = this.operation.session; + } else { + // implicitly create a session if one has not been provided + if ( + !this.s.explicitlyIgnoreSession && + !this.cursorState.session && + this.topology.hasSessionSupport() + ) { + this.cursorState.session = this.topology.startSession({ owner: this }); + + if (this.operation) { + this.operation.session = this.cursorState.session; + } + } + } + + super._initializeCursor(callback); + } + + /** + * Check if there is any document still available in the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + hasNext(callback) { + if (this.s.state === CursorState.CLOSED || (this.isDead && this.isDead())) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + return maybePromise(this, callback, cb => { + const cursor = this; + if (cursor.isNotified()) { + return cb(null, false); + } + + cursor._next((err, doc) => { + if (err) return cb(err); + if (doc == null || cursor.s.state === Cursor.CLOSED || cursor.isDead()) { + return cb(null, false); + } + + cursor.s.state = CursorState.OPEN; + + // NODE-2482: merge this into the core cursor implementation + cursor.cursorState.cursorIndex--; + if (cursor.cursorState.limit > 0) { + cursor.cursorState.currentLimit--; + } + + cb(null, true); + }); + }); + } + + /** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + next(callback) { + return maybePromise(this, callback, cb => { + const cursor = this; + if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) { + cb(MongoError.create({ message: 'Cursor is closed', driver: true })); + return; + } + + if (cursor.s.state === CursorState.INIT && cursor.cmd.sort) { + try { + cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); + } catch (err) { + return cb(err); + } + } + + cursor._next((err, doc) => { + if (err) return cb(err); + cursor.s.state = CursorState.OPEN; + cb(null, doc); + }); + }); + } + + /** + * Set the cursor query + * @method + * @param {object} filter The filter object used for the cursor. + * @return {Cursor} + */ + filter(filter) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.query = filter; + return this; + } + + /** + * Set the cursor maxScan + * @method + * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query + * @deprecated as of MongoDB 4.0 + * @return {Cursor} + */ + maxScan(maxScan) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.maxScan = maxScan; + return this; + } + + /** + * Set the cursor hint + * @method + * @param {object} hint If specified, then the query system will only consider plans using the hinted index. + * @return {Cursor} + */ + hint(hint) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.hint = hint; + return this; + } + + /** + * Set the cursor min + * @method + * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + * @return {Cursor} + */ + min(min) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.min = min; + return this; + } + + /** + * Set the cursor max + * @method + * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + * @return {Cursor} + */ + max(max) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.max = max; + return this; + } + + /** + * Set the cursor returnKey. If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * @method + * @param {bool} returnKey the returnKey value. + * @return {Cursor} + */ + returnKey(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.returnKey = value; + return this; + } + + /** + * Set the cursor showRecordId + * @method + * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + * @return {Cursor} + */ + showRecordId(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.showDiskLoc = value; + return this; + } + + /** + * Set the cursor snapshot + * @method + * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. + * @deprecated as of MongoDB 4.0 + * @return {Cursor} + */ + snapshot(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.snapshot = value; + return this; + } + + /** + * Set a node.js specific cursor option + * @method + * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. + * @param {object} value The field value. + * @throws {MongoError} + * @return {Cursor} + */ + setCursorOption(field, value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (fields.indexOf(field) === -1) { + throw MongoError.create({ + message: `option ${field} is not a supported option ${fields}`, + driver: true + }); + } + + this.s[field] = value; + if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value; + return this; + } + + /** + * Add a cursor flag to the cursor + * @method + * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ + addCursorFlag(flag, value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (flags.indexOf(flag) === -1) { + throw MongoError.create({ + message: `flag ${flag} is not a supported flag ${flags}`, + driver: true + }); + } + + if (typeof value !== 'boolean') { + throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true }); + } + + this.cmd[flag] = value; + return this; + } + + /** + * Add a query modifier to the cursor query + * @method + * @param {string} name The query modifier (must start with $, such as $orderby etc) + * @param {string|boolean|number} value The modifier value. + * @throws {MongoError} + * @return {Cursor} + */ + addQueryModifier(name, value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (name[0] !== '$') { + throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true }); + } + + // Strip of the $ + const field = name.substr(1); + // Set on the command + this.cmd[field] = value; + // Deal with the special case for sort + if (field === 'orderby') this.cmd.sort = this.cmd[field]; + return this; + } + + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * @method + * @param {string} value The comment attached to this query. + * @throws {MongoError} + * @return {Cursor} + */ + comment(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.comment = value; + return this; + } + + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * @method + * @param {number} value Number of milliseconds to wait before aborting the tailed query. + * @throws {MongoError} + * @return {Cursor} + */ + maxAwaitTimeMS(value) { + if (typeof value !== 'number') { + throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true }); + } + + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.maxAwaitTimeMS = value; + return this; + } + + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * @method + * @param {number} value Number of milliseconds to wait before aborting the query. + * @throws {MongoError} + * @return {Cursor} + */ + maxTimeMS(value) { + if (typeof value !== 'number') { + throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true }); + } + + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.maxTimeMS = value; + return this; + } + + /** + * Sets a field projection for the query. + * @method + * @param {object} value The field projection object. + * @throws {MongoError} + * @return {Cursor} + */ + project(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.fields = value; + return this; + } + + /** + * Sets the sort order of the cursor query. + * @method + * @param {(string|array|object)} keyOrList The key or keys set for the sort. + * @param {number} [direction] The direction of the sorting (1 or -1). + * @throws {MongoError} + * @return {Cursor} + */ + sort(keyOrList, direction) { + if (this.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true }); + } + + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + let order = keyOrList; + + // We have an array of arrays, we need to preserve the order of the sort + // so we will us a Map + if (Array.isArray(order) && Array.isArray(order[0])) { + order = new Map( + order.map(x => { + const value = [x[0], null]; + if (x[1] === 'asc') { + value[1] = 1; + } else if (x[1] === 'desc') { + value[1] = -1; + } else if (x[1] === 1 || x[1] === -1 || x[1].$meta) { + value[1] = x[1]; + } else { + throw new MongoError( + "Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" + ); + } + + return value; + }) + ); + } + + if (direction != null) { + order = [[keyOrList, direction]]; + } + + this.cmd.sort = order; + return this; + } + + /** + * Set the batch size for the cursor. + * @method + * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + * @throws {MongoError} + * @return {Cursor} + */ + batchSize(value) { + if (this.options.tailable) { + throw MongoError.create({ + message: "Tailable cursor doesn't support batchSize", + driver: true + }); + } + + if (this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + } + + this.cmd.batchSize = value; + this.setCursorBatchSize(value); + return this; + } + + /** + * Set the collation options for the cursor. + * @method + * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @throws {MongoError} + * @return {Cursor} + */ + collation(value) { + this.cmd.collation = value; + return this; + } + + /** + * Set the limit for the cursor. + * @method + * @param {number} value The limit for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ + limit(value) { + if (this.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true }); + } + + if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'limit requires an integer', driver: true }); + } + + this.cmd.limit = value; + this.setCursorLimit(value); + return this; + } + + /** + * Set the skip for the cursor. + * @method + * @param {number} value The skip for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ + skip(value) { + if (this.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true }); + } + + if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'skip requires an integer', driver: true }); + } + + this.cmd.skip = value; + this.setCursorSkip(value); + return this; + } + + /** + * The callback format for results + * @callback Cursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null|boolean)} result The result object if the command was executed successfully. + */ + + /** + * Clone the cursor + * @function external:CoreCursor#clone + * @return {Cursor} + */ + + /** + * Resets the cursor + * @function external:CoreCursor#rewind + * @return {null} + */ + + /** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previously accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method + * @deprecated + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + each(callback) { + // Rewind cursor state + this.rewind(); + // Set current cursor to INIT + this.s.state = CursorState.INIT; + // Run the query + each(this, callback); + } + + /** + * The callback format for the forEach iterator method + * @callback Cursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + + /** + * The callback error format for the forEach iterator method + * @callback Cursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method + * @param {Cursor~iteratorCallback} iterator The iteration callback. + * @param {Cursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {Promise} if no callback supplied + */ + forEach(iterator, callback) { + // Rewind cursor state + this.rewind(); + + // Set current cursor to INIT + this.s.state = CursorState.INIT; + + if (typeof callback === 'function') { + each(this, (err, doc) => { + if (err) { + callback(err); + return false; + } + if (doc != null) { + iterator(doc); + return true; + } + if (doc == null && callback) { + const internalCallback = callback; + callback = null; + internalCallback(null); + return false; + } + }); + } else { + return new this.s.promiseLibrary((fulfill, reject) => { + each(this, (err, doc) => { + if (err) { + reject(err); + return false; + } else if (doc == null) { + fulfill(null); + return false; + } else { + iterator(doc); + return true; + } + }); + }); + } + } + + /** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ + setReadPreference(readPreference) { + if (this.s.state !== CursorState.INIT) { + throw MongoError.create({ + message: 'cannot change cursor readPreference after cursor has been accessed', + driver: true + }); + } + + if (readPreference instanceof ReadPreference) { + this.options.readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this.options.readPreference = new ReadPreference(readPreference); + } else { + throw new TypeError('Invalid read preference: ' + readPreference); + } + + return this; + } + + /** + * The callback format for results + * @callback Cursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + + /** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contains partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + toArray(callback) { + if (this.options.tailable) { + throw MongoError.create({ + message: 'Tailable cursor cannot be converted to array', + driver: true + }); + } + + return maybePromise(this, callback, cb => { + const cursor = this; + const items = []; + + // Reset cursor + cursor.rewind(); + cursor.s.state = CursorState.INIT; + + // Fetch all the documents + const fetchDocs = () => { + cursor._next((err, doc) => { + if (err) { + return handleCallback(cb, err); + } + + if (doc == null) { + return cursor.close({ skipKillCursors: true }, () => handleCallback(cb, null, items)); + } + + // Add doc to items + items.push(doc); + + // Get all buffered objects + if (cursor.bufferedCount() > 0) { + let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); + Array.prototype.push.apply(items, docs); + } + + // Attempt a fetch + fetchDocs(); + }); + }; + + fetchDocs(); + }); + } + + /** + * The callback format for results + * @callback Cursor~countResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} count The count of documents. + */ + + /** + * Get the count of documents for this cursor + * @method + * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. + * @param {object} [options] Optional settings. + * @param {number} [options.skip] The number of documents to skip. + * @param {number} [options.limit] The maximum amounts to count before aborting. + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {string} [options.hint] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Cursor~countResultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + count(applySkipLimit, opts, callback) { + if (this.cmd.query == null) + throw MongoError.create({ + message: 'count can only be used with find command', + driver: true + }); + if (typeof opts === 'function') (callback = opts), (opts = {}); + opts = opts || {}; + + if (typeof applySkipLimit === 'function') { + callback = applySkipLimit; + applySkipLimit = true; + } + + if (this.cursorState.session) { + opts = Object.assign({}, opts, { session: this.cursorState.session }); + } + + const countOperation = new CountOperation(this, applySkipLimit, opts); + + return executeOperation(this.topology, countOperation, callback); + } + + /** + * Close the cursor, sending a KillCursor command and emitting close. + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor. + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + close(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { skipKillCursors: false }, options); + + return maybePromise(this, callback, cb => { + this.s.state = CursorState.CLOSED; + if (!options.skipKillCursors) { + // Kill the cursor + this.kill(); + } + + this._endSession(() => { + this.emit('close'); + cb(null, this); + }); + }); + } + + /** + * Map all documents using the provided function + * @method + * @param {function} [transform] The mapping transformation method. + * @return {Cursor} + */ + map(transform) { + if (this.cursorState.transforms && this.cursorState.transforms.doc) { + const oldTransform = this.cursorState.transforms.doc; + this.cursorState.transforms.doc = doc => { + return transform(oldTransform(doc)); + }; + } else { + this.cursorState.transforms = { doc: transform }; + } + + return this; + } + + /** + * Is the cursor closed + * @method + * @return {boolean} + */ + isClosed() { + return this.isDead(); + } + + destroy(err) { + if (err) this.emit('error', err); + this.pause(); + this.close(); + } + + /** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + * TODO [$5f5fbe42fcabad09c1c241b1]: replace this method with transformStream in next major release + */ + stream(options) { + this.cursorState.streamOptions = options || {}; + return this; + } + + /** + * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied, + * returns a stream of unmodified docs. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {stream} + */ + transformStream(options) { + const streamOptions = options || {}; + if (typeof streamOptions.transform === 'function') { + const stream = new Transform({ + objectMode: true, + transform: function(chunk, encoding, callback) { + this.push(streamOptions.transform(chunk)); + callback(); + } + }); + + return this.pipe(stream); + } + + return this.pipe(new PassThrough({ objectMode: true })); + } + + /** + * Execute the explain for the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + explain(callback) { + // NOTE: the next line includes a special case for operations which do not + // subclass `CommandOperationV2`. To be removed asap. + if (this.operation && this.operation.cmd == null) { + this.operation.options.explain = true; + this.operation.fullResponse = false; + return executeOperation(this.topology, this.operation, callback); + } + + this.cmd.explain = true; + + // Do we have a readConcern + if (this.cmd.readConcern) { + delete this.cmd['readConcern']; + } + return maybePromise(this, callback, cb => { + CoreCursor.prototype._next.apply(this, [cb]); + }); + } + + /** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ + getLogger() { + return this.logger; + } +} + +/** + * Cursor stream data event, fired for each document in the cursor. + * + * @event Cursor#data + * @type {object} + */ + +/** + * Cursor stream end event + * + * @event Cursor#end + * @type {null} + */ + +/** + * Cursor stream close event + * + * @event Cursor#close + * @type {null} + */ + +/** + * Cursor stream readable event + * + * @event Cursor#readable + * @type {null} + */ + +// aliases +Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; + +// deprecated methods +deprecate(Cursor.prototype.each, 'Cursor.each is deprecated. Use Cursor.forEach instead.'); +deprecate( + Cursor.prototype.maxScan, + 'Cursor.maxScan is deprecated, and will be removed in a later version' +); + +deprecate( + Cursor.prototype.snapshot, + 'Cursor Snapshot is deprecated, and will be removed in a later version' +); + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Readable#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Readable#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Readable#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Readable#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Readable#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Readable#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Readable#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Readable#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +module.exports = Cursor; + + +/***/ }), + +/***/ 6662: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const EventEmitter = __webpack_require__(8614).EventEmitter; +const inherits = __webpack_require__(1669).inherits; +const getSingleProperty = __webpack_require__(1371).getSingleProperty; +const CommandCursor = __webpack_require__(538); +const handleCallback = __webpack_require__(1371).handleCallback; +const filterOptions = __webpack_require__(1371).filterOptions; +const toError = __webpack_require__(1371).toError; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const MongoError = __webpack_require__(3994).MongoError; +const ObjectID = __webpack_require__(3994).ObjectID; +const Logger = __webpack_require__(3994).Logger; +const Collection = __webpack_require__(5193); +const mergeOptionsAndWriteConcern = __webpack_require__(1371).mergeOptionsAndWriteConcern; +const executeLegacyOperation = __webpack_require__(1371).executeLegacyOperation; +const ChangeStream = __webpack_require__(1117); +const deprecate = __webpack_require__(1669).deprecate; +const deprecateOptions = __webpack_require__(1371).deprecateOptions; +const MongoDBNamespace = __webpack_require__(1371).MongoDBNamespace; +const CONSTANTS = __webpack_require__(147); +const WriteConcern = __webpack_require__(2481); +const ReadConcern = __webpack_require__(7289); +const AggregationCursor = __webpack_require__(7429); + +// Operations +const createListener = __webpack_require__(2226).createListener; +const ensureIndex = __webpack_require__(2226).ensureIndex; +const evaluate = __webpack_require__(2226).evaluate; +const profilingInfo = __webpack_require__(2226).profilingInfo; +const validateDatabaseName = __webpack_require__(2226).validateDatabaseName; + +const AggregateOperation = __webpack_require__(1554); +const AddUserOperation = __webpack_require__(7057); +const CollectionsOperation = __webpack_require__(286); +const CommandOperation = __webpack_require__(499); +const RunCommandOperation = __webpack_require__(1363); +const CreateCollectionOperation = __webpack_require__(5561); +const CreateIndexesOperation = __webpack_require__(6394); +const DropCollectionOperation = __webpack_require__(2360).DropCollectionOperation; +const DropDatabaseOperation = __webpack_require__(2360).DropDatabaseOperation; +const ExecuteDbAdminCommandOperation = __webpack_require__(1681); +const IndexInformationOperation = __webpack_require__(4245); +const ListCollectionsOperation = __webpack_require__(840); +const ProfilingLevelOperation = __webpack_require__(3969); +const RemoveUserOperation = __webpack_require__(1969); +const RenameOperation = __webpack_require__(2808); +const SetProfilingLevelOperation = __webpack_require__(6301); + +const executeOperation = __webpack_require__(2548); + +/** + * @fileOverview The **Db** class is a class that represents a MongoDB Database. + * + * @example + * const MongoClient = require('mongodb').MongoClient; + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Select the database by name + * const testDb = client.db(dbName); + * client.close(); + * }); + */ + +// Allowed parameters +const legalOptionNames = [ + 'w', + 'wtimeout', + 'fsync', + 'j', + 'readPreference', + 'readPreferenceTags', + 'native_parser', + 'forceServerObjectId', + 'pkFactory', + 'serializeFunctions', + 'raw', + 'bufferMaxEntries', + 'authSource', + 'ignoreUndefined', + 'promoteLongs', + 'promiseLibrary', + 'readConcern', + 'retryMiliSeconds', + 'numberOfRetries', + 'parentDb', + 'noListener', + 'loggerLevel', + 'logger', + 'promoteBuffers', + 'promoteLongs', + 'promoteValues', + 'compression', + 'retryWrites' +]; + +/** + * Creates a new Db instance + * @class + * @param {string} databaseName The name of the database this instance represents. + * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. + * @param {object} [options] Optional settings. + * @param {string} [options.authSource] If the database authentication is dependent on another databaseName. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) + * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. + * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database + * @property {string} databaseName The name of the database this instance represents. + * @property {object} options The options associated with the db instance. + * @property {boolean} native_parser The current value of the parameter native_parser. + * @property {boolean} slaveOk The current slaveOk value for the db instance. + * @property {object} writeConcern The current write concern values. + * @property {object} topology Access the topology object (single server, replicaset or mongos). + * @fires Db#close + * @fires Db#reconnect + * @fires Db#error + * @fires Db#timeout + * @fires Db#parseError + * @fires Db#fullsetup + * @return {Db} a Db instance. + */ +function Db(databaseName, topology, options) { + options = options || {}; + if (!(this instanceof Db)) return new Db(databaseName, topology, options); + EventEmitter.call(this); + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure we put the promiseLib in the options + options.promiseLibrary = promiseLibrary; + + // Internal state of the db object + this.s = { + // DbCache + dbCache: {}, + // Children db's + children: [], + // Topology + topology: topology, + // Options + options: options, + // Logger instance + logger: Logger('Db', options), + // Get the bson parser + bson: topology ? topology.bson : null, + // Unpack read preference + readPreference: ReadPreference.fromOptions(options), + // Set buffermaxEntries + bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1, + // Parent db (if chained) + parentDb: options.parentDb || null, + // Set up the primary key factory or fallback to ObjectID + pkFactory: options.pkFactory || ObjectID, + // Get native parser + nativeParser: options.nativeParser || options.native_parser, + // Promise library + promiseLibrary: promiseLibrary, + // No listener + noListener: typeof options.noListener === 'boolean' ? options.noListener : false, + // ReadConcern + readConcern: ReadConcern.fromOptions(options), + writeConcern: WriteConcern.fromOptions(options), + // Namespace + namespace: new MongoDBNamespace(databaseName) + }; + + // Ensure we have a valid db name + validateDatabaseName(databaseName); + + // Add a read Only property + getSingleProperty(this, 'serverConfig', this.s.topology); + getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries); + getSingleProperty(this, 'databaseName', this.s.namespace.db); + + // This is a child db, do not register any listeners + if (options.parentDb) return; + if (this.s.noListener) return; + + // Add listeners + topology.on('error', createListener(this, 'error', this)); + topology.on('timeout', createListener(this, 'timeout', this)); + topology.on('close', createListener(this, 'close', this)); + topology.on('parseError', createListener(this, 'parseError', this)); + topology.once('open', createListener(this, 'open', this)); + topology.once('fullsetup', createListener(this, 'fullsetup', this)); + topology.once('all', createListener(this, 'all', this)); + topology.on('reconnect', createListener(this, 'reconnect', this)); +} + +inherits(Db, EventEmitter); + +// Topology +Object.defineProperty(Db.prototype, 'topology', { + enumerable: true, + get: function() { + return this.s.topology; + } +}); + +// Options +Object.defineProperty(Db.prototype, 'options', { + enumerable: true, + get: function() { + return this.s.options; + } +}); + +// slaveOk specified +Object.defineProperty(Db.prototype, 'slaveOk', { + enumerable: true, + get: function() { + if ( + this.s.options.readPreference != null && + (this.s.options.readPreference !== 'primary' || + this.s.options.readPreference.mode !== 'primary') + ) { + return true; + } + return false; + } +}); + +Object.defineProperty(Db.prototype, 'readConcern', { + enumerable: true, + get: function() { + return this.s.readConcern; + } +}); + +Object.defineProperty(Db.prototype, 'readPreference', { + enumerable: true, + get: function() { + if (this.s.readPreference == null) { + // TODO [$5f5fbe42fcabad09c1c241b2]: check client + return ReadPreference.primary; + } + + return this.s.readPreference; + } +}); + +// get the write Concern +Object.defineProperty(Db.prototype, 'writeConcern', { + enumerable: true, + get: function() { + return this.s.writeConcern; + } +}); + +Object.defineProperty(Db.prototype, 'namespace', { + enumerable: true, + get: function() { + return this.s.namespace.toString(); + } +}); + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.command = function(command, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + const commandOperation = new RunCommandOperation(this, command, options); + + return executeOperation(this.s.topology, commandOperation, callback); +}; + +/** + * Execute an aggregation framework pipeline against the database, needs MongoDB >= 3.6 + * @method + * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize=1000] Deprecated. Use `options.batchSize` + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {string} [options.comment] Add a comment to an aggregation command + * @param {string|object} [options.hint] Add an index selection hint to an aggregation command + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Database~aggregationCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Db.prototype.aggregate = function(pipeline, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if (options == null && callback == null) { + options = {}; + } + + const cursor = new AggregationCursor( + this.s.topology, + new AggregateOperation(this, pipeline, options), + options + ); + + // TODO [$5f5fbe42fcabad09c1c241b3]: remove this when NODE-2074 is resolved + if (typeof callback === 'function') { + callback(null, cursor); + return; + } + + return cursor; +}; + +/** + * Return the Admin db instance + * @method + * @return {Admin} return the new Admin db instance + */ +Db.prototype.admin = function() { + const Admin = __webpack_require__(3238); + + return new Admin(this, this.s.topology, this.s.promiseLibrary); +}; + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Db~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * The callback format for an aggregation call + * @callback Database~aggregationCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. + */ + +const collectionKeys = [ + 'pkFactory', + 'readPreference', + 'serializeFunctions', + 'strict', + 'readConcern', + 'ignoreUndefined', + 'promoteValues', + 'promoteBuffers', + 'promoteLongs' +]; + +/** + * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you + * can use it without a callback in the following way: `const collection = db.collection('mycollection');` + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) + * @param {Db~collectionResultCallback} [callback] The collection result callback + * @return {Collection} return the new Collection instance if not in strict mode + */ +Db.prototype.collection = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options = Object.assign({}, options); + + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // If we have not set a collection level readConcern set the db level one + options.readConcern = options.readConcern + ? new ReadConcern(options.readConcern.level) + : this.readConcern; + + // Do we have ignoreUndefined set + if (this.s.options.ignoreUndefined) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Merge in all needed options and ensure correct writeConcern merging from db level + options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true); + + // Execute + if (options == null || !options.strict) { + try { + const collection = new Collection( + this, + this.s.topology, + this.databaseName, + name, + this.s.pkFactory, + options + ); + if (callback) callback(null, collection); + return collection; + } catch (err) { + if (err instanceof MongoError && callback) return callback(err); + throw err; + } + } + + // Strict mode + if (typeof callback !== 'function') { + throw toError(`A callback is required in strict mode. While getting collection ${name}`); + } + + // Did the user destroy the topology + if (this.serverConfig && this.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + const listCollectionOptions = Object.assign({}, options, { nameOnly: true }); + + // Strict mode + this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => { + if (err != null) return handleCallback(callback, err, null); + if (collections.length === 0) + return handleCallback( + callback, + toError(`Collection ${name} does not exist. Currently in strict mode.`), + null + ); + + try { + return handleCallback( + callback, + null, + new Collection(this, this.s.topology, this.databaseName, name, this.s.pkFactory, options) + ); + } catch (err) { + return handleCallback(callback, err, null); + } + }); +}; + +/** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] DEPRECATED: Returns an error if the collection does not exist + * @param {boolean} [options.capped=false] Create a capped collection. + * @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 + * @param {number} [options.size] The size of the capped collection in bytes. + * @param {number} [options.max] The maximum number of documents in the capped collection. + * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. + * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. + * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. + * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. + * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. + * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. + * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. + * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createCollection = deprecateOptions( + { + name: 'Db.createCollection', + deprecatedOptions: ['autoIndexId', 'strict'], + optionsIndex: 1 + }, + function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; + options.readConcern = options.readConcern + ? new ReadConcern(options.readConcern.level) + : this.readConcern; + const createCollectionOperation = new CreateCollectionOperation(this, name, options); + + return executeOperation(this.s.topology, createCollectionOperation, callback); + } +); + +/** + * Get all the db statistics. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.scale] Divide the returned sizes by scale value. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.stats = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Build command object + const commandObject = { dbStats: true }; + // Check if we have the scale value + if (options['scale'] != null) commandObject['scale'] = options['scale']; + + // If we have a readPreference set + if (options.readPreference == null && this.s.readPreference) { + options.readPreference = this.s.readPreference; + } + + const statsOperation = new CommandOperation(this, options, null, commandObject); + + // Execute the command + return executeOperation(this.s.topology, statsOperation, callback); +}; + +/** + * Get the list of all collection information for the specified db. + * + * @method + * @param {object} [filter={}] Query to filter collections by + * @param {object} [options] Optional settings. + * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info + * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {CommandCursor} + */ +Db.prototype.listCollections = function(filter, options) { + filter = filter || {}; + options = options || {}; + + return new CommandCursor( + this.s.topology, + new ListCollectionsOperation(this, filter, options), + options + ); +}; + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options] Optional settings. + * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaluation of the javascript. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.eval = deprecate(function(code, parameters, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + parameters = args.length ? args.shift() : parameters; + options = args.length ? args.shift() || {} : {}; + + return executeLegacyOperation(this.s.topology, evaluate, [ + this, + code, + parameters, + options, + callback + ]); +}, 'Db.eval is deprecated as of MongoDB version 3.2'); + +/** + * Rename a collection. + * + * @method + * @param {string} fromCollection Name of current collection to rename. + * @param {string} toCollection New name of of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + // Add return new collection + options.new_collection = true; + + const renameOperation = new RenameOperation( + this.collection(fromCollection), + toCollection, + options + ); + + return executeOperation(this.s.topology, renameOperation, callback); +}; + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {string} name Name of collection to drop + * @param {Object} [options] Optional settings + * @param {WriteConcern} [options.writeConcern] A full WriteConcern object + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j] The journal write concern + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropCollection = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const dropCollectionOperation = new DropCollectionOperation(this, name, options); + + return executeOperation(this.s.topology, dropCollectionOperation, callback); +}; + +/** + * Drop a database, removing it permanently from the server. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropDatabase = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const dropDatabaseOperation = new DropDatabaseOperation(this, options); + + return executeOperation(this.s.topology, dropDatabaseOperation, callback); +}; + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionsResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.collections = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const collectionsOperation = new CollectionsOperation(this, options); + + return executeOperation(this.s.topology, collectionsOperation, callback); +}; + +/** + * Runs a command on the database as admin. + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.executeDbAdminCommand = function(selector, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options.readPreference = ReadPreference.resolve(this, options); + + const executeDbAdminCommandOperation = new ExecuteDbAdminCommandOperation( + this, + selector, + options + ); + + return executeOperation(this.s.topology, executeDbAdminCommandOperation, callback); +}; + +/** + * Creates an index on the db and collection. + * @method + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {(number|string)} [options.commitQuorum] (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + + const createIndexesOperation = new CreateIndexesOperation(this, name, fieldOrSpec, options); + + return executeOperation(this.s.topology, createIndexesOperation, callback); +}; + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated since version 2.0 + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.s.topology, ensureIndex, [ + this, + name, + fieldOrSpec, + options, + callback + ]); +}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0'); + +Db.prototype.addChild = function(db) { + if (this.s.parentDb) return this.s.parentDb.addChild(db); + this.s.children.push(db); +}; + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.addUser = function(username, password, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Special case where there is no password ($external users) + if (typeof username === 'string' && password != null && typeof password === 'object') { + options = password; + password = null; + } + + const addUserOperation = new AddUserOperation(this, username, password, options); + + return executeOperation(this.s.topology, addUserOperation, callback); +}; + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.removeUser = function(username, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const removeUserOperation = new RemoveUserOperation(this, username, options); + + return executeOperation(this.s.topology, removeUserOperation, callback); +}; + +/** + * Set the current profiling level of MongoDB + * + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.setProfilingLevel = function(level, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const setProfilingLevelOperation = new SetProfilingLevelOperation(this, level, options); + + return executeOperation(this.s.topology, setProfilingLevelOperation, callback); +}; + +/** + * Retrieve the current profiling information for MongoDB + * + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Query the system.profile collection directly. + */ +Db.prototype.profilingInfo = deprecate(function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.s.topology, profilingInfo, [this, options, callback]); +}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.'); + +/** + * Retrieve the current profiling Level for MongoDB + * + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.profilingLevel = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const profilingLevelOperation = new ProfilingLevelOperation(this, options); + + return executeOperation(this.s.topology, profilingLevelOperation, callback); +}; + +/** + * Retrieves this collections index info. + * @method + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.indexInformation = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const indexInformationOperation = new IndexInformationOperation(this, name, options); + + return executeOperation(this.s.topology, indexInformationOperation, callback); +}; + +/** + * Unref all sockets + * @method + */ +Db.prototype.unref = function() { + this.s.topology.unref(); +}; + +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections. + * @method + * @since 3.1.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +Db.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +Db.prototype.getLogger = function() { + return this.s.logger; +}; + +/** + * Db close event + * + * Emitted after a socket closed against a single server or mongos proxy. + * + * @event Db#close + * @type {MongoError} + */ + +/** + * Db reconnect event + * + * * Server: Emitted when the driver has reconnected and re-authenticated. + * * ReplicaSet: N/A + * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. + * + * @event Db#reconnect + * @type {object} + */ + +/** + * Db error event + * + * Emitted after an error occurred against a single server or mongos proxy. + * + * @event Db#error + * @type {MongoError} + */ + +/** + * Db timeout event + * + * Emitted after a socket timeout occurred against a single server or mongos proxy. + * + * @event Db#timeout + * @type {MongoError} + */ + +/** + * Db parseError event + * + * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. + * + * @event Db#parseError + * @type {MongoError} + */ + +/** + * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. + * + * * Server: Emitted when the driver has connected to the single server and has authenticated. + * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. + * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. + * + * @event Db#fullsetup + * @type {Db} + */ + +// Constants +Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; +Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; +Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; +Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; +Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; +Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; + +module.exports = Db; + + +/***/ }), + +/***/ 8275: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +let collection; +let cursor; +let db; + +function loadCollection() { + if (!collection) { + collection = __webpack_require__(5193); + } + return collection; +} + +function loadCursor() { + if (!cursor) { + cursor = __webpack_require__(7159); + } + return cursor; +} + +function loadDb() { + if (!db) { + db = __webpack_require__(6662); + } + return db; +} + +module.exports = { + loadCollection, + loadCursor, + loadDb +}; + + +/***/ }), + +/***/ 9386: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const MongoNetworkError = __webpack_require__(3994).MongoNetworkError; + +// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error +const GET_MORE_RESUMABLE_CODES = new Set([ + 6, // HostUnreachable + 7, // HostNotFound + 89, // NetworkTimeout + 91, // ShutdownInProgress + 189, // PrimarySteppedDown + 262, // ExceededTimeLimit + 9001, // SocketException + 10107, // NotMaster + 11600, // InterruptedAtShutdown + 11602, // InterruptedDueToReplStateChange + 13435, // NotMasterNoSlaveOk + 13436, // NotMasterOrSecondary + 63, // StaleShardVersion + 150, // StaleEpoch + 13388, // StaleConfig + 234, // RetryChangeStream + 133, // FailedToSatisfyReadPreference + 43 // CursorNotFound +]); + +function isResumableError(error, wireVersion) { + if (error instanceof MongoNetworkError) { + return true; + } + + if (wireVersion >= 9) { + // DRIVERS-1308: For 4.4 drivers running against 4.4 servers, drivers will add a special case to treat the CursorNotFound error code as resumable + if (error.code === 43) { + return true; + } + return error.hasErrorLabel('ResumableChangeStreamError'); + } + + return GET_MORE_RESUMABLE_CODES.has(error.code); +} + +module.exports = { GET_MORE_RESUMABLE_CODES, isResumableError }; + + +/***/ }), + +/***/ 4190: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var stream = __webpack_require__(2413), + util = __webpack_require__(1669); + +module.exports = GridFSBucketReadStream; + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * + * @class + * @extends external:Readable + * @param {Collection} chunks Handle for chunks collection + * @param {Collection} files Handle for files collection + * @param {Object} readPreference The read preference to use + * @param {Object} filter The query to use to find the file document + * @param {Object} [options] Optional settings. + * @param {Number} [options.sort] Optional sort for the file find query + * @param {Number} [options.skip] Optional skip for the file find query + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @fires GridFSBucketReadStream#error + * @fires GridFSBucketReadStream#file + */ +function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { + this.s = { + bytesRead: 0, + chunks: chunks, + cursor: null, + expected: 0, + files: files, + filter: filter, + init: false, + expectedEnd: 0, + file: null, + options: options, + readPreference: readPreference + }; + + stream.Readable.call(this); +} + +util.inherits(GridFSBucketReadStream, stream.Readable); + +/** + * An error occurred + * + * @event GridFSBucketReadStream#error + * @type {Error} + */ + +/** + * Fires when the stream loaded the file document corresponding to the + * provided id. + * + * @event GridFSBucketReadStream#file + * @type {object} + */ + +/** + * Emitted when a chunk of data is available to be consumed. + * + * @event GridFSBucketReadStream#data + * @type {object} + */ + +/** + * Fired when the stream is exhausted (no more data events). + * + * @event GridFSBucketReadStream#end + * @type {object} + */ + +/** + * Fired when the stream is exhausted and the underlying cursor is killed + * + * @event GridFSBucketReadStream#close + * @type {object} + */ + +/** + * Reads from the cursor and pushes to the stream. + * Private Impl, do not call directly + * @ignore + * @method + */ + +GridFSBucketReadStream.prototype._read = function() { + var _this = this; + if (this.destroyed) { + return; + } + + waitForFile(_this, function() { + doRead(_this); + }); +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} start Offset in bytes to start reading at + * @return {GridFSBucketReadStream} Reference to Self + */ + +GridFSBucketReadStream.prototype.start = function(start) { + throwIfInitialized(this); + this.s.options.start = start; + return this; +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} end Offset in bytes to stop reading at + * @return {GridFSBucketReadStream} Reference to self + */ + +GridFSBucketReadStream.prototype.end = function(end) { + throwIfInitialized(this); + this.s.options.end = end; + return this; +}; + +/** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @method + * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. + * @fires GridFSBucketWriteStream#close + * @fires GridFSBucketWriteStream#end + */ + +GridFSBucketReadStream.prototype.abort = function(callback) { + var _this = this; + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + this.s.cursor.close(function(error) { + _this.emit('close'); + callback && callback(error); + }); + } else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + _this.emit('close'); + } + callback && callback(); + } +}; + +/** + * @ignore + */ + +function throwIfInitialized(self) { + if (self.s.init) { + throw new Error('You cannot change options after the stream has entered' + 'flowing mode!'); + } +} + +/** + * @ignore + */ + +function doRead(_this) { + if (_this.destroyed) { + return; + } + + _this.s.cursor.next(function(error, doc) { + if (_this.destroyed) { + return; + } + if (error) { + return __handleError(_this, error); + } + if (!doc) { + _this.push(null); + + process.nextTick(() => { + _this.s.cursor.close(function(error) { + if (error) { + __handleError(_this, error); + return; + } + + _this.emit('close'); + }); + }); + + return; + } + + var bytesRemaining = _this.s.file.length - _this.s.bytesRead; + var expectedN = _this.s.expected++; + var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining); + + if (doc.n > expectedN) { + var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + + if (doc.n < expectedN) { + errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + + var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; + + if (buf.length !== expectedLength) { + if (bytesRemaining <= 0) { + errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; + return __handleError(_this, new Error(errmsg)); + } + + errmsg = + 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength; + return __handleError(_this, new Error(errmsg)); + } + + _this.s.bytesRead += buf.length; + + if (buf.length === 0) { + return _this.push(null); + } + + var sliceStart = null; + var sliceEnd = null; + + if (_this.s.bytesToSkip != null) { + sliceStart = _this.s.bytesToSkip; + _this.s.bytesToSkip = 0; + } + + const atEndOfStream = expectedN === _this.s.expectedEnd - 1; + const bytesLeftToRead = _this.s.options.end - _this.s.bytesToSkip; + if (atEndOfStream && _this.s.bytesToTrim != null) { + sliceEnd = _this.s.file.chunkSize - _this.s.bytesToTrim; + } else if (_this.s.options.end && bytesLeftToRead < doc.data.length()) { + sliceEnd = bytesLeftToRead; + } + + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); + } + + _this.push(buf); + }); +} + +/** + * @ignore + */ + +function init(self) { + var findOneOptions = {}; + if (self.s.readPreference) { + findOneOptions.readPreference = self.s.readPreference; + } + if (self.s.options && self.s.options.sort) { + findOneOptions.sort = self.s.options.sort; + } + if (self.s.options && self.s.options.skip) { + findOneOptions.skip = self.s.options.skip; + } + + self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { + if (error) { + return __handleError(self, error); + } + + if (!doc) { + var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename; + var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; + var err = new Error(errmsg); + err.code = 'ENOENT'; + return __handleError(self, err); + } + + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + self.push(null); + return; + } + + if (self.destroyed) { + // If user destroys the stream before we have a cursor, wait + // until the query is done to say we're 'closed' because we can't + // cancel a query. + self.emit('close'); + return; + } + + try { + self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); + } catch (error) { + return __handleError(self, error); + } + + var filter = { files_id: doc._id }; + + // Currently (MongoDB 3.4.4) skip function does not support the index, + // it needs to retrieve all the documents first and then skip them. (CS-25811) + // As work around we use $gte on the "n" field. + if (self.s.options && self.s.options.start != null) { + var skip = Math.floor(self.s.options.start / doc.chunkSize); + if (skip > 0) { + filter['n'] = { $gte: skip }; + } + } + self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); + + if (self.s.readPreference) { + self.s.cursor.setReadPreference(self.s.readPreference); + } + + self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + self.s.file = doc; + + try { + self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options); + } catch (error) { + return __handleError(self, error); + } + + self.emit('file', doc); + }); +} + +/** + * @ignore + */ + +function waitForFile(_this, callback) { + if (_this.s.file) { + return callback(); + } + + if (!_this.s.init) { + init(_this); + _this.s.init = true; + } + + _this.once('file', function() { + callback(); + }); +} + +/** + * @ignore + */ + +function handleStartOption(stream, doc, options) { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new Error( + 'Stream start (' + + options.start + + ') must not be ' + + 'more than the length of the file (' + + doc.length + + ')' + ); + } + if (options.start < 0) { + throw new Error('Stream start (' + options.start + ') must not be ' + 'negative'); + } + if (options.end != null && options.end < options.start) { + throw new Error( + 'Stream start (' + + options.start + + ') must not be ' + + 'greater than stream end (' + + options.end + + ')' + ); + } + + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + + return options.start - stream.s.bytesRead; + } +} + +/** + * @ignore + */ + +function handleEndOption(stream, doc, cursor, options) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new Error( + 'Stream end (' + + options.end + + ') must not be ' + + 'more than the length of the file (' + + doc.length + + ')' + ); + } + if (options.start < 0) { + throw new Error('Stream end (' + options.end + ') must not be ' + 'negative'); + } + + var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; + + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + + return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; + } +} + +/** + * @ignore + */ + +function __handleError(_this, error) { + _this.emit('error', error); +} + + +/***/ }), + +/***/ 2573: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var Emitter = __webpack_require__(8614).EventEmitter; +var GridFSBucketReadStream = __webpack_require__(4190); +var GridFSBucketWriteStream = __webpack_require__(1413); +var shallowClone = __webpack_require__(1371).shallowClone; +var toError = __webpack_require__(1371).toError; +var util = __webpack_require__(1669); +var executeLegacyOperation = __webpack_require__(1371).executeLegacyOperation; + +var DEFAULT_GRIDFS_BUCKET_OPTIONS = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; + +module.exports = GridFSBucket; + +/** + * Constructor for a streaming GridFS interface + * @class + * @extends external:EventEmitter + * @param {Db} db A db handle + * @param {object} [options] Optional settings. + * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. + * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB + * @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }` + * @param {object} [options.readPreference] Optional read preference to be passed to read operations + * @fires GridFSBucketWriteStream#index + */ + +function GridFSBucket(db, options) { + Emitter.apply(this); + this.setMaxListeners(0); + + if (options && typeof options === 'object') { + options = shallowClone(options); + var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); + for (var i = 0; i < keys.length; ++i) { + if (!options[keys[i]]) { + options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; + } + } + } else { + options = DEFAULT_GRIDFS_BUCKET_OPTIONS; + } + + this.s = { + db: db, + options: options, + _chunksCollection: db.collection(options.bucketName + '.chunks'), + _filesCollection: db.collection(options.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false, + promiseLibrary: db.s.promiseLibrary || Promise + }; +} + +util.inherits(GridFSBucket, Emitter); + +/** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * + * @event GridFSBucket#index + * @type {Error} + */ + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStream = function(filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string|number|object} id A custom id used to identify the file + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + + options.id = id; + + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming file + * data from GridFS. + * @method + * @param {ObjectId} id The id of the file doc + * @param {Object} [options] Optional settings. + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStream = function(id, options) { + var filter = { _id: id }; + options = { + start: options && options.start, + end: options && options.end + }; + + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + filter, + options + ); +}; + +/** + * Deletes a file with the given id + * @method + * @param {ObjectId} id The id of the file doc + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.delete = function(id, callback) { + return executeLegacyOperation(this.s.db.s.topology, _delete, [this, id, callback], { + skipSessions: true + }); +}; + +/** + * @ignore + */ + +function _delete(_this, id, callback) { + _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { + if (error) { + return callback(error); + } + + _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { + if (error) { + return callback(error); + } + + // Delete orphaned chunks before returning FileNotFound + if (!res.result.n) { + var errmsg = 'FileNotFound: no file with id ' + id + ' found'; + return callback(new Error(errmsg)); + } + + callback(); + }); + }); +} + +/** + * Convenience wrapper around find on the files collection + * @method + * @param {Object} filter + * @param {Object} [options] Optional settings for cursor + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find|find command documentation}. + * @param {number} [options.limit] Optional limit for cursor + * @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor + * @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag + * @param {number} [options.skip] Optional skip for cursor + * @param {object} [options.sort] Optional sort for cursor + * @return {Cursor} + */ + +GridFSBucket.prototype.find = function(filter, options) { + filter = filter || {}; + options = options || {}; + + var cursor = this.s._filesCollection.find(filter); + + if (options.batchSize != null) { + cursor.batchSize(options.batchSize); + } + if (options.limit != null) { + cursor.limit(options.limit); + } + if (options.maxTimeMS != null) { + cursor.maxTimeMS(options.maxTimeMS); + } + if (options.noCursorTimeout != null) { + cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); + } + if (options.skip != null) { + cursor.skip(options.skip); + } + if (options.sort != null) { + cursor.sort(options.sort); + } + + return cursor; +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + * @method + * @param {String} filename The name of the file to stream + * @param {Object} [options] Optional settings + * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { + var sort = { uploadDate: -1 }; + var skip = null; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; + } else { + skip = -options.revision - 1; + } + } + + var filter = { filename: filename }; + options = { + sort: sort, + skip: skip, + start: options && options.start, + end: options && options.end + }; + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + filter, + options + ); +}; + +/** + * Renames the file with the given _id to the given string + * @method + * @param {ObjectId} id the id of the file to rename + * @param {String} filename new name for the file + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.rename = function(id, filename, callback) { + return executeLegacyOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], { + skipSessions: true + }); +}; + +/** + * @ignore + */ + +function _rename(_this, id, filename, callback) { + var filter = { _id: id }; + var update = { $set: { filename: filename } }; + _this.s._filesCollection.updateOne(filter, update, function(error, res) { + if (error) { + return callback(error); + } + if (!res.result.n) { + return callback(toError('File with id ' + id + ' not found')); + } + callback(); + }); +} + +/** + * Removes this bucket's files collection, followed by its chunks collection. + * @method + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.drop = function(callback) { + return executeLegacyOperation(this.s.db.s.topology, _drop, [this, callback], { + skipSessions: true + }); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +GridFSBucket.prototype.getLogger = function() { + return this.s.db.s.logger; +}; + +/** + * @ignore + */ + +function _drop(_this, callback) { + _this.s._filesCollection.drop(function(error) { + if (error) { + return callback(error); + } + _this.s._chunksCollection.drop(function(error) { + if (error) { + return callback(error); + } + + return callback(); + }); + }); +} + +/** + * Callback format for all GridFSBucket methods that can accept a callback. + * @callback GridFSBucket~errorCallback + * @param {MongoError|undefined} error If present, an error instance representing any errors that occurred + * @param {*} result If present, a returned result for the method + */ + + +/***/ }), + +/***/ 1413: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var core = __webpack_require__(3994); +var crypto = __webpack_require__(6417); +var stream = __webpack_require__(2413); +var util = __webpack_require__(1669); +var Buffer = __webpack_require__(1867).Buffer; + +var ERROR_NAMESPACE_NOT_FOUND = 26; + +module.exports = GridFSBucketWriteStream; + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * + * @class + * @extends external:Writable + * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {string|number|object} [options.id] Custom file id for the GridFS file. + * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes + * @param {number} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {number} [options.j] The journal write concern + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @fires GridFSBucketWriteStream#error + * @fires GridFSBucketWriteStream#finish + */ + +function GridFSBucketWriteStream(bucket, filename, options) { + options = options || {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + // Signals the write is all done + this.done = false; + + this.id = options.id ? options.id : core.BSON.ObjectId(); + this.chunkSizeBytes = this.options.chunkSizeBytes; + this.bufToStore = Buffer.alloc(this.chunkSizeBytes); + this.length = 0; + this.md5 = !options.disableMD5 && crypto.createHash('md5'); + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false, + promiseLibrary: this.bucket.s.promiseLibrary + }; + + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + + var _this = this; + checkIndexes(this, function() { + _this.bucket.s.checkedIndexes = true; + _this.bucket.emit('index'); + }); + } +} + +util.inherits(GridFSBucketWriteStream, stream.Writable); + +/** + * An error occurred + * + * @event GridFSBucketWriteStream#error + * @type {Error} + */ + +/** + * `end()` was called and the write stream successfully wrote the file + * metadata and all the chunks to MongoDB. + * + * @event GridFSBucketWriteStream#finish + * @type {object} + */ + +/** + * Write a buffer to the stream. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {GridFSBucket~errorCallback} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. + */ + +GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { + var _this = this; + return waitForIndexes(this, function() { + return doWrite(_this, chunk, encoding, callback); + }); +}; + +/** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + * + * @method + * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred + * @return {Promise} if no callback specified + */ + +GridFSBucketWriteStream.prototype.abort = function(callback) { + if (this.state.streamEnd) { + var error = new Error('Cannot abort a stream that has already completed'); + if (typeof callback === 'function') { + return callback(error); + } + return this.state.promiseLibrary.reject(error); + } + if (this.state.aborted) { + error = new Error('Cannot call abort() on a stream twice'); + if (typeof callback === 'function') { + return callback(error); + } + return this.state.promiseLibrary.reject(error); + } + this.state.aborted = true; + this.chunks.deleteMany({ files_id: this.id }, function(error) { + if (typeof callback === 'function') callback(error); + }); +}; + +/** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {GridFSBucket~errorCallback} callback Function to call when all files and chunks have been persisted to MongoDB + */ + +GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { + var _this = this; + if (typeof chunk === 'function') { + (callback = chunk), (chunk = null), (encoding = null); + } else if (typeof encoding === 'function') { + (callback = encoding), (encoding = null); + } + + if (checkAborted(this, callback)) { + return; + } + this.state.streamEnd = true; + + if (callback) { + this.once('finish', function(result) { + callback(null, result); + }); + } + + if (!chunk) { + waitForIndexes(this, function() { + writeRemnant(_this); + }); + return; + } + + this.write(chunk, encoding, function() { + writeRemnant(_this); + }); +}; + +/** + * @ignore + */ + +function __handleError(_this, error, callback) { + if (_this.state.errored) { + return; + } + _this.state.errored = true; + if (callback) { + return callback(error); + } + _this.emit('error', error); +} + +/** + * @ignore + */ + +function createChunkDoc(filesId, n, data) { + return { + _id: core.BSON.ObjectId(), + files_id: filesId, + n: n, + data: data + }; +} + +/** + * @ignore + */ + +function checkChunksIndex(_this, callback) { + _this.chunks.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { files_id: 1, n: 1 }; + _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + return; + } + return callback(error); + } + + var hasChunksIndex = false; + indexes.forEach(function(index) { + if (index.key) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + hasChunksIndex = true; + } + } + }); + + if (hasChunksIndex) { + callback(); + } else { + index = { files_id: 1, n: 1 }; + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + indexOptions.unique = true; + + _this.chunks.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + } + }); +} + +/** + * @ignore + */ + +function checkDone(_this, callback) { + if (_this.done) return true; + if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) { + // Set done so we dont' trigger duplicate createFilesDoc + _this.done = true; + // Create a new files doc + var filesDoc = createFilesDoc( + _this.id, + _this.length, + _this.chunkSizeBytes, + _this.md5 && _this.md5.digest('hex'), + _this.filename, + _this.options.contentType, + _this.options.aliases, + _this.options.metadata + ); + + if (checkAborted(_this, callback)) { + return false; + } + + _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error, callback); + } + _this.emit('finish', filesDoc); + }); + + return true; + } + + return false; +} + +/** + * @ignore + */ + +function checkIndexes(_this, callback) { + _this.files.findOne({}, { _id: 1 }, function(error, doc) { + if (error) { + return callback(error); + } + if (doc) { + return callback(); + } + + _this.files.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { filename: 1, uploadDate: 1 }; + _this.files.createIndex(index, { background: false }, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + return; + } + return callback(error); + } + + var hasFileIndex = false; + indexes.forEach(function(index) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + + if (hasFileIndex) { + checkChunksIndex(_this, callback); + } else { + index = { filename: 1, uploadDate: 1 }; + + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + + _this.files.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + } + }); + }); +} + +/** + * @ignore + */ + +function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) { + var ret = { + _id: _id, + length: length, + chunkSize: chunkSize, + uploadDate: new Date(), + filename: filename + }; + + if (md5) { + ret.md5 = md5; + } + + if (contentType) { + ret.contentType = contentType; + } + + if (aliases) { + ret.aliases = aliases; + } + + if (metadata) { + ret.metadata = metadata; + } + + return ret; +} + +/** + * @ignore + */ + +function doWrite(_this, chunk, encoding, callback) { + if (checkAborted(_this, callback)) { + return false; + } + + var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + + _this.length += inputBuf.length; + + // Input is small enough to fit in our buffer + if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { + inputBuf.copy(_this.bufToStore, _this.pos); + _this.pos += inputBuf.length; + + callback && callback(); + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // True means client can keep writing. + return true; + } + + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + var inputBufRemaining = inputBuf.length; + var spaceRemaining = _this.chunkSizeBytes - _this.pos; + var numToCopy = Math.min(spaceRemaining, inputBuf.length); + var outstandingRequests = 0; + while (inputBufRemaining > 0) { + var inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy); + _this.pos += numToCopy; + spaceRemaining -= numToCopy; + if (spaceRemaining === 0) { + if (_this.md5) { + _this.md5.update(_this.bufToStore); + } + var doc = createChunkDoc(_this.id, _this.n, Buffer.from(_this.bufToStore)); + ++_this.state.outstandingRequests; + ++outstandingRequests; + + if (checkAborted(_this, callback)) { + return false; + } + + _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + --outstandingRequests; + + if (!outstandingRequests) { + _this.emit('drain', doc); + callback && callback(); + checkDone(_this); + } + }); + + spaceRemaining = _this.chunkSizeBytes; + _this.pos = 0; + ++_this.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // False means the client should wait for the 'drain' event. + return false; +} + +/** + * @ignore + */ + +function getWriteOptions(_this) { + var obj = {}; + if (_this.options.writeConcern) { + obj.w = _this.options.writeConcern.w; + obj.wtimeout = _this.options.writeConcern.wtimeout; + obj.j = _this.options.writeConcern.j; + } + return obj; +} + +/** + * @ignore + */ + +function waitForIndexes(_this, callback) { + if (_this.bucket.s.checkedIndexes) { + return callback(false); + } + + _this.bucket.once('index', function() { + callback(true); + }); + + return true; +} + +/** + * @ignore + */ + +function writeRemnant(_this, callback) { + // Buffer is empty, so don't bother to insert + if (_this.pos === 0) { + return checkDone(_this, callback); + } + + ++_this.state.outstandingRequests; + + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + var remnant = Buffer.alloc(_this.pos); + _this.bufToStore.copy(remnant, 0, 0, _this.pos); + if (_this.md5) { + _this.md5.update(remnant); + } + var doc = createChunkDoc(_this.id, _this.n, remnant); + + // If the stream was aborted, do not write remnant + if (checkAborted(_this, callback)) { + return false; + } + + _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + checkDone(_this); + }); +} + +/** + * @ignore + */ + +function checkAborted(_this, callback) { + if (_this.state.aborted) { + if (typeof callback === 'function') { + callback(new Error('this stream has been aborted')); + } + return true; + } + return false; +} + + +/***/ }), + +/***/ 3890: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var Binary = __webpack_require__(3994).BSON.Binary, + ObjectID = __webpack_require__(3994).BSON.ObjectID; + +var Buffer = __webpack_require__(1867).Buffer; + +/** + * Class for representing a single chunk in GridFS. + * + * @class + * + * @param file {GridStore} The {@link GridStore} object holding this chunk. + * @param mongoObject {object} The mongo object representation of this chunk. + * + * @throws Error when the type of data field for {@link mongoObject} is not + * supported. Currently supported types for data field are instances of + * {@link String}, {@link Array}, {@link Binary} and {@link Binary} + * from the bson module + * + * @see Chunk#buildMongoObject + */ +var Chunk = function(file, mongoObject, writeConcern) { + if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); + + this.file = file; + var mongoObjectFinal = mongoObject == null ? {} : mongoObject; + this.writeConcern = writeConcern || { w: 1 }; + this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; + this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; + this.data = new Binary(); + + if (typeof mongoObjectFinal.data === 'string') { + var buffer = Buffer.alloc(mongoObjectFinal.data.length); + buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); + this.data = new Binary(buffer); + } else if (Array.isArray(mongoObjectFinal.data)) { + buffer = Buffer.alloc(mongoObjectFinal.data.length); + var data = mongoObjectFinal.data.join(''); + buffer.write(data, 0, data.length, 'binary'); + this.data = new Binary(buffer); + } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { + this.data = mongoObjectFinal.data; + } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { + throw Error('Illegal chunk format'); + } + + // Update position + this.internalPosition = 0; +}; + +/** + * Writes a data to this object and advance the read/write head. + * + * @param data {string} the data to write + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.write = function(data, callback) { + this.data.write(data, this.internalPosition, data.length, 'binary'); + this.internalPosition = this.data.length(); + if (callback != null) return callback(null, this); + return this; +}; + +/** + * Reads data and advances the read/write head. + * + * @param length {number} The length of data to read. + * + * @return {string} The data read if the given length will not exceed the end of + * the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.read = function(length) { + // Default to full read if no index defined + length = length == null || length === 0 ? this.length() : length; + + if (this.length() - this.internalPosition + 1 >= length) { + var data = this.data.read(this.internalPosition, length); + this.internalPosition = this.internalPosition + length; + return data; + } else { + return ''; + } +}; + +Chunk.prototype.readSlice = function(length) { + if (this.length() - this.internalPosition >= length) { + var data = null; + if (this.data.buffer != null) { + //Pure BSON + data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); + } else { + //Native BSON + data = Buffer.alloc(length); + length = this.data.readInto(data, this.internalPosition); + } + this.internalPosition = this.internalPosition + length; + return data; + } else { + return null; + } +}; + +/** + * Checks if the read/write head is at the end. + * + * @return {boolean} Whether the read/write head has reached the end of this + * chunk. + */ +Chunk.prototype.eof = function() { + return this.internalPosition === this.length() ? true : false; +}; + +/** + * Reads one character from the data of this chunk and advances the read/write + * head. + * + * @return {string} a single character data read if the the read/write head is + * not at the end of the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.getc = function() { + return this.read(1); +}; + +/** + * Clears the contents of the data in this chunk and resets the read/write head + * to the initial position. + */ +Chunk.prototype.rewind = function() { + this.internalPosition = 0; + this.data = new Binary(); +}; + +/** + * Saves this chunk to the database. Also overwrites existing entries having the + * same id as this chunk. + * + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.save = function(options, callback) { + var self = this; + if (typeof options === 'function') { + callback = options; + options = {}; + } + + self.file.chunkCollection(function(err, collection) { + if (err) return callback(err); + + // Merge the options + var writeOptions = { upsert: true }; + for (var name in options) writeOptions[name] = options[name]; + for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; + + if (self.data.length() > 0) { + self.buildMongoObject(function(mongoObject) { + var options = { forceServerObjectId: true }; + for (var name in self.writeConcern) { + options[name] = self.writeConcern[name]; + } + + collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) { + callback(err, self); + }); + }); + } else { + callback(null, self); + } + // }); + }); +}; + +/** + * Creates a mongoDB object representation of this chunk. + * + * @param callback {function(Object)} This will be called after executing this + * method. The object will be passed to the first parameter and will have + * the structure: + * + *

+ *        {
+ *          '_id' : , // {number} id for this chunk
+ *          'files_id' : , // {number} foreign key to the file collection
+ *          'n' : , // {number} chunk number
+ *          'data' : , // {bson#Binary} the chunk data itself
+ *        }
+ *        
+ * + * @see MongoDB GridFS Chunk Object Structure + */ +Chunk.prototype.buildMongoObject = function(callback) { + var mongoObject = { + files_id: this.file.fileId, + n: this.chunkNumber, + data: this.data + }; + // If we are saving using a specific ObjectId + if (this.objectId != null) mongoObject._id = this.objectId; + + callback(mongoObject); +}; + +/** + * @return {number} the length of the data + */ +Chunk.prototype.length = function() { + return this.data.length(); +}; + +/** + * The position of the read/write head + * @name position + * @lends Chunk# + * @field + */ +Object.defineProperty(Chunk.prototype, 'position', { + enumerable: true, + get: function() { + return this.internalPosition; + }, + set: function(value) { + this.internalPosition = value; + } +}); + +/** + * The default chunk size + * @constant + */ +Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; + +module.exports = Chunk; + + +/***/ }), + +/***/ 9406: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/** + * @fileOverview GridFS is a tool for MongoDB to store files to the database. + * Because of the restrictions of the object size the database can hold, a + * facility to split a file into several chunks is needed. The {@link GridStore} + * class offers a simplified api to interact with files while managing the + * chunks of split files behind the scenes. More information about GridFS can be + * found here. + * + * @example + * const MongoClient = require('mongodb').MongoClient; + * const GridStore = require('mongodb').GridStore; + * const ObjectID = require('mongodb').ObjectID; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * const gridStore = new GridStore(db, null, "w"); + * gridStore.open(function(err, gridStore) { + * gridStore.write("hello world!", function(err, gridStore) { + * gridStore.close(function(err, result) { + * // Let's read the file using object Id + * GridStore.read(db, result._id, function(err, data) { + * test.equal('hello world!', data); + * client.close(); + * test.done(); + * }); + * }); + * }); + * }); + * }); + */ +const Chunk = __webpack_require__(3890); +const ObjectID = __webpack_require__(3994).BSON.ObjectID; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const Buffer = __webpack_require__(1867).Buffer; +const fs = __webpack_require__(5747); +const f = __webpack_require__(1669).format; +const util = __webpack_require__(1669); +const MongoError = __webpack_require__(3994).MongoError; +const inherits = util.inherits; +const Duplex = __webpack_require__(2413).Duplex; +const shallowClone = __webpack_require__(1371).shallowClone; +const executeLegacyOperation = __webpack_require__(1371).executeLegacyOperation; +const deprecate = __webpack_require__(1669).deprecate; + +var REFERENCE_BY_FILENAME = 0, + REFERENCE_BY_ID = 1; + +const deprecationFn = deprecate(() => {}, +'GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead'); + +/** + * Namespace provided by the core module + * @external Duplex + */ + +/** + * Create a new GridStore instance + * + * Modes + * - **"r"** - read only. This is the default mode. + * - **"w"** - write in truncate mode. Existing data will be overwritten. + * + * @class + * @param {Db} db A database instance to interact with. + * @param {object} [id] optional unique id for this file + * @param {string} [filename] optional filename for this file, no unique constrain on the field + * @param {string} mode set the mode for this file. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {string} [options.root] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {string} [options.content_type] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. + * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. + * @param {object} [options.metadata] Arbitrary data the user wants to store. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @property {number} chunkSize Get the gridstore chunk size. + * @property {number} md5 The md5 checksum for this file. + * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory + * @return {GridStore} a GridStore instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStore = function GridStore(db, id, filename, mode, options) { + deprecationFn(); + if (!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); + this.db = db; + + // Handle options + if (typeof options === 'undefined') options = {}; + // Handle mode + if (typeof mode === 'undefined') { + mode = filename; + filename = undefined; + } else if (typeof mode === 'object') { + options = mode; + mode = filename; + filename = undefined; + } + + if (id && id._bsontype === 'ObjectID') { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } else if (typeof filename === 'undefined') { + this.referenceBy = REFERENCE_BY_FILENAME; + this.filename = id; + if (mode.indexOf('w') != null) { + this.fileId = new ObjectID(); + } + } else { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } + + // Set up the rest + this.mode = mode == null ? 'r' : mode; + this.options = options || {}; + + // Opened + this.isOpen = false; + + // Set the root if overridden + this.root = + this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; + this.position = 0; + this.readPreference = + this.options.readPreference || db.options.readPreference || ReadPreference.primary; + this.writeConcern = _getWriteConcern(db, this.options); + // Set default chunk size + this.internalChunkSize = + this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; + + // Get the promiseLibrary + var promiseLibrary = this.options.promiseLibrary || Promise; + + // Set the promiseLibrary + this.promiseLibrary = promiseLibrary; + + Object.defineProperty(this, 'chunkSize', { + enumerable: true, + get: function() { + return this.internalChunkSize; + }, + set: function(value) { + if (!(this.mode[0] === 'w' && this.position === 0 && this.uploadDate == null)) { + this.internalChunkSize = this.internalChunkSize; + } else { + this.internalChunkSize = value; + } + } + }); + + Object.defineProperty(this, 'md5', { + enumerable: true, + get: function() { + return this.internalMd5; + } + }); + + Object.defineProperty(this, 'chunkNumber', { + enumerable: true, + get: function() { + return this.currentChunk && this.currentChunk.chunkNumber + ? this.currentChunk.chunkNumber + : null; + } + }); +}; + +/** + * The callback format for the Gridstore.open method + * @callback GridStore~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The GridStore instance if the open method was successful. + */ + +/** + * Opens the file from the database and initialize this object. Also creates a + * new one if file does not exist. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~openCallback} [callback] this will be called after executing this method + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.open = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (this.mode !== 'w' && this.mode !== 'w+' && this.mode !== 'r') { + throw MongoError.create({ message: 'Illegal mode ' + this.mode, driver: true }); + } + + return executeLegacyOperation(this.db.s.topology, open, [this, options, callback], { + skipSessions: true + }); +}; + +var open = function(self, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(self.db, self.options); + + // If we are writing we need to ensure we have the right indexes for md5's + if (self.mode === 'w' || self.mode === 'w+') { + // Get files collection + var collection = self.collection(); + // Put index on filename + collection.ensureIndex([['filename', 1]], writeConcern, function() { + // Get chunk collection + var chunkCollection = self.chunkCollection(); + // Make an unique index for compatibility with mongo-cxx-driver:legacy + var chunkIndexOptions = shallowClone(writeConcern); + chunkIndexOptions.unique = true; + // Ensure index on chunk collection + chunkCollection.ensureIndex( + [ + ['files_id', 1], + ['n', 1] + ], + chunkIndexOptions, + function() { + // Open the connection + _open(self, writeConcern, function(err, r) { + if (err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + } + ); + }); + } else { + // Open the gridstore + _open(self, writeConcern, function(err, r) { + if (err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + } +}; + +/** + * Verify if the file is at EOF. + * + * @method + * @return {boolean} true if the read/write head is at the end of this file. + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.eof = function() { + return this.position === this.length ? true : false; +}; + +/** + * The callback result format. + * @callback GridStore~resultCallback + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result from the callback. + */ + +/** + * Retrieves a single character from this file. + * + * @method + * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.getc = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, getc, [this, options, callback], { + skipSessions: true + }); +}; + +var getc = function(self, options, callback) { + if (self.eof()) { + callback(null, null); + } else if (self.currentChunk.eof()) { + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + self.currentChunk = chunk; + self.position = self.position + 1; + callback(err, self.currentChunk.getc()); + }); + } else { + self.position = self.position + 1; + callback(null, self.currentChunk.getc()); + } +}; + +/** + * Writes a string to the file with a newline character appended at the end if + * the given string does not have one. + * + * @method + * @param {string} string the string to write. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.puts = function(string, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + var finalString = string.match(/\n$/) == null ? string + '\n' : string; + return executeLegacyOperation( + this.db.s.topology, + this.write.bind(this), + [finalString, options, callback], + { skipSessions: true } + ); +}; + +/** + * Return a modified Readable stream including a possible transform method. + * + * @method + * @return {GridStoreStream} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.stream = function() { + return new GridStoreStream(this); +}; + +/** + * Writes some data. This method will work properly only if initialized with mode "w" or "w+". + * + * @method + * @param {(string|Buffer)} data the data to write. + * @param {boolean} [close] closes this file after writing if set to true. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.write = function write(data, close, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation( + this.db.s.topology, + _writeNormal, + [this, data, close, options, callback], + { skipSessions: true } + ); +}; + +/** + * Handles the destroy part of a stream + * + * @method + * @result {null} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.destroy = function destroy() { + // close and do not emit any more events. queued data is not sent. + if (!this.writable) return; + this.readable = false; + if (this.writable) { + this.writable = false; + this._q.length = 0; + this.emit('close'); + } +}; + +/** + * Stores a file from the file system to the GridFS database. + * + * @method + * @param {(string|Buffer|FileHandle)} file the file to store. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.writeFile = function(file, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, writeFile, [this, file, options, callback], { + skipSessions: true + }); +}; + +var writeFile = function(self, file, options, callback) { + if (typeof file === 'string') { + fs.open(file, 'r', function(err, fd) { + if (err) return callback(err); + self.writeFile(fd, callback); + }); + return; + } + + self.open(function(err, self) { + if (err) return callback(err, self); + + fs.fstat(file, function(err, stats) { + if (err) return callback(err, self); + + var offset = 0; + var index = 0; + + // Write a chunk + var writeChunk = function() { + // Allocate the buffer + var _buffer = Buffer.alloc(self.chunkSize); + // Read the file + fs.read(file, _buffer, 0, _buffer.length, offset, function(err, bytesRead, data) { + if (err) return callback(err, self); + + offset = offset + bytesRead; + + // Create a new chunk for the data + var chunk = new Chunk(self, { n: index++ }, self.writeConcern); + chunk.write(data.slice(0, bytesRead), function(err, chunk) { + if (err) return callback(err, self); + + chunk.save({}, function(err) { + if (err) return callback(err, self); + + self.position = self.position + bytesRead; + + // Point to current chunk + self.currentChunk = chunk; + + if (offset >= stats.size) { + fs.close(file, function(err) { + if (err) return callback(err); + + self.close(function(err) { + if (err) return callback(err, self); + return callback(null, self); + }); + }); + } else { + return process.nextTick(writeChunk); + } + }); + }); + }); + }; + + // Process the first write + process.nextTick(writeChunk); + }); + }); +}; + +/** + * Saves this file to the database. This will overwrite the old entry if it + * already exists. This will work properly only if mode was initialized to + * "w" or "w+". + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.close = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, close, [this, options, callback], { + skipSessions: true + }); +}; + +var close = function(self, options, callback) { + if (self.mode[0] === 'w') { + // Set up options + options = Object.assign({}, self.writeConcern, options); + + if (self.currentChunk != null && self.currentChunk.position > 0) { + self.currentChunk.save({}, function(err) { + if (err && typeof callback === 'function') return callback(err); + + self.collection(function(err, files) { + if (err && typeof callback === 'function') return callback(err); + + // Build the mongo object + if (self.uploadDate != null) { + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + } else { + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + } + }); + }); + } else { + self.collection(function(err, files) { + if (err && typeof callback === 'function') return callback(err); + + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + }); + } + } else if (self.mode[0] === 'r') { + if (typeof callback === 'function') callback(null, null); + } else { + if (typeof callback === 'function') + callback(MongoError.create({ message: f('Illegal mode %s', self.mode), driver: true })); + } +}; + +/** + * The collection callback format. + * @callback GridStore~collectionCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection from the command execution. + */ + +/** + * Retrieve this file's chunks collection. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.chunkCollection = function(callback) { + if (typeof callback === 'function') return this.db.collection(this.root + '.chunks', callback); + return this.db.collection(this.root + '.chunks'); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.unlink = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, unlink, [this, options, callback], { + skipSessions: true + }); +}; + +var unlink = function(self, options, callback) { + deleteChunks(self, function(err) { + if (err !== null) { + err.message = 'at deleteChunks: ' + err.message; + return callback(err); + } + + self.collection(function(err, collection) { + if (err !== null) { + err.message = 'at collection: ' + err.message; + return callback(err); + } + + collection.remove({ _id: self.fileId }, self.writeConcern, function(err) { + callback(err, self); + }); + }); + }); +}; + +/** + * Retrieves the file collection associated with this object. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.collection = function(callback) { + if (typeof callback === 'function') this.db.collection(this.root + '.files', callback); + return this.db.collection(this.root + '.files'); +}; + +/** + * The readlines callback format. + * @callback GridStore~readlinesCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {string[]} strings The array of strings returned. + */ + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.readlines = function(separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + separator = args.length ? args.shift() : '\n'; + separator = separator || '\n'; + options = args.length ? args.shift() : {}; + + return executeLegacyOperation( + this.db.s.topology, + readlines, + [this, separator, options, callback], + { skipSessions: true } + ); +}; + +var readlines = function(self, separator, options, callback) { + self.read(function(err, data) { + if (err) return callback(err); + + var items = data.toString().split(separator); + items = items.length > 0 ? items.splice(0, items.length - 1) : []; + for (var i = 0; i < items.length; i++) { + items[i] = items[i] + separator; + } + + callback(null, items); + }); +}; + +/** + * Deletes all the chunks of this file in the database if mode was set to "w" or + * "w+" and resets the read/write head to the initial position. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.rewind = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, rewind, [this, options, callback], { + skipSessions: true + }); +}; + +var rewind = function(self, options, callback) { + if (self.currentChunk.chunkNumber !== 0) { + if (self.mode[0] === 'w') { + deleteChunks(self, function(err) { + if (err) return callback(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.position = 0; + callback(null, self); + }); + } else { + self.currentChunk(0, function(err, chunk) { + if (err) return callback(err); + self.currentChunk = chunk; + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + }); + } + } else { + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + } +}; + +/** + * The read callback format. + * @callback GridStore~readCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Buffer} data The data read from the GridStore object + */ + +/** + * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. + * + * There are 3 signatures for this method: + * + * (callback) + * (length, callback) + * (length, buffer, callback) + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.read = function(length, buffer, options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + length = args.length ? args.shift() : null; + buffer = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + + return executeLegacyOperation( + this.db.s.topology, + read, + [this, length, buffer, options, callback], + { skipSessions: true } + ); +}; + +var read = function(self, length, buffer, options, callback) { + // The data is a c-terminated string and thus the length - 1 + var finalLength = length == null ? self.length - self.position : length; + var finalBuffer = buffer == null ? Buffer.alloc(finalLength) : buffer; + // Add a index to buffer to keep track of writing position or apply current index + finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; + + if (self.currentChunk.length() - self.currentChunk.position + finalBuffer._index >= finalLength) { + var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update internal position + self.position = self.position + finalBuffer.length; + // Check if we don't have a file at all + if (finalLength === 0 && finalBuffer.length === 0) + return callback(MongoError.create({ message: 'File does not exist', driver: true }), null); + // Else return data + return callback(null, finalBuffer); + } + + // Read the next chunk + slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update index position + finalBuffer._index += slice.length; + + // Load next chunk and read more + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + if (err) return callback(err); + + if (chunk.length() > 0) { + self.currentChunk = chunk; + self.read(length, finalBuffer, callback); + } else { + if (finalBuffer._index > 0) { + callback(null, finalBuffer); + } else { + callback( + MongoError.create({ + message: 'no chunks found for file, possibly corrupt', + driver: true + }), + null + ); + } + } + }); +}; + +/** + * The tell callback format. + * @callback GridStore~tellCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} position The current read position in the GridStore. + */ + +/** + * Retrieves the position of the read/write head of this file. + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~tellCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.tell = function(callback) { + var self = this; + // We provided a callback leg + if (typeof callback === 'function') return callback(null, this.position); + // Return promise + return new self.promiseLibrary(function(resolve) { + resolve(self.position); + }); +}; + +/** + * The tell callback format. + * @callback GridStore~gridStoreCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The gridStore. + */ + +/** + * Moves the read/write head to a new location. + * + * There are 3 signatures for this method + * + * Seek Location Modes + * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. + * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. + * - **GridStore.IO_SEEK_END**, set the position from the end of the file. + * + * @method + * @param {number} [position] the position to seek to + * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~gridStoreCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.seek = function(position, seekLocation, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + seekLocation = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + + return executeLegacyOperation( + this.db.s.topology, + seek, + [this, position, seekLocation, options, callback], + { skipSessions: true } + ); +}; + +var seek = function(self, position, seekLocation, options, callback) { + // Seek only supports read mode + if (self.mode !== 'r') { + return callback( + MongoError.create({ message: 'seek is only supported for mode r', driver: true }) + ); + } + + var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; + var finalPosition = position; + var targetPosition = 0; + + // Calculate the position + if (seekLocationFinal === GridStore.IO_SEEK_CUR) { + targetPosition = self.position + finalPosition; + } else if (seekLocationFinal === GridStore.IO_SEEK_END) { + targetPosition = self.length + finalPosition; + } else { + targetPosition = finalPosition; + } + + // Get the chunk + var newChunkNumber = Math.floor(targetPosition / self.chunkSize); + var seekChunk = function() { + nthChunk(self, newChunkNumber, function(err, chunk) { + if (err) return callback(err, null); + if (chunk == null) return callback(new Error('no chunk found')); + + // Set the current chunk + self.currentChunk = chunk; + self.position = targetPosition; + self.currentChunk.position = self.position % self.chunkSize; + callback(err, self); + }); + }; + + seekChunk(); +}; + +/** + * @ignore + */ +var _open = function(self, options, callback) { + var collection = self.collection(); + // Create the query + var query = + self.referenceBy === REFERENCE_BY_ID ? { _id: self.fileId } : { filename: self.filename }; + query = null == self.fileId && self.filename == null ? null : query; + options.readPreference = self.readPreference; + + // Fetch the chunks + if (query != null) { + collection.findOne(query, options, function(err, doc) { + if (err) { + return error(err); + } + + // Check if the collection for the files exists otherwise prepare the new one + if (doc != null) { + self.fileId = doc._id; + // Prefer a new filename over the existing one if this is a write + self.filename = + self.mode === 'r' || self.filename === undefined ? doc.filename : self.filename; + self.contentType = doc.contentType; + self.internalChunkSize = doc.chunkSize; + self.uploadDate = doc.uploadDate; + self.aliases = doc.aliases; + self.length = doc.length; + self.metadata = doc.metadata; + self.internalMd5 = doc.md5; + } else if (self.mode !== 'r') { + self.fileId = self.fileId == null ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = + self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + } else { + self.length = 0; + var txtId = self.fileId._bsontype === 'ObjectID' ? self.fileId.toHexString() : self.fileId; + return error( + MongoError.create({ + message: f( + 'file with id %s not opened for writing', + self.referenceBy === REFERENCE_BY_ID ? txtId : self.filename + ), + driver: true + }), + self + ); + } + + // Process the mode of the object + if (self.mode === 'r') { + nthChunk(self, 0, options, function(err, chunk) { + if (err) return error(err); + self.currentChunk = chunk; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w' && doc) { + // Delete any existing chunks + deleteChunks(self, options, function(err) { + if (err) return error(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null + ? self.internalChunkSize + : self.options['chunk_size']; + self.metadata = + self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w') { + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + } else if (self.mode === 'w+') { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if (err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = + self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + }); + } else { + // Write only mode + self.fileId = null == self.fileId ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = + self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + + // No file exists set up write mode + if (self.mode === 'w') { + // Delete any existing chunks + deleteChunks(self, options, function(err) { + if (err) return error(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w+') { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if (err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + } + + // only pass error to callback once + function error(err) { + if (error.err) return; + callback((error.err = err)); + } +}; + +/** + * @ignore + */ +var writeBuffer = function(self, buffer, close, callback) { + if (typeof close === 'function') { + callback = close; + close = null; + } + var finalClose = typeof close === 'boolean' ? close : false; + + if (self.mode !== 'w') { + callback( + MongoError.create({ + message: f( + 'file with id %s not opened for writing', + self.referenceBy === REFERENCE_BY_ID ? self.referenceBy : self.filename + ), + driver: true + }), + null + ); + } else { + if (self.currentChunk.position + buffer.length >= self.chunkSize) { + // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left + // to a new chunk (recursively) + var previousChunkNumber = self.currentChunk.chunkNumber; + var leftOverDataSize = self.chunkSize - self.currentChunk.position; + var firstChunkData = buffer.slice(0, leftOverDataSize); + var leftOverData = buffer.slice(leftOverDataSize); + // A list of chunks to write out + var chunksToWrite = [self.currentChunk.write(firstChunkData)]; + // If we have more data left than the chunk size let's keep writing new chunks + while (leftOverData.length >= self.chunkSize) { + // Create a new chunk and write to it + var newChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); + firstChunkData = leftOverData.slice(0, self.chunkSize); + leftOverData = leftOverData.slice(self.chunkSize); + // Update chunk number + previousChunkNumber = previousChunkNumber + 1; + // Write data + newChunk.write(firstChunkData); + // Push chunk to save list + chunksToWrite.push(newChunk); + } + + // Set current chunk with remaining data + self.currentChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); + // If we have left over data write it + if (leftOverData.length > 0) self.currentChunk.write(leftOverData); + + // Update the position for the gridstore + self.position = self.position + buffer.length; + // Total number of chunks to write + var numberOfChunksToWrite = chunksToWrite.length; + + for (var i = 0; i < chunksToWrite.length; i++) { + chunksToWrite[i].save({}, function(err) { + if (err) return callback(err); + + numberOfChunksToWrite = numberOfChunksToWrite - 1; + + if (numberOfChunksToWrite <= 0) { + // We care closing the file before returning + if (finalClose) { + return self.close(function(err) { + callback(err, self); + }); + } + + // Return normally + return callback(null, self); + } + }); + } + } else { + // Update the position for the gridstore + self.position = self.position + buffer.length; + // We have less data than the chunk size just write it and callback + self.currentChunk.write(buffer); + // We care closing the file before returning + if (finalClose) { + return self.close(function(err) { + callback(err, self); + }); + } + // Return normally + return callback(null, self); + } + } +}; + +/** + * Creates a mongoDB object representation of this object. + * + *

+ *        {
+ *          '_id' : , // {number} id for this file
+ *          'filename' : , // {string} name for this file
+ *          'contentType' : , // {string} mime type for this file
+ *          'length' : , // {number} size of this file?
+ *          'chunksize' : , // {number} chunk size used by this file
+ *          'uploadDate' : , // {Date}
+ *          'aliases' : , // {array of string}
+ *          'metadata' : , // {string}
+ *        }
+ *        
+ * + * @ignore + */ +var buildMongoObject = function(self, callback) { + // Calcuate the length + var mongoObject = { + _id: self.fileId, + filename: self.filename, + contentType: self.contentType, + length: self.position ? self.position : 0, + chunkSize: self.chunkSize, + uploadDate: self.uploadDate, + aliases: self.aliases, + metadata: self.metadata + }; + + var md5Command = { filemd5: self.fileId, root: self.root }; + self.db.command(md5Command, function(err, results) { + if (err) return callback(err); + + mongoObject.md5 = results.md5; + callback(null, mongoObject); + }); +}; + +/** + * Gets the nth chunk of this file. + * @ignore + */ +var nthChunk = function(self, chunkNumber, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + options.readPreference = self.readPreference; + // Get the nth chunk + self + .chunkCollection() + .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { + if (err) return callback(err); + + var finalChunk = chunk == null ? {} : chunk; + callback(null, new Chunk(self, finalChunk, self.writeConcern)); + }); +}; + +/** + * @ignore + */ +var lastChunkNumber = function(self) { + return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @ignore + */ +var deleteChunks = function(self, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + + if (self.fileId != null) { + self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { + if (err) return callback(err, false); + callback(null, true); + }); + } else { + callback(null, true); + } +}; + +/** + * The collection to be used for holding the files and chunks collection. + * + * @classconstant DEFAULT_ROOT_COLLECTION + */ +GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; + +/** + * Default file mime type + * + * @classconstant DEFAULT_CONTENT_TYPE + */ +GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; + +/** + * Seek mode where the given length is absolute. + * + * @classconstant IO_SEEK_SET + */ +GridStore.IO_SEEK_SET = 0; + +/** + * Seek mode where the given length is an offset to the current read/write head. + * + * @classconstant IO_SEEK_CUR + */ +GridStore.IO_SEEK_CUR = 1; + +/** + * Seek mode where the given length is an offset to the end of the file. + * + * @classconstant IO_SEEK_END + */ +GridStore.IO_SEEK_END = 2; + +/** + * Checks if a file exists in the database. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file to look for. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeLegacyOperation( + db.s.topology, + exists, + [db, fileIdObject, rootCollection, options, callback], + { skipSessions: true } + ); +}; + +var exists = function(db, fileIdObject, rootCollection, options, callback) { + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Fetch collection + var rootCollectionFinal = + rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + db.collection(rootCollectionFinal + '.files', function(err, collection) { + if (err) return callback(err); + + // Build query + var query = + typeof fileIdObject === 'string' || + Object.prototype.toString.call(fileIdObject) === '[object RegExp]' + ? { filename: fileIdObject } + : { _id: fileIdObject }; // Attempt to locate file + + // We have a specific query + if ( + fileIdObject != null && + typeof fileIdObject === 'object' && + Object.prototype.toString.call(fileIdObject) !== '[object RegExp]' + ) { + query = fileIdObject; + } + + // Check if the entry exists + collection.findOne(query, { readPreference: readPreference }, function(err, item) { + if (err) return callback(err); + callback(null, item == null ? false : true); + }); + }); +}; + +/** + * Gets the list of files stored in the GridFS. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.list = function(db, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeLegacyOperation(db.s.topology, list, [db, rootCollection, options, callback], { + skipSessions: true + }); +}; + +var list = function(db, rootCollection, options, callback) { + // Ensure we have correct values + if (rootCollection != null && typeof rootCollection === 'object') { + options = rootCollection; + rootCollection = null; + } + + // Establish read preference + var readPreference = options.readPreference || ReadPreference.primary; + // Check if we are returning by id not filename + var byId = options['id'] != null ? options['id'] : false; + // Fetch item + var rootCollectionFinal = + rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + var items = []; + db.collection(rootCollectionFinal + '.files', function(err, collection) { + if (err) return callback(err); + + collection.find({}, { readPreference: readPreference }, function(err, cursor) { + if (err) return callback(err); + + cursor.each(function(err, item) { + if (item != null) { + items.push(byId ? item._id : item.filename); + } else { + callback(err, items); + } + }); + }); + }); +}; + +/** + * Reads the contents of a file. + * + * This method has the following signatures + * + * (db, name, callback) + * (db, name, length, callback) + * (db, name, length, offset, callback) + * (db, name, length, offset, options, callback) + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file. + * @param {number} [length] The size of data to read. + * @param {number} [offset] The offset from the head of the file of which to start reading from. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.read = function(db, name, length, offset, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + length = args.length ? args.shift() : null; + offset = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + return executeLegacyOperation( + db.s.topology, + readStatic, + [db, name, length, offset, options, callback], + { skipSessions: true } + ); +}; + +var readStatic = function(db, name, length, offset, options, callback) { + new GridStore(db, name, 'r', options).open(function(err, gridStore) { + if (err) return callback(err); + // Make sure we are not reading out of bounds + if (offset && offset >= gridStore.length) + return callback('offset larger than size of file', null); + if (length && length > gridStore.length) + return callback('length is larger than the size of the file', null); + if (offset && length && offset + length > gridStore.length) + return callback('offset and length is larger than the size of the file', null); + + if (offset != null) { + gridStore.seek(offset, function(err, gridStore) { + if (err) return callback(err); + gridStore.read(length, callback); + }); + } else { + gridStore.read(length, callback); + } + }); +}; + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {(String|object)} name the name of the file. + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.readlines = function(db, name, separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + separator = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + return executeLegacyOperation( + db.s.topology, + readlinesStatic, + [db, name, separator, options, callback], + { skipSessions: true } + ); +}; + +var readlinesStatic = function(db, name, separator, options, callback) { + var finalSeperator = separator == null ? '\n' : separator; + new GridStore(db, name, 'r', options).open(function(err, gridStore) { + if (err) return callback(err); + gridStore.readlines(finalSeperator, callback); + }); +}; + +/** + * Deletes the chunks and metadata information of a file from GridFS. + * + * @method + * @static + * @param {Db} db The database to query. + * @param {(string|array)} names The name/names of the files to delete. + * @param {object} [options] Optional settings. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.unlink = function(db, names, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeLegacyOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], { + skipSessions: true + }); +}; + +var unlinkStatic = function(self, db, names, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(db, options); + + // List of names + if (names.constructor === Array) { + var tc = 0; + for (var i = 0; i < names.length; i++) { + ++tc; + GridStore.unlink(db, names[i], options, function() { + if (--tc === 0) { + callback(null, self); + } + }); + } + } else { + new GridStore(db, names, 'w', options).open(function(err, gridStore) { + if (err) return callback(err); + deleteChunks(gridStore, function(err) { + if (err) return callback(err); + gridStore.collection(function(err, collection) { + if (err) return callback(err); + collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) { + callback(err, self); + }); + }); + }); + }); + } +}; + +/** + * @ignore + */ +var _writeNormal = function(self, data, close, options, callback) { + // If we have a buffer write it using the writeBuffer method + if (Buffer.isBuffer(data)) { + return writeBuffer(self, data, close, callback); + } else { + return writeBuffer(self, Buffer.from(data, 'binary'), close, callback); + } +}; + +/** + * @ignore + */ +var _setWriteConcernHash = function(options) { + var finalOptions = {}; + if (options.w != null) finalOptions.w = options.w; + if (options.journal === true) finalOptions.j = options.journal; + if (options.j === true) finalOptions.j = options.j; + if (options.fsync === true) finalOptions.fsync = options.fsync; + if (options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; + return finalOptions; +}; + +/** + * @ignore + */ +var _getWriteConcern = function(self, options) { + // Final options + var finalOptions = { w: 1 }; + options = options || {}; + + // Local options verification + if ( + options.w != null || + typeof options.j === 'boolean' || + typeof options.journal === 'boolean' || + typeof options.fsync === 'boolean' + ) { + finalOptions = _setWriteConcernHash(options); + } else if (options.safe != null && typeof options.safe === 'object') { + finalOptions = _setWriteConcernHash(options.safe); + } else if (typeof options.safe === 'boolean') { + finalOptions = { w: options.safe ? 1 : 0 }; + } else if ( + self.options.w != null || + typeof self.options.j === 'boolean' || + typeof self.options.journal === 'boolean' || + typeof self.options.fsync === 'boolean' + ) { + finalOptions = _setWriteConcernHash(self.options); + } else if ( + self.safe && + (self.safe.w != null || + typeof self.safe.j === 'boolean' || + typeof self.safe.journal === 'boolean' || + typeof self.safe.fsync === 'boolean') + ) { + finalOptions = _setWriteConcernHash(self.safe); + } else if (typeof self.safe === 'boolean') { + finalOptions = { w: self.safe ? 1 : 0 }; + } + + // Ensure we don't have an invalid combination of write concerns + if ( + finalOptions.w < 1 && + (finalOptions.journal === true || finalOptions.j === true || finalOptions.fsync === true) + ) + throw MongoError.create({ + message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true', + driver: true + }); + + // Return the options + return finalOptions; +}; + +/** + * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @extends external:Duplex + * @return {GridStoreStream} a GridStoreStream instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStoreStream = function(gs) { + // Initialize the duplex stream + Duplex.call(this); + + // Get the gridstore + this.gs = gs; + + // End called + this.endCalled = false; + + // If we have a seek + this.totalBytesToRead = this.gs.length - this.gs.position; + this.seekPosition = this.gs.position; +}; + +// +// Inherit duplex +inherits(GridStoreStream, Duplex); + +GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; + +// Set up override +GridStoreStream.prototype.pipe = function(destination) { + var self = this; + + // Only open gridstore if not already open + if (!self.gs.isOpen) { + self.gs.open(function(err) { + if (err) return self.emit('error', err); + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + }); + } else { + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + } + + return destination; +}; + +// Called by stream +GridStoreStream.prototype._read = function() { + var self = this; + + var read = function() { + // Read data + self.gs.read(length, function(err, buffer) { + if (err && !self.endCalled) return self.emit('error', err); + + // Stream is closed + if (self.endCalled || buffer == null) return self.push(null); + // Remove bytes read + if (buffer.length <= self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer.length; + self.push(buffer); + } else if (buffer.length > self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer._index; + self.push(buffer.slice(0, buffer._index)); + } + + // Finished reading + if (self.totalBytesToRead <= 0) { + self.endCalled = true; + } + }); + }; + + // Set read length + var length = + self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; + if (!self.gs.isOpen) { + self.gs.open(function(err) { + self.totalBytesToRead = self.gs.length - self.gs.position; + if (err) return self.emit('error', err); + read(); + }); + } else { + read(); + } +}; + +GridStoreStream.prototype.destroy = function() { + this.pause(); + this.endCalled = true; + this.gs.close(); + this.emit('end'); +}; + +GridStoreStream.prototype.write = function(chunk) { + var self = this; + if (self.endCalled) + return self.emit( + 'error', + MongoError.create({ message: 'attempting to write to stream after end called', driver: true }) + ); + // Do we have to open the gridstore + if (!self.gs.isOpen) { + self.gs.open(function() { + self.gs.isOpen = true; + self.gs.write(chunk, function() { + process.nextTick(function() { + self.emit('drain'); + }); + }); + }); + return false; + } else { + self.gs.write(chunk, function() { + self.emit('drain'); + }); + return true; + } +}; + +GridStoreStream.prototype.end = function(chunk, encoding, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + chunk = args.length ? args.shift() : null; + encoding = args.length ? args.shift() : null; + self.endCalled = true; + + if (chunk) { + self.gs.write(chunk, function() { + self.gs.close(function() { + if (typeof callback === 'function') callback(); + self.emit('end'); + }); + }); + } + + self.gs.close(function() { + if (typeof callback === 'function') callback(); + self.emit('end'); + }); +}; + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Duplex#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Duplex#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Duplex#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Duplex#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Duplex#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Duplex#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Duplex#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Duplex#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +/** + * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. + * @function external:Duplex#write + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {boolean} + */ + +/** + * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. + * @function external:Duplex#end + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {null} + */ + +/** + * GridStoreStream stream data event, fired for each document in the cursor. + * + * @event GridStoreStream#data + * @type {object} + */ + +/** + * GridStoreStream stream end event + * + * @event GridStoreStream#end + * @type {null} + */ + +/** + * GridStoreStream stream close event + * + * @event GridStoreStream#close + * @type {null} + */ + +/** + * GridStoreStream stream readable event + * + * @event GridStoreStream#readable + * @type {null} + */ + +/** + * GridStoreStream stream drain event + * + * @event GridStoreStream#drain + * @type {null} + */ + +/** + * GridStoreStream stream finish event + * + * @event GridStoreStream#finish + * @type {null} + */ + +/** + * GridStoreStream stream pipe event + * + * @event GridStoreStream#pipe + * @type {null} + */ + +/** + * GridStoreStream stream unpipe event + * + * @event GridStoreStream#unpipe + * @type {null} + */ + +/** + * GridStoreStream stream error event + * + * @event GridStoreStream#error + * @type {null} + */ + +/** + * @ignore + */ +module.exports = GridStore; + + +/***/ }), + +/***/ 1545: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const ChangeStream = __webpack_require__(1117); +const Db = __webpack_require__(6662); +const EventEmitter = __webpack_require__(8614).EventEmitter; +const inherits = __webpack_require__(1669).inherits; +const MongoError = __webpack_require__(3994).MongoError; +const deprecate = __webpack_require__(1669).deprecate; +const WriteConcern = __webpack_require__(2481); +const MongoDBNamespace = __webpack_require__(1371).MongoDBNamespace; +const ReadPreference = __webpack_require__(4485); +const maybePromise = __webpack_require__(1371).maybePromise; +const NativeTopology = __webpack_require__(2632); +const connect = __webpack_require__(5210).connect; +const validOptions = __webpack_require__(5210).validOptions; + +/** + * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. + * + * @example + * // Connect using a MongoClient instance + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * const mongoClient = new MongoClient(url); + * mongoClient.connect(function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * + * @example + * // Connect using the MongoClient.connect static method + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + */ + +/** + * A string specifying the level of a ReadConcern + * @typedef {'local'|'available'|'majority'|'linearizable'|'snapshot'} ReadConcernLevel + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html#read-concern-levels + */ + +/** + * Configuration options for drivers wrapping the node driver. + * + * @typedef {Object} DriverInfoOptions + * @property {string} [name] The name of the driver + * @property {string} [version] The version of the driver + * @property {string} [platform] Optional platform information + */ + +/** + * Configuration options for drivers wrapping the node driver. + * + * @typedef {Object} DriverInfoOptions + * @property {string} [name] The name of the driver + * @property {string} [version] The version of the driver + * @property {string} [platform] Optional platform information + */ + +/** + * Creates a new MongoClient instance + * @class + * @param {string} url The connection URI string + * @param {object} [options] Optional settings + * @param {number} [options.poolSize=5] The maximum size of the individual server pool + * @param {boolean} [options.ssl=false] Enable SSL connection. *deprecated* use `tls` variants + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority + * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer *deprecated* use `tls` variants + * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer *deprecated* use `tls` variants + * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer *deprecated* use `tls` variants + * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase *deprecated* use `tls` variants + * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer *deprecated* use `tls` variants + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. *deprecated* use `tls` variants + * @param {boolean} [options.tls=false] Enable TLS connections + * @param {boolean} [options.tlsInsecure=false] Relax TLS constraints, disabling validation + * @param {string} [options.tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection + * @param {string} [options.tlsCertificateKeyFile] A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated + * @param {string} [options.tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections + * @param {boolean} [options.tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid + * @param {boolean} [options.tlsAllowInvalidHostnames] Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate + * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out + * @param {number} [options.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out + * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). + * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {string} [options.replicaSet=undefined] The Replicaset set name + * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {string} [options.authSource=undefined] Define the database to authenticate against + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j=false] Specify a journal write concern + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) + * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) + * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) + * @param {object} [options.logger=undefined] Custom logger object + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers + * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit + * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness + * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections + * @param {string} [options.auth.user=undefined] The username for auth + * @param {string} [options.auth.password=undefined] The password for auth + * @param {string} [options.authMechanism] An authentication mechanism to use for connection authentication, see the {@link https://docs.mongodb.com/manual/reference/connection-string/#urioption.authMechanism|authMechanism} reference for supported options. + * @param {object} [options.compression] Type of compression to use: snappy or zlib + * @param {boolean} [options.fsync=false] Specify a file sync write concern + * @param {array} [options.readPreferenceTags] Read preference tags + * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor + * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client + * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + * @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser. + * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer + * @param {Number} [options.localThresholdMS=15] **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers + * @param {Number} [options.serverSelectionTimeoutMS=30000] **Only applies to the unified topology** How long to block for server selection before throwing an error + * @param {Number} [options.heartbeatFrequencyMS=10000] **Only applies to the unified topology** The frequency with which topology updates are scheduled + * @param {number} [options.maxPoolSize=10] **Only applies to the unified topology** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. + * @param {number} [options.minPoolSize=0] **Only applies to the unified topology** The minimum number of connections that MUST exist at any moment in a single connection pool. + * @param {number} [options.maxIdleTimeMS] **Only applies to the unified topology** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. The default is infinity. + * @param {number} [options.waitQueueTimeoutMS=0] **Only applies to the unified topology** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. + * @param {AutoEncrypter~AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption + * @param {DriverInfoOptions} [options.driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver + * @param {boolean} [options.directConnection=false] Enable directConnection + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {MongoClient} a MongoClient instance + */ +function MongoClient(url, options) { + if (!(this instanceof MongoClient)) return new MongoClient(url, options); + // Set up event emitter + EventEmitter.call(this); + + // The internal state + this.s = { + url: url, + options: options || {}, + promiseLibrary: (options && options.promiseLibrary) || Promise, + dbCache: new Map(), + sessions: new Set(), + writeConcern: WriteConcern.fromOptions(options), + namespace: new MongoDBNamespace('admin') + }; +} + +/** + * @ignore + */ +inherits(MongoClient, EventEmitter); + +Object.defineProperty(MongoClient.prototype, 'writeConcern', { + enumerable: true, + get: function() { + return this.s.writeConcern; + } +}); + +Object.defineProperty(MongoClient.prototype, 'readPreference', { + enumerable: true, + get: function() { + return ReadPreference.primary; + } +}); + +/** + * The callback format for results + * @callback MongoClient~connectCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {MongoClient} client The connected client. + */ + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.prototype.connect = function(callback) { + if (typeof callback === 'string') { + throw new TypeError('`connect` only accepts a callback'); + } + + const client = this; + return maybePromise(this, callback, cb => { + const err = validOptions(client.s.options); + if (err) return cb(err); + + connect(client, client.s.url, client.s.options, err => { + if (err) return cb(err); + cb(null, client); + }); + }); +}; + +MongoClient.prototype.logout = deprecate(function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + if (typeof callback === 'function') callback(null, true); +}, 'Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient'); + +/** + * Close the db and its underlying connections + * @method + * @param {boolean} [force=false] Force close, emitting no events + * @param {Db~noResultCallback} [callback] The result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.prototype.close = function(force, callback) { + if (typeof force === 'function') { + callback = force; + force = false; + } + + const client = this; + return maybePromise(this, callback, cb => { + const completeClose = err => { + client.emit('close', client); + + if (!(client.topology instanceof NativeTopology)) { + for (const item of client.s.dbCache) { + item[1].emit('close', client); + } + } + + client.removeAllListeners('close'); + cb(err); + }; + + if (client.topology == null) { + completeClose(); + return; + } + + client.topology.close(force, err => { + const autoEncrypter = client.topology.s.options.autoEncrypter; + if (!autoEncrypter) { + completeClose(err); + return; + } + + autoEncrypter.teardown(force, err2 => completeClose(err || err2)); + }); + }); +}; + +/** + * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are + * related in a parent-child relationship to the original instance so that events are correctly emitted on child + * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. + * You can control these behaviors with the options noListener and returnNonCachedInstance. + * + * @method + * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string. + * @param {object} [options] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {Db} + */ +MongoClient.prototype.db = function(dbName, options) { + options = options || {}; + + // Default to db from connection string if not provided + if (!dbName) { + dbName = this.s.options.dbName; + } + + // Copy the options and add out internal override of the not shared flag + const finalOptions = Object.assign({}, this.s.options, options); + + // Do we have the db in the cache already + if (this.s.dbCache.has(dbName) && finalOptions.returnNonCachedInstance !== true) { + return this.s.dbCache.get(dbName); + } + + // Add promiseLibrary + finalOptions.promiseLibrary = this.s.promiseLibrary; + + // If no topology throw an error message + if (!this.topology) { + throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'); + } + + // Return the db object + const db = new Db(dbName, this.topology, finalOptions); + + // Add the db to the cache + this.s.dbCache.set(dbName, db); + // Return the database + return db; +}; + +/** + * Check if MongoClient is connected + * + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {boolean} + */ +MongoClient.prototype.isConnected = function(options) { + options = options || {}; + + if (!this.topology) return false; + return this.topology.isConnected(options); +}; + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @static + * @param {string} url The connection URI string + * @param {object} [options] Optional settings + * @param {number} [options.poolSize=5] The maximum size of the individual server pool + * @param {boolean} [options.ssl=false] Enable SSL connection. *deprecated* use `tls` variants + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority + * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer *deprecated* use `tls` variants + * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer *deprecated* use `tls` variants + * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer *deprecated* use `tls` variants + * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase *deprecated* use `tls` variants + * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer *deprecated* use `tls` variants + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. *deprecated* use `tls` variants + * @param {boolean} [options.tls=false] Enable TLS connections + * @param {boolean} [options.tlsInsecure=false] Relax TLS constraints, disabling validation + * @param {string} [options.tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection + * @param {string} [options.tlsCertificateKeyFile] A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated + * @param {string} [options.tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections + * @param {boolean} [options.tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid + * @param {boolean} [options.tlsAllowInvalidHostnames] Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate + * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out + * @param {number} [options.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out + * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). + * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {string} [options.replicaSet=undefined] The Replicaset set name + * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {string} [options.authSource=undefined] Define the database to authenticate against + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j=false] Specify a journal write concern + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) + * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) + * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) + * @param {object} [options.logger=undefined] Custom logger object + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers + * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit + * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness + * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections + * @param {string} [options.auth.user=undefined] The username for auth + * @param {string} [options.auth.password=undefined] The password for auth + * @param {string} [options.authMechanism] An authentication mechanism to use for connection authentication, see the {@link https://docs.mongodb.com/manual/reference/connection-string/#urioption.authMechanism|authMechanism} reference for supported options. + * @param {object} [options.compression] Type of compression to use: snappy or zlib + * @param {boolean} [options.fsync=false] Specify a file sync write concern + * @param {array} [options.readPreferenceTags] Read preference tags + * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor + * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client + * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + * @param {boolean} [options.directConnection=false] Enable directConnection + * @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser. + * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer + * @param {Number} [options.localThresholdMS=15] **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers + * @param {Number} [options.serverSelectionTimeoutMS=30000] **Only applies to the unified topology** How long to block for server selection before throwing an error + * @param {Number} [options.heartbeatFrequencyMS=10000] **Only applies to the unified topology** The frequency with which topology updates are scheduled + * @param {number} [options.maxPoolSize=10] **Only applies to the unified topology** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. + * @param {number} [options.minPoolSize=0] **Only applies to the unified topology** The minimum number of connections that MUST exist at any moment in a single connection pool. + * @param {number} [options.maxIdleTimeMS] **Only applies to the unified topology** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. The default is infinity. + * @param {number} [options.waitQueueTimeoutMS=0] **Only applies to the unified topology** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. + * @param {AutoEncrypter~AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption + * @param {DriverInfoOptions} [options.driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.connect = function(url, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : null; + options = options || {}; + + // Create client + const mongoClient = new MongoClient(url, options); + // Execute the connect method + return mongoClient.connect(callback); +}; + +/** + * Starts a new session on the server + * + * @param {SessionOptions} [options] optional settings for a driver session + * @return {ClientSession} the newly established session + */ +MongoClient.prototype.startSession = function(options) { + options = Object.assign({ explicit: true }, options); + if (!this.topology) { + throw new MongoError('Must connect to a server before calling this method'); + } + + if (!this.topology.hasSessionSupport()) { + throw new MongoError('Current topology does not support sessions'); + } + + return this.topology.startSession(options, this.s.options); +}; + +/** + * Runs a given operation with an implicitly created session. The lifetime of the session + * will be handled without the need for user interaction. + * + * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function) + * + * @param {Object} [options] Optional settings to be appled to implicitly created session + * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}` + * @return {Promise} + */ +MongoClient.prototype.withSession = function(options, operation) { + if (typeof options === 'function') (operation = options), (options = undefined); + const session = this.startSession(options); + + let cleanupHandler = (err, result, opts) => { + // prevent multiple calls to cleanupHandler + cleanupHandler = () => { + throw new ReferenceError('cleanupHandler was called too many times'); + }; + + opts = Object.assign({ throw: true }, opts); + session.endSession(); + + if (err) { + if (opts.throw) throw err; + return Promise.reject(err); + } + }; + + try { + const result = operation(session); + return Promise.resolve(result) + .then(result => cleanupHandler(null, result)) + .catch(err => cleanupHandler(err, null, { throw: true })); + } catch (err) { + return cleanupHandler(err, null, { throw: false }); + } +}; +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin, + * and config databases. + * @method + * @since 3.1.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +MongoClient.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * Return the mongo client logger + * @method + * @return {Logger} return the mongo client logger + * @ignore + */ +MongoClient.prototype.getLogger = function() { + return this.s.options.logger; +}; + +module.exports = MongoClient; + + +/***/ }), + +/***/ 7057: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const CommandOperation = __webpack_require__(499); +const defineAspects = __webpack_require__(1018).defineAspects; +const crypto = __webpack_require__(6417); +const handleCallback = __webpack_require__(1371).handleCallback; +const toError = __webpack_require__(1371).toError; + +class AddUserOperation extends CommandOperation { + constructor(db, username, password, options) { + super(db, options); + + this.username = username; + this.password = password; + } + + _buildCommand() { + const db = this.db; + const username = this.username; + const password = this.password; + const options = this.options; + + // Get additional values + let roles = Array.isArray(options.roles) ? options.roles : []; + + // If not roles defined print deprecated message + // TODO [$5f5fbe42fcabad09c1c241b4]: handle deprecation properly + if (roles.length === 0) { + console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); + } + + // Check the db name and add roles if needed + if ( + (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && + !Array.isArray(options.roles) + ) { + roles = ['root']; + } else if (!Array.isArray(options.roles)) { + roles = ['dbOwner']; + } + + const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; + + let userPassword = password; + + if (!digestPassword) { + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password); + userPassword = md5.digest('hex'); + } + + // Build the command to execute + const command = { + createUser: username, + customData: options.customData || {}, + roles: roles, + digestPassword + }; + + // No password + if (typeof password === 'string') { + command.pwd = userPassword; + } + + return command; + } + + execute(callback) { + const options = this.options; + + // Error out if digestPassword set + if (options.digestPassword != null) { + return callback( + toError( + "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." + ) + ); + } + + // Attempt to execute auth command + super.execute((err, r) => { + if (!err) { + return handleCallback(callback, err, r); + } + + return handleCallback(callback, err, null); + }); + } +} + +defineAspects(AddUserOperation, Aspect.WRITE_OPERATION); + +module.exports = AddUserOperation; + + +/***/ }), + +/***/ 1554: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const CommandOperationV2 = __webpack_require__(1189); +const MongoError = __webpack_require__(3994).MongoError; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; + +const DB_AGGREGATE_COLLECTION = 1; +const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; + +class AggregateOperation extends CommandOperationV2 { + constructor(parent, pipeline, options) { + super(parent, options, { fullResponse: true }); + + this.target = + parent.s.namespace && parent.s.namespace.collection + ? parent.s.namespace.collection + : DB_AGGREGATE_COLLECTION; + + this.pipeline = pipeline; + + // determine if we have a write stage, override read preference if so + this.hasWriteStage = false; + if (typeof options.out === 'string') { + this.pipeline = this.pipeline.concat({ $out: options.out }); + this.hasWriteStage = true; + } else if (pipeline.length > 0) { + const finalStage = pipeline[pipeline.length - 1]; + if (finalStage.$out || finalStage.$merge) { + this.hasWriteStage = true; + } + } + + if (this.hasWriteStage) { + this.readPreference = ReadPreference.primary; + } + + if (options.explain && (this.readConcern || this.writeConcern)) { + throw new MongoError( + '"explain" cannot be used on an aggregate call with readConcern/writeConcern' + ); + } + + if (options.cursor != null && typeof options.cursor !== 'object') { + throw new MongoError('cursor options must be an object'); + } + } + + get canRetryRead() { + return !this.hasWriteStage; + } + + addToPipeline(stage) { + this.pipeline.push(stage); + } + + execute(server, callback) { + const options = this.options; + const serverWireVersion = maxWireVersion(server); + const command = { aggregate: this.target, pipeline: this.pipeline }; + + if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { + this.readConcern = null; + } + + if (serverWireVersion >= 5) { + if (this.hasWriteStage && this.writeConcern) { + Object.assign(command, { writeConcern: this.writeConcern }); + } + } + + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + if (typeof options.allowDiskUse === 'boolean') { + command.allowDiskUse = options.allowDiskUse; + } + + if (options.hint) { + command.hint = options.hint; + } + + if (options.explain) { + options.full = false; + command.explain = options.explain; + } + + command.cursor = options.cursor || {}; + if (options.batchSize && !this.hasWriteStage) { + command.cursor.batchSize = options.batchSize; + } + + super.executeCommand(server, command, callback); + } +} + +defineAspects(AggregateOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = AggregateOperation; + + +/***/ }), + +/***/ 6976: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const applyRetryableWrites = __webpack_require__(1371).applyRetryableWrites; +const applyWriteConcern = __webpack_require__(1371).applyWriteConcern; +const MongoError = __webpack_require__(3994).MongoError; +const OperationBase = __webpack_require__(1018).OperationBase; + +class BulkWriteOperation extends OperationBase { + constructor(collection, operations, options) { + super(options); + + this.collection = collection; + this.operations = operations; + } + + execute(callback) { + const coll = this.collection; + const operations = this.operations; + let options = this.options; + + // Add ignoreUndfined + if (coll.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = coll.s.options.ignoreUndefined; + } + + // Create the bulk operation + const bulk = + options.ordered === true || options.ordered == null + ? coll.initializeOrderedBulkOp(options) + : coll.initializeUnorderedBulkOp(options); + + // Do we have a collation + let collation = false; + + // for each op go through and add to the bulk + try { + for (let i = 0; i < operations.length; i++) { + // Get the operation type + const key = Object.keys(operations[i])[0]; + // Check if we have a collation + if (operations[i][key].collation) { + collation = true; + } + + // Pass to the raw bulk + bulk.raw(operations[i]); + } + } catch (err) { + return callback(err, null); + } + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; + const capabilities = coll.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if (collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError('server/primary/mongos does not support collation')); + } + + // Execute the bulk + bulk.execute(writeCon, finalOptions, (err, r) => { + // We have connection level error + if (!r && err) { + return callback(err, null); + } + + r.insertedCount = r.nInserted; + r.matchedCount = r.nMatched; + r.modifiedCount = r.nModified || 0; + r.deletedCount = r.nRemoved; + r.upsertedCount = r.getUpsertedIds().length; + r.upsertedIds = {}; + r.insertedIds = {}; + + // Update the n + r.n = r.insertedCount; + + // Inserted documents + const inserted = r.getInsertedIds(); + // Map inserted ids + for (let i = 0; i < inserted.length; i++) { + r.insertedIds[inserted[i].index] = inserted[i]._id; + } + + // Upserted documents + const upserted = r.getUpsertedIds(); + // Map upserted ids + for (let i = 0; i < upserted.length; i++) { + r.upsertedIds[upserted[i].index] = upserted[i]._id; + } + + // Return the results + callback(null, r); + }); + } +} + +module.exports = BulkWriteOperation; + + +/***/ }), + +/***/ 6716: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const applyWriteConcern = __webpack_require__(1371).applyWriteConcern; +const Code = __webpack_require__(3994).BSON.Code; +const createIndexDb = __webpack_require__(2226).createIndex; +const decorateWithCollation = __webpack_require__(1371).decorateWithCollation; +const decorateWithReadConcern = __webpack_require__(1371).decorateWithReadConcern; +const ensureIndexDb = __webpack_require__(2226).ensureIndex; +const evaluate = __webpack_require__(2226).evaluate; +const executeCommand = __webpack_require__(2226).executeCommand; +const handleCallback = __webpack_require__(1371).handleCallback; +const indexInformationDb = __webpack_require__(2226).indexInformation; +const Long = __webpack_require__(3994).BSON.Long; +const MongoError = __webpack_require__(3994).MongoError; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const insertDocuments = __webpack_require__(2296).insertDocuments; +const updateDocuments = __webpack_require__(2296).updateDocuments; + +/** + * Group function helper + * @ignore + */ +// var groupFunction = function () { +// var c = db[ns].find(condition); +// var map = new Map(); +// var reduce_function = reduce; +// +// while (c.hasNext()) { +// var obj = c.next(); +// var key = {}; +// +// for (var i = 0, len = keys.length; i < len; ++i) { +// var k = keys[i]; +// key[k] = obj[k]; +// } +// +// var aggObj = map.get(key); +// +// if (aggObj == null) { +// var newObj = Object.extend({}, key); +// aggObj = Object.extend(newObj, initial); +// map.put(key, aggObj); +// } +// +// reduce_function(obj, aggObj); +// } +// +// return { "result": map.values() }; +// }.toString(); +const groupFunction = + 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; + +/** + * Create an index on the db and collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function createIndex(coll, fieldOrSpec, options, callback) { + createIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); +} + +/** + * Create multiple indexes in the collection. This method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * + * @method + * @param {Collection} a Collection instance. + * @param {array} indexSpecs An array of index specifications to be created + * @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function createIndexes(coll, indexSpecs, options, callback) { + const capabilities = coll.s.topology.capabilities(); + + // Ensure we generate the correct name if the parameter is not set + for (let i = 0; i < indexSpecs.length; i++) { + if (indexSpecs[i].name == null) { + const keys = []; + + // Did the user pass in a collation, check if our write server supports it + if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError('server/primary/mongos does not support collation')); + } + + for (let name in indexSpecs[i].key) { + keys.push(`${name}_${indexSpecs[i].key[name]}`); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + // Execute the index + executeCommand( + coll.s.db, + { + createIndexes: coll.collectionName, + indexes: indexSpecs + }, + options, + callback + ); +} + +/** + * Ensure that an index exists. If the index does not exist, this function creates it. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function ensureIndex(coll, fieldOrSpec, options, callback) { + ensureIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); +} + +/** + * Run a group command across a collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options] Optional settings. See Collection.prototype.group for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. + */ +function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { + // Execute using the command + if (command) { + const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); + + const selector = { + group: { + ns: coll.collectionName, + $reduce: reduceFunction, + cond: condition, + initial: initial, + out: 'inline' + } + }; + + // if finalize is defined + if (finalize != null) selector.group['finalize'] = finalize; + // Set up group selector + if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { + selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); + } else { + const hash = {}; + keys.forEach(key => { + hash[key] = 1; + }); + selector.group.key = hash; + } + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = ReadPreference.resolve(coll, options); + + // Do we have a readConcern specified + decorateWithReadConcern(selector, coll, options); + + // Have we specified collation + try { + decorateWithCollation(selector, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute command + executeCommand(coll.s.db, selector, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.retval); + }); + } else { + // Create execution scope + const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; + + scope.ns = coll.collectionName; + scope.keys = keys; + scope.condition = condition; + scope.initial = initial; + + // Pass in the function text to execute within mongodb. + const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); + + evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, results.result || results); + }); + } +} + +/** + * Retrieve all the indexes on the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexes(coll, options, callback) { + options = Object.assign({}, { full: true }, options); + indexInformationDb(coll.s.db, coll.collectionName, options, callback); +} + +/** + * Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|array)} indexes One or more index names to check. + * @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexExists(coll, indexes, options, callback) { + indexInformation(coll, options, (err, indexInformation) => { + // If we have an error return + if (err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if (!Array.isArray(indexes)) + return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); +} + +/** + * Retrieve this collection's index info. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexInformation(coll, options, callback) { + indexInformationDb(coll.s.db, coll.collectionName, options, callback); +} + +/** + * Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are + * no ordering guarantees for returned results. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + */ +function parallelCollectionScan(coll, options, callback) { + // Create command object + const commandObject = { + parallelCollectionScan: coll.collectionName, + numCursors: options.numCursors + }; + + // Do we have a readConcern specified + decorateWithReadConcern(commandObject, coll, options); + + // Store the raw value + const raw = options.raw; + delete options['raw']; + + // Execute the command + executeCommand(coll.s.db, commandObject, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result == null) + return handleCallback( + callback, + new Error('no result returned for parallelCollectionScan'), + null + ); + + options = Object.assign({ explicitlyIgnoreSession: true }, options); + + const cursors = []; + // Add the raw back to the option + if (raw) options.raw = raw; + // Create command cursors for each item + for (let i = 0; i < result.cursors.length; i++) { + const rawId = result.cursors[i].cursor.id; + // Convert cursorId to Long if needed + const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; + // Add a command cursor + cursors.push(coll.s.topology.cursor(coll.namespace, cursorId, options)); + } + + handleCallback(callback, null, cursors); + }); +} + +/** + * Save a document. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} doc Document to save + * @param {object} [options] Optional settings. See Collection.prototype.save for a list of options. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +function save(coll, doc, options, callback) { + // Get the write concern options + const finalOptions = applyWriteConcern( + Object.assign({}, options), + { db: coll.s.db, collection: coll }, + options + ); + // Establish if we need to perform an insert or update + if (doc._id != null) { + finalOptions.upsert = true; + return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); + } + + // Insert the document + insertDocuments(coll, [doc], finalOptions, (err, result) => { + if (callback == null) return; + if (doc == null) return handleCallback(callback, null, null); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +module.exports = { + createIndex, + createIndexes, + ensureIndex, + group, + indexes, + indexExists, + indexInformation, + parallelCollectionScan, + save +}; + + +/***/ }), + +/***/ 286: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const handleCallback = __webpack_require__(1371).handleCallback; + +let collection; +function loadCollection() { + if (!collection) { + collection = __webpack_require__(5193); + } + return collection; +} + +class CollectionsOperation extends OperationBase { + constructor(db, options) { + super(options); + + this.db = db; + } + + execute(callback) { + const db = this.db; + let options = this.options; + + let Collection = loadCollection(); + + options = Object.assign({}, options, { nameOnly: true }); + // Let's get the collection names + db.listCollections({}, options).toArray((err, documents) => { + if (err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(doc => { + return doc.name.indexOf('$') === -1; + }); + + // Return the collection objects + handleCallback( + callback, + null, + documents.map(d => { + return new Collection( + db, + db.s.topology, + db.databaseName, + d.name, + db.s.pkFactory, + db.s.options + ); + }) + ); + }); + } +} + +module.exports = CollectionsOperation; + + +/***/ }), + +/***/ 499: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const OperationBase = __webpack_require__(1018).OperationBase; +const applyWriteConcern = __webpack_require__(1371).applyWriteConcern; +const debugOptions = __webpack_require__(1371).debugOptions; +const handleCallback = __webpack_require__(1371).handleCallback; +const MongoError = __webpack_require__(3994).MongoError; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const MongoDBNamespace = __webpack_require__(1371).MongoDBNamespace; + +const debugFields = [ + 'authSource', + 'w', + 'wtimeout', + 'j', + 'native_parser', + 'forceServerObjectId', + 'serializeFunctions', + 'raw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bufferMaxEntries', + 'numberOfRetries', + 'retryMiliSeconds', + 'readPreference', + 'pkFactory', + 'parentDb', + 'promiseLibrary', + 'noListener' +]; + +class CommandOperation extends OperationBase { + constructor(db, options, collection, command) { + super(options); + + if (!this.hasAspect(Aspect.WRITE_OPERATION)) { + if (collection != null) { + this.options.readPreference = ReadPreference.resolve(collection, options); + } else { + this.options.readPreference = ReadPreference.resolve(db, options); + } + } else { + if (collection != null) { + applyWriteConcern(this.options, { db, coll: collection }, this.options); + } else { + applyWriteConcern(this.options, { db }, this.options); + } + this.options.readPreference = ReadPreference.primary; + } + + this.db = db; + + if (command != null) { + this.command = command; + } + + if (collection != null) { + this.collection = collection; + } + } + + _buildCommand() { + if (this.command != null) { + return this.command; + } + } + + execute(callback) { + const db = this.db; + const options = Object.assign({}, this.options); + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + let command; + try { + command = this._buildCommand(); + } catch (e) { + return callback(e); + } + + // Get the db name we are executing against + const dbName = options.dbName || options.authdb || db.databaseName; + + // Convert the readPreference if its not a write + if (this.hasAspect(Aspect.WRITE_OPERATION)) { + if (options.writeConcern && (!options.session || !options.session.inTransaction())) { + command.writeConcern = options.writeConcern; + } + } + + // Debug information + if (db.s.logger.isDebug()) { + db.s.logger.debug( + `executing command ${JSON.stringify( + command + )} against ${dbName}.$cmd with options [${JSON.stringify( + debugOptions(debugFields, options) + )}]` + ); + } + + const namespace = + this.namespace != null ? this.namespace : new MongoDBNamespace(dbName, '$cmd'); + + // Execute command + db.s.topology.command(namespace, command, options, (err, result) => { + if (err) return handleCallback(callback, err); + if (options.full) return handleCallback(callback, null, result); + handleCallback(callback, null, result.result); + }); + } +} + +module.exports = CommandOperation; + + +/***/ }), + +/***/ 1189: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const OperationBase = __webpack_require__(1018).OperationBase; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const ReadConcern = __webpack_require__(7289); +const WriteConcern = __webpack_require__(2481); +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const commandSupportsReadConcern = __webpack_require__(5474).commandSupportsReadConcern; +const MongoError = __webpack_require__(3111).MongoError; + +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; + +class CommandOperationV2 extends OperationBase { + constructor(parent, options, operationOptions) { + super(options); + + this.ns = parent.s.namespace.withCollection('$cmd'); + const propertyProvider = this.hasAspect(Aspect.NO_INHERIT_OPTIONS) ? undefined : parent; + this.readPreference = ReadPreference.resolve(propertyProvider, this.options); + this.readConcern = resolveReadConcern(propertyProvider, this.options); + this.writeConcern = resolveWriteConcern(propertyProvider, this.options); + this.explain = false; + + if (operationOptions && typeof operationOptions.fullResponse === 'boolean') { + this.fullResponse = true; + } + + // TODO [$5f5fbe42fcabad09c1c241b5]: A lot of our code depends on having the read preference in the options. This should + // go away, but also requires massive test rewrites. + this.options.readPreference = this.readPreference; + + // TODO(NODE-2056): make logger another "inheritable" property + if (parent.s.logger) { + this.logger = parent.s.logger; + } else if (parent.s.db && parent.s.db.logger) { + this.logger = parent.s.db.logger; + } + } + + executeCommand(server, cmd, callback) { + // TODO [$5f5fbe42fcabad09c1c241b6]: consider making this a non-enumerable property + this.server = server; + + const options = this.options; + const serverWireVersion = maxWireVersion(server); + const inTransaction = this.session && this.session.inTransaction(); + + if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) { + Object.assign(cmd, { readConcern: this.readConcern }); + } + + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback( + new MongoError( + `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation` + ) + ); + return; + } + + if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION)) { + Object.assign(cmd, { writeConcern: this.writeConcern }); + } + + if (options.collation && typeof options.collation === 'object') { + Object.assign(cmd, { collation: options.collation }); + } + } + + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + if (typeof options.comment === 'string') { + cmd.comment = options.comment; + } + + if (this.logger && this.logger.isDebug()) { + this.logger.debug(`executing command ${JSON.stringify(cmd)} against ${this.ns}`); + } + + server.command(this.ns.toString(), cmd, this.options, (err, result) => { + if (err) { + callback(err, null); + return; + } + + if (this.fullResponse) { + callback(null, result); + return; + } + + callback(null, result.result); + }); + } +} + +function resolveWriteConcern(parent, options) { + return WriteConcern.fromOptions(options) || (parent && parent.writeConcern); +} + +function resolveReadConcern(parent, options) { + return ReadConcern.fromOptions(options) || (parent && parent.readConcern); +} + +module.exports = CommandOperationV2; + + +/***/ }), + +/***/ 2296: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const applyRetryableWrites = __webpack_require__(1371).applyRetryableWrites; +const applyWriteConcern = __webpack_require__(1371).applyWriteConcern; +const decorateWithCollation = __webpack_require__(1371).decorateWithCollation; +const decorateWithReadConcern = __webpack_require__(1371).decorateWithReadConcern; +const executeCommand = __webpack_require__(2226).executeCommand; +const formattedOrderClause = __webpack_require__(1371).formattedOrderClause; +const handleCallback = __webpack_require__(1371).handleCallback; +const MongoError = __webpack_require__(3994).MongoError; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const toError = __webpack_require__(1371).toError; +const CursorState = __webpack_require__(4847).CursorState; + +/** + * Build the count command. + * + * @method + * @param {collectionOrCursor} an instance of a collection or cursor + * @param {object} query The query for the count. + * @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options. + */ +function buildCountCommand(collectionOrCursor, query, options) { + const skip = options.skip; + const limit = options.limit; + let hint = options.hint; + const maxTimeMS = options.maxTimeMS; + query = query || {}; + + // Final query + const cmd = { + count: options.collectionName, + query: query + }; + + if (collectionOrCursor.s.numberOfRetries) { + // collectionOrCursor is a cursor + if (collectionOrCursor.options.hint) { + hint = collectionOrCursor.options.hint; + } else if (collectionOrCursor.cmd.hint) { + hint = collectionOrCursor.cmd.hint; + } + decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.cmd); + } else { + decorateWithCollation(cmd, collectionOrCursor, options); + } + + // Add limit, skip and maxTimeMS if defined + if (typeof skip === 'number') cmd.skip = skip; + if (typeof limit === 'number') cmd.limit = limit; + if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; + if (hint) cmd.hint = hint; + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, collectionOrCursor); + + return cmd; +} + +function deleteCallback(err, r, callback) { + if (callback == null) return; + if (err && callback) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.deletedCount = r.result.n; + if (callback) callback(null, r); +} + +/** + * Find and update a document. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options. + * @param {Collection~findAndModifyCallback} [callback] The command result callback + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +function findAndModify(coll, query, sort, doc, options, callback) { + // Create findAndModify command object + const queryObject = { + findAndModify: coll.collectionName, + query: query + }; + + sort = formattedOrderClause(sort); + if (sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + const projection = options.projection || options.fields; + + if (projection) { + queryObject.fields = projection; + } + + if (options.arrayFilters) { + queryObject.arrayFilters = options.arrayFilters; + delete options.arrayFilters; + } + + if (doc && !options.remove) { + queryObject.update = doc; + } + + if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; + + // Either use override on the function, or go back to default on either the collection + // level or db + options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // No check on the documents + options.checkKeys = false; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // Decorate the findAndModify command with the write Concern + if (finalOptions.writeConcern) { + queryObject.writeConcern = finalOptions.writeConcern; + } + + // Have we specified bypassDocumentValidation + if (finalOptions.bypassDocumentValidation === true) { + queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; + } + + finalOptions.readPreference = ReadPreference.primary; + + // Have we specified collation + try { + decorateWithCollation(queryObject, coll, finalOptions); + } catch (err) { + return callback(err, null); + } + + // Execute the command + executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { + if (err) return handleCallback(callback, err, null); + + return handleCallback(callback, null, result); + }); +} + +/** + * Retrieves this collections index info. + * + * @method + * @param {Db} db The Db instance on which to retrieve the index info. + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function indexInformation(db, name, options, callback) { + // If we specified full information + const full = options['full'] == null ? false : options['full']; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Process all the results from the index command and collection + function processResults(indexes) { + // Contains all the information + let info = {}; + // Process all the indexes + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for (let name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + db.collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) return callback(toError(err)); + if (!Array.isArray(indexes)) return handleCallback(callback, null, []); + if (full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +function prepareDocs(coll, docs, options) { + const forceServerObjectId = + typeof options.forceServerObjectId === 'boolean' + ? options.forceServerObjectId + : coll.s.db.options.forceServerObjectId; + + // no need to modify the docs if server sets the ObjectId + if (forceServerObjectId === true) { + return docs; + } + + return docs.map(doc => { + if (forceServerObjectId !== true && doc._id == null) { + doc._id = coll.s.pkFactory.createPk(); + } + + return doc; + }); +} + +// Get the next available document from the cursor, returns null if no more documents are available. +function nextObject(cursor, callback) { + if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) { + return handleCallback( + callback, + MongoError.create({ message: 'Cursor is closed', driver: true }) + ); + } + + if (cursor.s.state === CursorState.INIT && cursor.cmd && cursor.cmd.sort) { + try { + cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); + } catch (err) { + return handleCallback(callback, err); + } + } + + // Get the next object + cursor._next((err, doc) => { + cursor.s.state = CursorState.OPEN; + if (err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +function insertDocuments(coll, docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Ensure we are operating on an array op docs + docs = Array.isArray(docs) ? docs : [docs]; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // If keep going set unordered + if (finalOptions.keepGoing === true) finalOptions.ordered = false; + finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + docs = prepareDocs(coll, docs, options); + + // File inserts + coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) + return handleCallback(callback, toError(result.result.writeErrors[0])); + // Add docs to the list + result.ops = docs; + // Return the results + handleCallback(callback, null, result); + }); +} + +function removeDocuments(coll, selector, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}); + } else if (typeof selector === 'function') { + callback = selector; + options = {}; + selector = {}; + } + + // Create an empty options object if the provided one is null + options = options || {}; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // If selector is null set empty + if (selector == null) selector = {}; + + // Build the op + const op = { q: selector, limit: 0 }; + if (options.single) { + op.limit = 1; + } else if (finalOptions.retryWrites) { + finalOptions.retryWrites = false; + } + if (options.hint) { + op.hint = options.hint; + } + + // Have we specified collation + try { + decorateWithCollation(finalOptions, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute the remove + coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) { + return handleCallback(callback, toError(result.result.writeErrors[0])); + } + + // Return the results + handleCallback(callback, null, result); + }); +} + +function updateDocuments(coll, selector, document, options, callback) { + if ('function' === typeof options) (callback = options), (options = null); + if (options == null) options = {}; + if (!('function' === typeof callback)) callback = null; + + // If we are not providing a selector or document throw + if (selector == null || typeof selector !== 'object') + return callback(toError('selector must be a valid JavaScript object')); + if (document == null || typeof document !== 'object') + return callback(toError('document must be a valid JavaScript object')); + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // Do we return the actual result document + // Either use override on the function, or go back to default on either the collection + // level or db + finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // Execute the operation + const op = { q: selector, u: document }; + op.upsert = options.upsert !== void 0 ? !!options.upsert : false; + op.multi = options.multi !== void 0 ? !!options.multi : false; + + if (options.hint) { + op.hint = options.hint; + } + + if (finalOptions.arrayFilters) { + op.arrayFilters = finalOptions.arrayFilters; + delete finalOptions.arrayFilters; + } + + if (finalOptions.retryWrites && op.multi) { + finalOptions.retryWrites = false; + } + + // Have we specified collation + try { + decorateWithCollation(finalOptions, coll, options); + } catch (err) { + return callback(err, null); + } + + // Update options + coll.s.topology.update(coll.s.namespace, [op], finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) + return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +function updateCallback(err, r, callback) { + if (callback == null) return; + if (err) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + callback(null, r); +} + +module.exports = { + buildCountCommand, + deleteCallback, + findAndModify, + indexInformation, + nextObject, + prepareDocs, + insertDocuments, + removeDocuments, + updateDocuments, + updateCallback +}; + + +/***/ }), + +/***/ 5210: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const deprecate = __webpack_require__(1669).deprecate; +const Logger = __webpack_require__(3994).Logger; +const MongoCredentials = __webpack_require__(3994).MongoCredentials; +const MongoError = __webpack_require__(3994).MongoError; +const Mongos = __webpack_require__(2048); +const NativeTopology = __webpack_require__(2632); +const parse = __webpack_require__(3994).parseConnectionString; +const ReadConcern = __webpack_require__(7289); +const ReadPreference = __webpack_require__(3994).ReadPreference; +const ReplSet = __webpack_require__(382); +const Server = __webpack_require__(8421); +const ServerSessionPool = __webpack_require__(3994).Sessions.ServerSessionPool; +const emitDeprecationWarning = __webpack_require__(1371).emitDeprecationWarning; +const fs = __webpack_require__(5747); +const BSON = __webpack_require__(7746).retrieveBSON(); +const CMAP_EVENT_NAMES = __webpack_require__(897).CMAP_EVENT_NAMES; + +let client; +function loadClient() { + if (!client) { + client = __webpack_require__(1545); + } + return client; +} + +const legacyParse = deprecate( + __webpack_require__(8729), + 'current URL string parser is deprecated, and will be removed in a future version. ' + + 'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.' +); + +const AUTH_MECHANISM_INTERNAL_MAP = { + DEFAULT: 'default', + PLAIN: 'plain', + GSSAPI: 'gssapi', + 'MONGODB-CR': 'mongocr', + 'MONGODB-X509': 'x509', + 'MONGODB-AWS': 'mongodb-aws', + 'SCRAM-SHA-1': 'scram-sha-1', + 'SCRAM-SHA-256': 'scram-sha-256' +}; + +const monitoringEvents = [ + 'timeout', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha', + 'all', + 'fullsetup', + 'open' +]; + +const VALID_AUTH_MECHANISMS = new Set([ + 'DEFAULT', + 'PLAIN', + 'GSSAPI', + 'MONGODB-CR', + 'MONGODB-X509', + 'MONGODB-AWS', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256' +]); + +const validOptionNames = [ + 'poolSize', + 'ssl', + 'sslValidate', + 'sslCA', + 'sslCert', + 'sslKey', + 'sslPass', + 'sslCRL', + 'autoReconnect', + 'noDelay', + 'keepAlive', + 'keepAliveInitialDelay', + 'connectTimeoutMS', + 'family', + 'socketTimeoutMS', + 'reconnectTries', + 'reconnectInterval', + 'ha', + 'haInterval', + 'replicaSet', + 'secondaryAcceptableLatencyMS', + 'acceptableLatencyMS', + 'connectWithNoPrimary', + 'authSource', + 'w', + 'wtimeout', + 'j', + 'forceServerObjectId', + 'serializeFunctions', + 'ignoreUndefined', + 'raw', + 'bufferMaxEntries', + 'readPreference', + 'pkFactory', + 'promiseLibrary', + 'readConcern', + 'maxStalenessSeconds', + 'loggerLevel', + 'logger', + 'promoteValues', + 'promoteBuffers', + 'promoteLongs', + 'domainsEnabled', + 'checkServerIdentity', + 'validateOptions', + 'appname', + 'auth', + 'user', + 'password', + 'authMechanism', + 'compression', + 'fsync', + 'readPreferenceTags', + 'numberOfRetries', + 'auto_reconnect', + 'minSize', + 'monitorCommands', + 'retryWrites', + 'retryReads', + 'useNewUrlParser', + 'useUnifiedTopology', + 'serverSelectionTimeoutMS', + 'useRecoveryToken', + 'autoEncryption', + 'driverInfo', + 'tls', + 'tlsInsecure', + 'tlsinsecure', + 'tlsAllowInvalidCertificates', + 'tlsAllowInvalidHostnames', + 'tlsCAFile', + 'tlsCertificateFile', + 'tlsCertificateKeyFile', + 'tlsCertificateKeyFilePassword', + 'minHeartbeatFrequencyMS', + 'heartbeatFrequencyMS', + 'directConnection', + 'appName', + + // CMAP options + 'maxPoolSize', + 'minPoolSize', + 'maxIdleTimeMS', + 'waitQueueTimeoutMS' +]; + +const ignoreOptionNames = ['native_parser']; +const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; + +// Validate options object +function validOptions(options) { + const _validOptions = validOptionNames.concat(legacyOptionNames); + + for (const name in options) { + if (ignoreOptionNames.indexOf(name) !== -1) { + continue; + } + + if (_validOptions.indexOf(name) === -1) { + if (options.validateOptions) { + return new MongoError(`option ${name} is not supported`); + } else { + console.warn(`the options [${name}] is not supported`); + } + } + + if (legacyOptionNames.indexOf(name) !== -1) { + console.warn( + `the server/replset/mongos/db options are deprecated, ` + + `all their options are supported at the top level of the options object [${validOptionNames}]` + ); + } + } +} + +const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => { + obj[name.toLowerCase()] = name; + return obj; +}, {}); + +function addListeners(mongoClient, topology) { + topology.on('authenticated', createListener(mongoClient, 'authenticated')); + topology.on('error', createListener(mongoClient, 'error')); + topology.on('timeout', createListener(mongoClient, 'timeout')); + topology.on('close', createListener(mongoClient, 'close')); + topology.on('parseError', createListener(mongoClient, 'parseError')); + topology.once('open', createListener(mongoClient, 'open')); + topology.once('fullsetup', createListener(mongoClient, 'fullsetup')); + topology.once('all', createListener(mongoClient, 'all')); + topology.on('reconnect', createListener(mongoClient, 'reconnect')); +} + +function assignTopology(client, topology) { + client.topology = topology; + + if (!(topology instanceof NativeTopology)) { + topology.s.sessionPool = new ServerSessionPool(topology.s.coreTopology); + } +} + +// Clear out all events +function clearAllEvents(topology) { + monitoringEvents.forEach(event => topology.removeAllListeners(event)); +} + +// Collect all events in order from SDAM +function collectEvents(mongoClient, topology) { + let MongoClient = loadClient(); + const collectedEvents = []; + + if (mongoClient instanceof MongoClient) { + monitoringEvents.forEach(event => { + topology.on(event, (object1, object2) => { + if (event === 'open') { + collectedEvents.push({ event: event, object1: mongoClient }); + } else { + collectedEvents.push({ event: event, object1: object1, object2: object2 }); + } + }); + }); + } + + return collectedEvents; +} + +function resolveTLSOptions(options) { + if (options.tls == null) { + return; + } + + ['sslCA', 'sslKey', 'sslCert'].forEach(optionName => { + if (options[optionName]) { + options[optionName] = fs.readFileSync(options[optionName]); + } + }); +} + +const emitDeprecationForNonUnifiedTopology = deprecate(() => {}, +'current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. ' + 'To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.'); + +function connect(mongoClient, url, options, callback) { + options = Object.assign({}, options); + + // If callback is null throw an exception + if (callback == null) { + throw new Error('no callback function provided'); + } + + let didRequestAuthentication = false; + const logger = Logger('MongoClient', options); + + // Did we pass in a Server/ReplSet/Mongos + if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) { + return connectWithUrl(mongoClient, url, options, connectCallback); + } + + const useNewUrlParser = options.useNewUrlParser !== false; + + const parseFn = useNewUrlParser ? parse : legacyParse; + const transform = useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions; + + parseFn(url, options, (err, _object) => { + // Do not attempt to connect if parsing error + if (err) return callback(err); + + // Flatten + const object = transform(_object); + + // Parse the string + const _finalOptions = createUnifiedOptions(object, options); + + // Check if we have connection and socket timeout set + if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000; + if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 10000; + if (_finalOptions.retryWrites == null) _finalOptions.retryWrites = true; + if (_finalOptions.useRecoveryToken == null) _finalOptions.useRecoveryToken = true; + if (_finalOptions.readPreference == null) _finalOptions.readPreference = 'primary'; + + if (_finalOptions.db_options && _finalOptions.db_options.auth) { + delete _finalOptions.db_options.auth; + } + + // `journal` should be translated to `j` for the driver + if (_finalOptions.journal != null) { + _finalOptions.j = _finalOptions.journal; + _finalOptions.journal = undefined; + } + + // resolve tls options if needed + resolveTLSOptions(_finalOptions); + + // Store the merged options object + mongoClient.s.options = _finalOptions; + + // Failure modes + if (object.servers.length === 0) { + return callback(new Error('connection string must contain at least one seed host')); + } + + if (_finalOptions.auth && !_finalOptions.credentials) { + try { + didRequestAuthentication = true; + _finalOptions.credentials = generateCredentials( + mongoClient, + _finalOptions.auth.user, + _finalOptions.auth.password, + _finalOptions + ); + } catch (err) { + return callback(err); + } + } + + if (_finalOptions.useUnifiedTopology) { + return createTopology(mongoClient, 'unified', _finalOptions, connectCallback); + } + + emitDeprecationForNonUnifiedTopology(); + + // Do we have a replicaset then skip discovery and go straight to connectivity + if (_finalOptions.replicaSet || _finalOptions.rs_name) { + return createTopology(mongoClient, 'replicaset', _finalOptions, connectCallback); + } else if (object.servers.length > 1) { + return createTopology(mongoClient, 'mongos', _finalOptions, connectCallback); + } else { + return createServer(mongoClient, _finalOptions, connectCallback); + } + }); + + function connectCallback(err, topology) { + const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`; + if (err && err.message === 'no mongos proxies found in seed list') { + if (logger.isWarn()) { + logger.warn(warningMessage); + } + + // Return a more specific error message for MongoClient.connect + return callback(new MongoError(warningMessage)); + } + + if (didRequestAuthentication) { + mongoClient.emit('authenticated', null, true); + } + + // Return the error and db instance + callback(err, topology); + } +} + +function connectWithUrl(mongoClient, url, options, connectCallback) { + // Set the topology + assignTopology(mongoClient, url); + + // Add listeners + addListeners(mongoClient, url); + + // Propagate the events to the client + relayEvents(mongoClient, url); + + let finalOptions = Object.assign({}, options); + + // If we have a readPreference passed in by the db options, convert it from a string + if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { + finalOptions.readPreference = new ReadPreference( + options.readPreference || options.read_preference + ); + } + + const isDoingAuth = finalOptions.user || finalOptions.password || finalOptions.authMechanism; + if (isDoingAuth && !finalOptions.credentials) { + try { + finalOptions.credentials = generateCredentials( + mongoClient, + finalOptions.user, + finalOptions.password, + finalOptions + ); + } catch (err) { + return connectCallback(err, url); + } + } + + return url.connect(finalOptions, connectCallback); +} + +function createListener(mongoClient, event) { + const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']); + return (v1, v2) => { + if (eventSet.has(event)) { + return mongoClient.emit(event, mongoClient); + } + + mongoClient.emit(event, v1, v2); + }; +} + +function createServer(mongoClient, options, callback) { + // Pass in the promise library + options.promiseLibrary = mongoClient.s.promiseLibrary; + + // Set default options + const servers = translateOptions(options); + + const server = servers[0]; + + // Propagate the events to the client + const collectedEvents = collectEvents(mongoClient, server); + + // Connect to topology + server.connect(options, (err, topology) => { + if (err) { + server.close(true); + return callback(err); + } + // Clear out all the collected event listeners + clearAllEvents(server); + + // Relay all the events + relayEvents(mongoClient, server); + // Add listeners + addListeners(mongoClient, server); + // Check if we are really speaking to a mongos + const ismaster = topology.lastIsMaster(); + + // Set the topology + assignTopology(mongoClient, topology); + + // Do we actually have a mongos + if (ismaster && ismaster.msg === 'isdbgrid') { + // Destroy the current connection + topology.close(); + // Create mongos connection instead + return createTopology(mongoClient, 'mongos', options, callback); + } + + // Fire all the events + replayEvents(mongoClient, collectedEvents); + // Otherwise callback + callback(err, topology); + }); +} + +const DEPRECATED_UNIFIED_EVENTS = new Set([ + 'reconnect', + 'reconnectFailed', + 'attemptReconnect', + 'joined', + 'left', + 'ping', + 'ha', + 'all', + 'fullsetup', + 'open' +]); + +function registerDeprecatedEventNotifiers(client) { + client.on('newListener', eventName => { + if (DEPRECATED_UNIFIED_EVENTS.has(eventName)) { + emitDeprecationWarning( + `The \`${eventName}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`, + 'DeprecationWarning' + ); + } + }); +} + +function createTopology(mongoClient, topologyType, options, callback) { + // Pass in the promise library + options.promiseLibrary = mongoClient.s.promiseLibrary; + + const translationOptions = {}; + if (topologyType === 'unified') translationOptions.createServers = false; + + // Set default options + const servers = translateOptions(options, translationOptions); + + // determine CSFLE support + if (options.autoEncryption != null) { + let AutoEncrypter; + try { + require.resolve('mongodb-client-encryption'); + } catch (err) { + callback( + new MongoError( + 'Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project' + ) + ); + return; + } + + try { + let mongodbClientEncryption = __webpack_require__(5764); + if (typeof mongodbClientEncryption.extension !== 'function') { + callback( + new MongoError( + 'loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`' + ) + ); + } + AutoEncrypter = mongodbClientEncryption.extension(__webpack_require__(5517)).AutoEncrypter; + } catch (err) { + callback(err); + return; + } + + const mongoCryptOptions = Object.assign( + { + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]) + }, + options.autoEncryption + ); + + options.autoEncrypter = new AutoEncrypter(mongoClient, mongoCryptOptions); + } + + // Create the topology + let topology; + if (topologyType === 'mongos') { + topology = new Mongos(servers, options); + } else if (topologyType === 'replicaset') { + topology = new ReplSet(servers, options); + } else if (topologyType === 'unified') { + topology = new NativeTopology(options.servers, options); + registerDeprecatedEventNotifiers(mongoClient); + } + + // Add listeners + addListeners(mongoClient, topology); + + // Propagate the events to the client + relayEvents(mongoClient, topology); + + // Open the connection + assignTopology(mongoClient, topology); + + // initialize CSFLE if requested + if (options.autoEncrypter) { + options.autoEncrypter.init(err => { + if (err) { + callback(err); + return; + } + + topology.connect(options, err => { + if (err) { + topology.close(true); + callback(err); + return; + } + + callback(undefined, topology); + }); + }); + + return; + } + + // otherwise connect normally + topology.connect(options, err => { + if (err) { + topology.close(true); + return callback(err); + } + + callback(undefined, topology); + return; + }); +} + +function createUnifiedOptions(finalOptions, options) { + const childOptions = [ + 'mongos', + 'server', + 'db', + 'replset', + 'db_options', + 'server_options', + 'rs_options', + 'mongos_options' + ]; + const noMerge = ['readconcern', 'compression', 'autoencryption']; + + for (const name in options) { + if (noMerge.indexOf(name.toLowerCase()) !== -1) { + finalOptions[name] = options[name]; + } else if (childOptions.indexOf(name.toLowerCase()) !== -1) { + finalOptions = mergeOptions(finalOptions, options[name], false); + } else { + if ( + options[name] && + typeof options[name] === 'object' && + !Buffer.isBuffer(options[name]) && + !Array.isArray(options[name]) + ) { + finalOptions = mergeOptions(finalOptions, options[name], true); + } else { + finalOptions[name] = options[name]; + } + } + } + + return finalOptions; +} + +function generateCredentials(client, username, password, options) { + options = Object.assign({}, options); + + // the default db to authenticate against is 'self' + // if authententicate is called from a retry context, it may be another one, like admin + const source = options.authSource || options.authdb || options.dbName; + + // authMechanism + const authMechanismRaw = options.authMechanism || 'DEFAULT'; + const authMechanism = authMechanismRaw.toUpperCase(); + const mechanismProperties = options.authMechanismProperties; + + if (!VALID_AUTH_MECHANISMS.has(authMechanism)) { + throw MongoError.create({ + message: `authentication mechanism ${authMechanismRaw} not supported', options.authMechanism`, + driver: true + }); + } + + return new MongoCredentials({ + mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism], + mechanismProperties, + source, + username, + password + }); +} + +function legacyTransformUrlOptions(object) { + return mergeOptions(createUnifiedOptions({}, object), object, false); +} + +function mergeOptions(target, source, flatten) { + for (const name in source) { + if (source[name] && typeof source[name] === 'object' && flatten) { + target = mergeOptions(target, source[name], flatten); + } else { + target[name] = source[name]; + } + } + + return target; +} + +function relayEvents(mongoClient, topology) { + const serverOrCommandEvents = [ + // APM + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + + // SDAM + 'serverOpening', + 'serverClosed', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + + // Legacy + 'joined', + 'left', + 'ping', + 'ha' + ].concat(CMAP_EVENT_NAMES); + + serverOrCommandEvents.forEach(event => { + topology.on(event, (object1, object2) => { + mongoClient.emit(event, object1, object2); + }); + }); +} + +// +// Replay any events due to single server connection switching to Mongos +// +function replayEvents(mongoClient, events) { + for (let i = 0; i < events.length; i++) { + mongoClient.emit(events[i].event, events[i].object1, events[i].object2); + } +} + +function transformUrlOptions(_object) { + let object = Object.assign({ servers: _object.hosts }, _object.options); + for (let name in object) { + const camelCaseName = LEGACY_OPTIONS_MAP[name]; + if (camelCaseName) { + object[camelCaseName] = object[name]; + } + } + + const hasUsername = _object.auth && _object.auth.username; + const hasAuthMechanism = _object.options && _object.options.authMechanism; + if (hasUsername || hasAuthMechanism) { + object.auth = Object.assign({}, _object.auth); + if (object.auth.db) { + object.authSource = object.authSource || object.auth.db; + } + + if (object.auth.username) { + object.auth.user = object.auth.username; + } + } + + if (_object.defaultDatabase) { + object.dbName = _object.defaultDatabase; + } + + if (object.maxPoolSize) { + object.poolSize = object.maxPoolSize; + } + + if (object.readConcernLevel) { + object.readConcern = new ReadConcern(object.readConcernLevel); + } + + if (object.wTimeoutMS) { + object.wtimeout = object.wTimeoutMS; + } + + if (_object.srvHost) { + object.srvHost = _object.srvHost; + } + + return object; +} + +function translateOptions(options, translationOptions) { + translationOptions = Object.assign({}, { createServers: true }, translationOptions); + + // If we have a readPreference passed in by the db options + if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { + options.readPreference = new ReadPreference(options.readPreference || options.read_preference); + } + + // Do we have readPreference tags, add them + if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { + options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; + } + + // Do we have maxStalenessSeconds + if (options.maxStalenessSeconds) { + options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; + } + + // Set the socket and connection timeouts + if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000; + if (options.connectTimeoutMS == null) options.connectTimeoutMS = 10000; + + if (!translationOptions.createServers) { + return; + } + + // Create server instances + return options.servers.map(serverObj => { + return serverObj.domain_socket + ? new Server(serverObj.domain_socket, 27017, options) + : new Server(serverObj.host, serverObj.port, options); + }); +} + +module.exports = { validOptions, connect }; + + +/***/ }), + +/***/ 7885: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const buildCountCommand = __webpack_require__(2296).buildCountCommand; +const OperationBase = __webpack_require__(1018).OperationBase; + +class CountOperation extends OperationBase { + constructor(cursor, applySkipLimit, options) { + super(options); + + this.cursor = cursor; + this.applySkipLimit = applySkipLimit; + } + + execute(callback) { + const cursor = this.cursor; + const applySkipLimit = this.applySkipLimit; + const options = this.options; + + if (applySkipLimit) { + if (typeof cursor.cursorSkip() === 'number') options.skip = cursor.cursorSkip(); + if (typeof cursor.cursorLimit() === 'number') options.limit = cursor.cursorLimit(); + } + + // Ensure we have the right read preference inheritance + if (options.readPreference) { + cursor.setReadPreference(options.readPreference); + } + + if ( + typeof options.maxTimeMS !== 'number' && + cursor.cmd && + typeof cursor.cmd.maxTimeMS === 'number' + ) { + options.maxTimeMS = cursor.cmd.maxTimeMS; + } + + let finalOptions = {}; + finalOptions.skip = options.skip; + finalOptions.limit = options.limit; + finalOptions.hint = options.hint; + finalOptions.maxTimeMS = options.maxTimeMS; + + // Command + finalOptions.collectionName = cursor.namespace.collection; + + let command; + try { + command = buildCountCommand(cursor, cursor.cmd.query, finalOptions); + } catch (err) { + return callback(err); + } + + // Set cursor server to the same as the topology + cursor.server = cursor.topology.s.coreTopology; + + // Execute the command + cursor.topology.command( + cursor.namespace.withCollection('$cmd'), + command, + cursor.options, + (err, result) => { + callback(err, result ? result.result.n : null); + } + ); + } +} + +module.exports = CountOperation; + + +/***/ }), + +/***/ 5131: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const AggregateOperation = __webpack_require__(1554); + +class CountDocumentsOperation extends AggregateOperation { + constructor(collection, query, options) { + const pipeline = [{ $match: query }]; + if (typeof options.skip === 'number') { + pipeline.push({ $skip: options.skip }); + } + + if (typeof options.limit === 'number') { + pipeline.push({ $limit: options.limit }); + } + + pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); + + super(collection, pipeline, options); + } + + execute(server, callback) { + super.execute(server, (err, result) => { + if (err) { + callback(err, null); + return; + } + + // NOTE: We're avoiding creating a cursor here to reduce the callstack. + const response = result.result; + if (response.cursor == null || response.cursor.firstBatch == null) { + callback(null, 0); + return; + } + + const docs = response.cursor.firstBatch; + callback(null, docs.length ? docs[0].n : 0); + }); + } +} + +module.exports = CountDocumentsOperation; + + +/***/ }), + +/***/ 5561: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; +const CommandOperation = __webpack_require__(499); +const applyWriteConcern = __webpack_require__(1371).applyWriteConcern; +const loadCollection = __webpack_require__(8275).loadCollection; +const MongoError = __webpack_require__(3994).MongoError; +const ReadPreference = __webpack_require__(3994).ReadPreference; + +const ILLEGAL_COMMAND_FIELDS = new Set([ + 'w', + 'wtimeout', + 'j', + 'fsync', + 'autoIndexId', + 'strict', + 'serializeFunctions', + 'pkFactory', + 'raw', + 'readPreference', + 'session', + 'readConcern', + 'writeConcern' +]); + +class CreateCollectionOperation extends CommandOperation { + constructor(db, name, options) { + super(db, options); + this.name = name; + } + + _buildCommand() { + const name = this.name; + const options = this.options; + + const cmd = { create: name }; + for (let n in options) { + if ( + options[n] != null && + typeof options[n] !== 'function' && + !ILLEGAL_COMMAND_FIELDS.has(n) + ) { + cmd[n] = options[n]; + } + } + + return cmd; + } + + execute(callback) { + const db = this.db; + const name = this.name; + const options = this.options; + const Collection = loadCollection(); + + let listCollectionOptions = Object.assign({ nameOnly: true, strict: false }, options); + listCollectionOptions = applyWriteConcern(listCollectionOptions, { db }, listCollectionOptions); + + function done(err) { + if (err) { + return callback(err); + } + + try { + callback( + null, + new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) + ); + } catch (err) { + callback(err); + } + } + + const strictMode = listCollectionOptions.strict; + if (strictMode) { + db.listCollections({ name }, listCollectionOptions) + .setReadPreference(ReadPreference.PRIMARY) + .toArray((err, collections) => { + if (err) { + return callback(err); + } + + if (collections.length > 0) { + return callback( + new MongoError(`Collection ${name} already exists. Currently in strict mode.`) + ); + } + + super.execute(done); + }); + + return; + } + + // otherwise just execute the command + super.execute(done); + } +} + +defineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION); +module.exports = CreateCollectionOperation; + + +/***/ }), + +/***/ 6394: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; +const CommandOperationV2 = __webpack_require__(1189); +const MongoError = __webpack_require__(3994).MongoError; +const parseIndexOptions = __webpack_require__(1371).parseIndexOptions; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; + +const VALID_INDEX_OPTIONS = new Set([ + 'background', + 'unique', + 'name', + 'partialFilterExpression', + 'sparse', + 'expireAfterSeconds', + 'storageEngine', + 'collation', + + // text indexes + 'weights', + 'default_language', + 'language_override', + 'textIndexVersion', + + // 2d-sphere indexes + '2dsphereIndexVersion', + + // 2d indexes + 'bits', + 'min', + 'max', + + // geoHaystack Indexes + 'bucketSize', + + // wildcard indexes + 'wildcardProjection' +]); + +class CreateIndexesOperation extends CommandOperationV2 { + /** + * @ignore + */ + constructor(parent, collection, indexes, options) { + super(parent, options); + this.collection = collection; + + // createIndex can be called with a variety of styles: + // coll.createIndex('a'); + // coll.createIndex({ a: 1 }); + // coll.createIndex([['a', 1]]); + // createIndexes is always called with an array of index spec objects + if (!Array.isArray(indexes) || Array.isArray(indexes[0])) { + this.onlyReturnNameOfCreatedIndex = true; + // TODO [$5f5fbe42fcabad09c1c241b7]: remove in v4 (breaking change); make createIndex return full response as createIndexes does + + const indexParameters = parseIndexOptions(indexes); + // Generate the index name + const name = typeof options.name === 'string' ? options.name : indexParameters.name; + // Set up the index + const indexSpec = { name, key: indexParameters.fieldHash }; + // merge valid index options into the index spec + for (let optionName in options) { + if (VALID_INDEX_OPTIONS.has(optionName)) { + indexSpec[optionName] = options[optionName]; + } + } + this.indexes = [indexSpec]; + return; + } + + this.indexes = indexes; + } + + /** + * @ignore + */ + execute(server, callback) { + const options = this.options; + const indexes = this.indexes; + + const serverWireVersion = maxWireVersion(server); + + // Ensure we generate the correct name if the parameter is not set + for (let i = 0; i < indexes.length; i++) { + // Did the user pass in a collation, check if our write server supports it + if (indexes[i].collation && serverWireVersion < 5) { + callback( + new MongoError( + `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation` + ) + ); + return; + } + + if (indexes[i].name == null) { + const keys = []; + + for (let name in indexes[i].key) { + keys.push(`${name}_${indexes[i].key[name]}`); + } + + // Set the name + indexes[i].name = keys.join('_'); + } + } + + const cmd = { createIndexes: this.collection, indexes }; + + if (options.commitQuorum != null) { + if (serverWireVersion < 9) { + callback( + new MongoError('`commitQuorum` option for `createIndexes` not supported on servers < 4.4') + ); + return; + } + cmd.commitQuorum = options.commitQuorum; + } + + // collation is set on each index, it should not be defined at the root + this.options.collation = undefined; + + super.executeCommand(server, cmd, (err, result) => { + if (err) { + callback(err); + return; + } + + callback(null, this.onlyReturnNameOfCreatedIndex ? indexes[0].name : result); + }); + } +} + +defineAspects(CreateIndexesOperation, [Aspect.WRITE_OPERATION, Aspect.EXECUTE_WITH_SELECTION]); + +module.exports = CreateIndexesOperation; + + +/***/ }), + +/***/ 3554: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const buildCountCommand = __webpack_require__(6716).buildCountCommand; +const handleCallback = __webpack_require__(1371).handleCallback; +const MongoError = __webpack_require__(3994).MongoError; +const push = Array.prototype.push; +const CursorState = __webpack_require__(4847).CursorState; + +/** + * Get the count of documents for this cursor. + * + * @method + * @param {Cursor} cursor The Cursor instance on which to count. + * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options. + * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options. + * @param {Cursor~countResultCallback} [callback] The result callback. + */ +function count(cursor, applySkipLimit, opts, callback) { + if (applySkipLimit) { + if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); + if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); + } + + // Ensure we have the right read preference inheritance + if (opts.readPreference) { + cursor.setReadPreference(opts.readPreference); + } + + if ( + typeof opts.maxTimeMS !== 'number' && + cursor.cmd && + typeof cursor.cmd.maxTimeMS === 'number' + ) { + opts.maxTimeMS = cursor.cmd.maxTimeMS; + } + + let options = {}; + options.skip = opts.skip; + options.limit = opts.limit; + options.hint = opts.hint; + options.maxTimeMS = opts.maxTimeMS; + + // Command + options.collectionName = cursor.namespace.collection; + + let command; + try { + command = buildCountCommand(cursor, cursor.cmd.query, options); + } catch (err) { + return callback(err); + } + + // Set cursor server to the same as the topology + cursor.server = cursor.topology.s.coreTopology; + + // Execute the command + cursor.topology.command( + cursor.namespace.withCollection('$cmd'), + command, + cursor.options, + (err, result) => { + callback(err, result ? result.result.n : null); + } + ); +} + +/** + * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information. + * + * @method + * @deprecated + * @param {Cursor} cursor The Cursor instance on which to run. + * @param {Cursor~resultCallback} callback The result callback. + */ +function each(cursor, callback) { + if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); + if (cursor.isNotified()) return; + if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) { + return handleCallback( + callback, + MongoError.create({ message: 'Cursor is closed', driver: true }) + ); + } + + if (cursor.s.state === CursorState.INIT) { + cursor.s.state = CursorState.OPEN; + } + + // Define function to avoid global scope escape + let fn = null; + // Trampoline all the entries + if (cursor.bufferedCount() > 0) { + while ((fn = loop(cursor, callback))) fn(cursor, callback); + each(cursor, callback); + } else { + cursor.next((err, item) => { + if (err) return handleCallback(callback, err); + if (item == null) { + return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); + } + + if (handleCallback(callback, null, item) === false) return; + each(cursor, callback); + }); + } +} + +// Trampoline emptying the number of retrieved items +// without incurring a nextTick operation +function loop(cursor, callback) { + // No more items we are done + if (cursor.bufferedCount() === 0) return; + // Get the next document + cursor._next(callback); + // Loop + return loop; +} + +/** + * Returns an array of documents. See Cursor.prototype.toArray for more information. + * + * @method + * @param {Cursor} cursor The Cursor instance from which to get the next document. + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + */ +function toArray(cursor, callback) { + const items = []; + + // Reset cursor + cursor.rewind(); + cursor.s.state = CursorState.INIT; + + // Fetch all the documents + const fetchDocs = () => { + cursor._next((err, doc) => { + if (err) { + return handleCallback(callback, err); + } + + if (doc == null) { + return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); + } + + // Add doc to items + items.push(doc); + + // Get all buffered objects + if (cursor.bufferedCount() > 0) { + let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); + + // Transform the doc if transform method added + if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { + docs = docs.map(cursor.s.transforms.doc); + } + + push.apply(items, docs); + } + + // Attempt a fetch + fetchDocs(); + }); + }; + + fetchDocs(); +} + +module.exports = { count, each, toArray }; + + +/***/ }), + +/***/ 2226: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const applyWriteConcern = __webpack_require__(1371).applyWriteConcern; +const Code = __webpack_require__(3994).BSON.Code; +const debugOptions = __webpack_require__(1371).debugOptions; +const handleCallback = __webpack_require__(1371).handleCallback; +const MongoError = __webpack_require__(3994).MongoError; +const parseIndexOptions = __webpack_require__(1371).parseIndexOptions; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const toError = __webpack_require__(1371).toError; +const CONSTANTS = __webpack_require__(147); +const MongoDBNamespace = __webpack_require__(1371).MongoDBNamespace; + +const debugFields = [ + 'authSource', + 'w', + 'wtimeout', + 'j', + 'native_parser', + 'forceServerObjectId', + 'serializeFunctions', + 'raw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bufferMaxEntries', + 'numberOfRetries', + 'retryMiliSeconds', + 'readPreference', + 'pkFactory', + 'parentDb', + 'promiseLibrary', + 'noListener' +]; + +/** + * Creates an index on the db and collection. + * @method + * @param {Db} db The Db instance on which to create an index. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function createIndex(db, name, fieldOrSpec, options, callback) { + // Get the write concern options + let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); + finalOptions = applyWriteConcern(finalOptions, { db }, options); + + // Ensure we have a callback + if (finalOptions.writeConcern && typeof callback !== 'function') { + throw MongoError.create({ + message: 'Cannot use a writeConcern without a provided callback', + driver: true + }); + } + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // Attempt to run using createIndexes command + createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { + if (err == null) return handleCallback(callback, err, result); + + /** + * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: + * 67 = 'CannotCreateIndex' (malformed index options) + * 85 = 'IndexOptionsConflict' (index already exists with different options) + * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) + * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) + * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) + * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) + */ + if ( + err.code === 67 || + err.code === 11000 || + err.code === 85 || + err.code === 86 || + err.code === 11600 || + err.code === 197 + ) { + return handleCallback(callback, err, result); + } + + // Create command + const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); + // Set no key checking + finalOptions.checkKeys = false; + // Insert document + db.s.topology.insert( + db.s.namespace.withCollection(CONSTANTS.SYSTEM_INDEX_COLLECTION), + doc, + finalOptions, + (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err); + if (result == null) return handleCallback(callback, null, null); + if (result.result.writeErrors) + return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); + handleCallback(callback, null, doc.name); + } + ); + }); +} + +// Add listeners to topology +function createListener(db, e, object) { + function listener(err) { + if (object.listeners(e).length > 0) { + object.emit(e, err, db); + + // Emit on all associated db's if available + for (let i = 0; i < db.s.children.length; i++) { + db.s.children[i].emit(e, err, db.s.children[i]); + } + } + } + return listener; +} + +/** + * Ensures that an index exists. If it does not, creates it. + * + * @method + * @param {Db} db The Db instance on which to ensure the index. + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function ensureIndex(db, name, fieldOrSpec, options, callback) { + // Get the write concern options + const finalOptions = applyWriteConcern({}, { db }, options); + // Create command + const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); + const index_name = selector.name; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // Merge primary readPreference + finalOptions.readPreference = ReadPreference.PRIMARY; + + // Check if the index already exists + indexInformation(db, name, finalOptions, (err, indexInformation) => { + if (err != null && err.code !== 26) return handleCallback(callback, err, null); + // If the index does not exist, create it + if (indexInformation == null || !indexInformation[index_name]) { + createIndex(db, name, fieldOrSpec, options, callback); + } else { + if (typeof callback === 'function') return handleCallback(callback, null, index_name); + } + }); +} + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Db} db The Db instance. + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options] Optional settings. See Db.prototype.eval for a list of options. + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + */ +function evaluate(db, code, parameters, options, callback) { + let finalCode = code; + let finalParameters = []; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // If not a code object translate to one + if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); + // Ensure the parameters are correct + if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = [parameters]; + } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = parameters; + } + + // Create execution selector + let cmd = { $eval: finalCode, args: finalParameters }; + // Check if the nolock parameter is passed in + if (options['nolock']) { + cmd['nolock'] = options['nolock']; + } + + // Set primary read preference + options.readPreference = new ReadPreference(ReadPreference.PRIMARY); + + // Execute the command + executeCommand(db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result && result.ok === 1) return handleCallback(callback, null, result.retval); + if (result) + return handleCallback( + callback, + MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), + null + ); + handleCallback(callback, err, result); + }); +} + +/** + * Execute a command + * + * @method + * @param {Db} db The Db instance on which to execute the command. + * @param {object} command The command hash + * @param {object} [options] Optional settings. See Db.prototype.command for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeCommand(db, command, options, callback) { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Get the db name we are executing against + const dbName = options.dbName || options.authdb || db.databaseName; + + // Convert the readPreference if its not a write + options.readPreference = ReadPreference.resolve(db, options); + + // Debug information + if (db.s.logger.isDebug()) + db.s.logger.debug( + `executing command ${JSON.stringify( + command + )} against ${dbName}.$cmd with options [${JSON.stringify( + debugOptions(debugFields, options) + )}]` + ); + + // Execute command + db.s.topology.command(db.s.namespace.withCollection('$cmd'), command, options, (err, result) => { + if (err) return handleCallback(callback, err); + if (options.full) return handleCallback(callback, null, result); + handleCallback(callback, null, result.result); + }); +} + +/** + * Runs a command on the database as admin. + * + * @method + * @param {Db} db The Db instance on which to execute the command. + * @param {object} command The command hash + * @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeDbAdminCommand(db, command, options, callback) { + const namespace = new MongoDBNamespace('admin', '$cmd'); + + db.s.topology.command(namespace, command, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); +} + +/** + * Retrieves this collections index info. + * + * @method + * @param {Db} db The Db instance on which to retrieve the index info. + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function indexInformation(db, name, options, callback) { + // If we specified full information + const full = options['full'] == null ? false : options['full']; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Process all the results from the index command and collection + function processResults(indexes) { + // Contains all the information + let info = {}; + // Process all the indexes + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for (let name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + db.collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) return callback(toError(err)); + if (!Array.isArray(indexes)) return handleCallback(callback, null, []); + if (full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +/** + * Retrieve the current profiling information for MongoDB + * + * @method + * @param {Db} db The Db instance on which to retrieve the profiling info. + * @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options. + * @param {Db~resultCallback} [callback] The command result callback. + * @deprecated Query the system.profile collection directly. + */ +function profilingInfo(db, options, callback) { + try { + db.collection('system.profile') + .find({}, options) + .toArray(callback); + } catch (err) { + return callback(err, null); + } +} + +// Validate the database name +function validateDatabaseName(databaseName) { + if (typeof databaseName !== 'string') + throw MongoError.create({ message: 'database name must be a string', driver: true }); + if (databaseName.length === 0) + throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); + if (databaseName === '$external') return; + + const invalidChars = [' ', '.', '$', '/', '\\']; + for (let i = 0; i < invalidChars.length; i++) { + if (databaseName.indexOf(invalidChars[i]) !== -1) + throw MongoError.create({ + message: "database names cannot contain the character '" + invalidChars[i] + "'", + driver: true + }); + } +} + +/** + * Create the command object for Db.prototype.createIndex. + * + * @param {Db} db The Db instance on which to create the command. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @return {Object} The insert command object. + */ +function createCreateIndexCommand(db, name, fieldOrSpec, options) { + const indexParameters = parseIndexOptions(fieldOrSpec); + const fieldHash = indexParameters.fieldHash; + + // Generate the index name + const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; + const selector = { + ns: db.s.namespace.withCollection(name).toString(), + key: fieldHash, + name: indexName + }; + + // Ensure we have a correct finalUnique + const finalUnique = options == null || 'object' === typeof options ? false : options; + // Set up options + options = options == null || typeof options === 'boolean' ? {} : options; + + // Add all the options + const keysToOmit = Object.keys(selector); + for (let optionName in options) { + if (keysToOmit.indexOf(optionName) === -1) { + selector[optionName] = options[optionName]; + } + } + + if (selector['unique'] == null) selector['unique'] = finalUnique; + + // Remove any write concern operations + const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; + for (let i = 0; i < removeKeys.length; i++) { + delete selector[removeKeys[i]]; + } + + // Return the command creation selector + return selector; +} + +/** + * Create index using the createIndexes command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback. + */ +function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { + // Build the index + const indexParameters = parseIndexOptions(fieldOrSpec); + // Generate the index name + const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; + // Set up the index + const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; + // merge all the options + const keysToOmit = Object.keys(indexes[0]).concat([ + 'writeConcern', + 'w', + 'wtimeout', + 'j', + 'fsync', + 'readPreference', + 'session' + ]); + + for (let optionName in options) { + if (keysToOmit.indexOf(optionName) === -1) { + indexes[0][optionName] = options[optionName]; + } + } + + // Get capabilities + const capabilities = db.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { + // Create a new error + const error = new MongoError('server/primary/mongos does not support collation'); + error.code = 67; + // Return the error + return callback(error); + } + + // Create command, apply write concern to command + const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); + + // ReadPreference primary + options.readPreference = ReadPreference.PRIMARY; + + // Build the command + executeCommand(db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result.ok === 0) return handleCallback(callback, toError(result), null); + // Return the indexName for backward compatibility + handleCallback(callback, null, indexName); + }); +} + +module.exports = { + createListener, + createIndex, + ensureIndex, + evaluate, + executeCommand, + executeDbAdminCommand, + indexInformation, + profilingInfo, + validateDatabaseName +}; + + +/***/ }), + +/***/ 323: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const deleteCallback = __webpack_require__(2296).deleteCallback; +const removeDocuments = __webpack_require__(2296).removeDocuments; + +class DeleteManyOperation extends OperationBase { + constructor(collection, filter, options) { + super(options); + + this.collection = collection; + this.filter = filter; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const options = this.options; + + options.single = false; + removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); + } +} + +module.exports = DeleteManyOperation; + + +/***/ }), + +/***/ 6352: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const deleteCallback = __webpack_require__(2296).deleteCallback; +const removeDocuments = __webpack_require__(2296).removeDocuments; + +class DeleteOneOperation extends OperationBase { + constructor(collection, filter, options) { + super(options); + + this.collection = collection; + this.filter = filter; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const options = this.options; + + options.single = true; + removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); + } +} + +module.exports = DeleteOneOperation; + + +/***/ }), + +/***/ 6469: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; +const CommandOperationV2 = __webpack_require__(1189); +const decorateWithCollation = __webpack_require__(1371).decorateWithCollation; +const decorateWithReadConcern = __webpack_require__(1371).decorateWithReadConcern; + +/** + * Return a list of distinct values for the given key across a collection. + * + * @class + * @property {Collection} a Collection instance. + * @property {string} key Field of the document to find distinct values for. + * @property {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @property {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. + */ +class DistinctOperation extends CommandOperationV2 { + /** + * Construct a Distinct operation. + * + * @param {Collection} a Collection instance. + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. + */ + constructor(collection, key, query, options) { + super(collection, options); + + this.collection = collection; + this.key = key; + this.query = query; + } + + /** + * Execute the operation. + * + * @param {Collection~resultCallback} [callback] The command result callback + */ + execute(server, callback) { + const coll = this.collection; + const key = this.key; + const query = this.query; + const options = this.options; + + // Distinct command + const cmd = { + distinct: coll.collectionName, + key: key, + query: query + }; + + // Add maxTimeMS if defined + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, coll, options); + + // Have we specified collation + try { + decorateWithCollation(cmd, coll, options); + } catch (err) { + return callback(err, null); + } + + super.executeCommand(server, cmd, (err, result) => { + if (err) { + callback(err); + return; + } + + callback(null, this.options.full ? result : result.values); + }); + } +} + +defineAspects(DistinctOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = DistinctOperation; + + +/***/ }), + +/***/ 2360: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const CommandOperation = __webpack_require__(499); +const defineAspects = __webpack_require__(1018).defineAspects; +const handleCallback = __webpack_require__(1371).handleCallback; + +class DropOperation extends CommandOperation { + constructor(db, options) { + const finalOptions = Object.assign({}, options, db.s.options); + + if (options.session) { + finalOptions.session = options.session; + } + + super(db, finalOptions); + } + + execute(callback) { + super.execute((err, result) => { + if (err) return handleCallback(callback, err); + if (result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); + } +} + +defineAspects(DropOperation, Aspect.WRITE_OPERATION); + +class DropCollectionOperation extends DropOperation { + constructor(db, name, options) { + super(db, options); + + this.name = name; + this.namespace = `${db.namespace}.${name}`; + } + + _buildCommand() { + return { drop: this.name }; + } +} + +class DropDatabaseOperation extends DropOperation { + _buildCommand() { + return { dropDatabase: 1 }; + } +} + +module.exports = { + DropOperation, + DropCollectionOperation, + DropDatabaseOperation +}; + + +/***/ }), + +/***/ 3560: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; +const CommandOperation = __webpack_require__(499); +const applyWriteConcern = __webpack_require__(1371).applyWriteConcern; +const handleCallback = __webpack_require__(1371).handleCallback; + +class DropIndexOperation extends CommandOperation { + constructor(collection, indexName, options) { + super(collection.s.db, options, collection); + + this.collection = collection; + this.indexName = indexName; + } + + _buildCommand() { + const collection = this.collection; + const indexName = this.indexName; + const options = this.options; + + let cmd = { dropIndexes: collection.collectionName, index: indexName }; + + // Decorate command with writeConcern if supported + cmd = applyWriteConcern(cmd, { db: collection.s.db, collection }, options); + + return cmd; + } + + execute(callback) { + // Execute command + super.execute((err, result) => { + if (typeof callback !== 'function') return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); + } +} + +defineAspects(DropIndexOperation, Aspect.WRITE_OPERATION); + +module.exports = DropIndexOperation; + + +/***/ }), + +/***/ 5328: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; +const DropIndexOperation = __webpack_require__(3560); +const handleCallback = __webpack_require__(1371).handleCallback; + +class DropIndexesOperation extends DropIndexOperation { + constructor(collection, options) { + super(collection, '*', options); + } + + execute(callback) { + super.execute(err => { + if (err) return handleCallback(callback, err, false); + handleCallback(callback, null, true); + }); + } +} + +defineAspects(DropIndexesOperation, Aspect.WRITE_OPERATION); + +module.exports = DropIndexesOperation; + + +/***/ }), + +/***/ 4451: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; +const CommandOperationV2 = __webpack_require__(1189); + +class EstimatedDocumentCountOperation extends CommandOperationV2 { + constructor(collection, query, options) { + if (typeof options === 'undefined') { + options = query; + query = undefined; + } + + super(collection, options); + this.collectionName = collection.s.namespace.collection; + if (query) { + this.query = query; + } + } + + execute(server, callback) { + const options = this.options; + const cmd = { count: this.collectionName }; + + if (this.query) { + cmd.query = this.query; + } + + if (typeof options.skip === 'number') { + cmd.skip = options.skip; + } + + if (typeof options.limit === 'number') { + cmd.limit = options.limit; + } + + if (options.hint) { + cmd.hint = options.hint; + } + + super.executeCommand(server, cmd, (err, response) => { + if (err) { + callback(err); + return; + } + + callback(null, response.n); + }); + } +} + +defineAspects(EstimatedDocumentCountOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = EstimatedDocumentCountOperation; + + +/***/ }), + +/***/ 1681: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const handleCallback = __webpack_require__(1371).handleCallback; +const MongoError = __webpack_require__(3994).MongoError; +const MongoDBNamespace = __webpack_require__(1371).MongoDBNamespace; + +class ExecuteDbAdminCommandOperation extends OperationBase { + constructor(db, selector, options) { + super(options); + + this.db = db; + this.selector = selector; + } + + execute(callback) { + const db = this.db; + const selector = this.selector; + const options = this.options; + + const namespace = new MongoDBNamespace('admin', '$cmd'); + db.s.topology.command(namespace, selector, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); + } +} + +module.exports = ExecuteDbAdminCommandOperation; + + +/***/ }), + +/***/ 2548: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const MongoError = __webpack_require__(3111).MongoError; +const Aspect = __webpack_require__(1018).Aspect; +const OperationBase = __webpack_require__(1018).OperationBase; +const ReadPreference = __webpack_require__(4485); +const isRetryableError = __webpack_require__(3111).isRetryableError; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const isUnifiedTopology = __webpack_require__(1178).isUnifiedTopology; + +/** + * Executes the given operation with provided arguments. + * + * This method reduces large amounts of duplication in the entire codebase by providing + * a single point for determining whether callbacks or promises should be used. Additionally + * it allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided + * + * @param {object} topology The topology to execute this operation on + * @param {Operation} operation The operation to execute + * @param {function} callback The command result callback + */ +function executeOperation(topology, operation, callback) { + if (topology == null) { + throw new TypeError('This method requires a valid topology instance'); + } + + if (!(operation instanceof OperationBase)) { + throw new TypeError('This method requires a valid operation instance'); + } + + if (isUnifiedTopology(topology) && topology.shouldCheckForSessionSupport()) { + return selectServerForSessionSupport(topology, operation, callback); + } + + const Promise = topology.s.promiseLibrary; + + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session, owner; + if (topology.hasSessionSupport()) { + if (operation.session == null) { + owner = Symbol(); + session = topology.startSession({ owner }); + operation.session = session; + } else if (operation.session.hasEnded) { + throw new MongoError('Use of expired sessions is not permitted'); + } + } + + let result; + if (typeof callback !== 'function') { + result = new Promise((resolve, reject) => { + callback = (err, res) => { + if (err) return reject(err); + resolve(res); + }; + }); + } + + function executeCallback(err, result) { + if (session && session.owner === owner) { + session.endSession(); + if (operation.session === session) { + operation.clearSession(); + } + } + + callback(err, result); + } + + try { + if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { + executeWithServerSelection(topology, operation, executeCallback); + } else { + operation.execute(executeCallback); + } + } catch (e) { + if (session && session.owner === owner) { + session.endSession(); + if (operation.session === session) { + operation.clearSession(); + } + } + + throw e; + } + + return result; +} + +function supportsRetryableReads(server) { + return maxWireVersion(server) >= 6; +} + +function executeWithServerSelection(topology, operation, callback) { + const readPreference = operation.readPreference || ReadPreference.primary; + const inTransaction = operation.session && operation.session.inTransaction(); + + if (inTransaction && !readPreference.equals(ReadPreference.primary)) { + callback( + new MongoError( + `Read preference in a transaction must be primary, not: ${readPreference.mode}` + ) + ); + + return; + } + + const serverSelectionOptions = { + readPreference, + session: operation.session + }; + + function callbackWithRetry(err, result) { + if (err == null) { + return callback(null, result); + } + + if (!isRetryableError(err)) { + return callback(err); + } + + // select a new server, and attempt to retry the operation + topology.selectServer(serverSelectionOptions, (err, server) => { + if (err || !supportsRetryableReads(server)) { + callback(err, null); + return; + } + + operation.execute(server, callback); + }); + } + + // select a server, and execute the operation against it + topology.selectServer(serverSelectionOptions, (err, server) => { + if (err) { + callback(err, null); + return; + } + + const shouldRetryReads = + topology.s.options.retryReads !== false && + operation.session && + !inTransaction && + supportsRetryableReads(server) && + operation.canRetryRead; + + if (operation.hasAspect(Aspect.RETRYABLE) && shouldRetryReads) { + operation.execute(server, callbackWithRetry); + return; + } + + operation.execute(server, callback); + }); +} + +// TODO [$5f5fbe42fcabad09c1c241b8]: This is only supported for unified topology, it should go away once +// we remove support for legacy topology types. +function selectServerForSessionSupport(topology, operation, callback) { + const Promise = topology.s.promiseLibrary; + + let result; + if (typeof callback !== 'function') { + result = new Promise((resolve, reject) => { + callback = (err, result) => { + if (err) return reject(err); + resolve(result); + }; + }); + } + + topology.selectServer(ReadPreference.primaryPreferred, err => { + if (err) { + callback(err); + return; + } + + executeOperation(topology, operation, callback); + }); + + return result; +} + +module.exports = executeOperation; + + +/***/ }), + +/***/ 9961: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const MongoError = __webpack_require__(3111).MongoError; + +class FindOperation extends OperationBase { + constructor(collection, ns, command, options) { + super(options); + + this.ns = ns; + this.cmd = command; + this.readPreference = ReadPreference.resolve(collection, this.options); + } + + execute(server, callback) { + // copied from `CommandOperationV2`, to be subclassed in the future + this.server = server; + + if (typeof this.cmd.allowDiskUse !== 'undefined' && maxWireVersion(server) < 4) { + callback(new MongoError('The `allowDiskUse` option is not supported on MongoDB < 3.2')); + return; + } + + // TOOD: use `MongoDBNamespace` through and through + const cursorState = this.cursorState || {}; + server.query(this.ns.toString(), this.cmd, cursorState, this.options, callback); + } +} + +defineAspects(FindOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = FindOperation; + + +/***/ }), + +/***/ 711: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const applyRetryableWrites = __webpack_require__(1371).applyRetryableWrites; +const applyWriteConcern = __webpack_require__(1371).applyWriteConcern; +const decorateWithCollation = __webpack_require__(1371).decorateWithCollation; +const executeCommand = __webpack_require__(2226).executeCommand; +const formattedOrderClause = __webpack_require__(1371).formattedOrderClause; +const handleCallback = __webpack_require__(1371).handleCallback; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const MongoError = __webpack_require__(9386).MongoError; + +class FindAndModifyOperation extends OperationBase { + constructor(collection, query, sort, doc, options) { + super(options); + + this.collection = collection; + this.query = query; + this.sort = sort; + this.doc = doc; + } + + execute(callback) { + const coll = this.collection; + const query = this.query; + const sort = formattedOrderClause(this.sort); + const doc = this.doc; + let options = this.options; + + // Create findAndModify command object + const queryObject = { + findAndModify: coll.collectionName, + query: query + }; + + if (sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + const projection = options.projection || options.fields; + + if (projection) { + queryObject.fields = projection; + } + + if (options.arrayFilters) { + queryObject.arrayFilters = options.arrayFilters; + } + + if (doc && !options.remove) { + queryObject.update = doc; + } + + if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; + + // Either use override on the function, or go back to default on either the collection + // level or db + options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // No check on the documents + options.checkKeys = false; + + // Final options for retryable writes and write concern + options = applyRetryableWrites(options, coll.s.db); + options = applyWriteConcern(options, { db: coll.s.db, collection: coll }, options); + + // Decorate the findAndModify command with the write Concern + if (options.writeConcern) { + queryObject.writeConcern = options.writeConcern; + } + + // Have we specified bypassDocumentValidation + if (options.bypassDocumentValidation === true) { + queryObject.bypassDocumentValidation = options.bypassDocumentValidation; + } + + options.readPreference = ReadPreference.primary; + + // Have we specified collation + try { + decorateWithCollation(queryObject, coll, options); + } catch (err) { + return callback(err, null); + } + + if (options.hint) { + // TODO [$5f5fbe42fcabad09c1c241b9]: once this method becomes a CommandOperationV2 we will have the server + // in place to check. + const unacknowledgedWrite = options.writeConcern && options.writeConcern.w === 0; + if (unacknowledgedWrite || maxWireVersion(coll.s.topology) < 8) { + callback( + new MongoError('The current topology does not support a hint on findAndModify commands') + ); + + return; + } + + queryObject.hint = options.hint; + } + + // Execute the command + executeCommand(coll.s.db, queryObject, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + + return handleCallback(callback, null, result); + }); + } +} + +module.exports = FindAndModifyOperation; + + +/***/ }), + +/***/ 4497: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const handleCallback = __webpack_require__(1371).handleCallback; +const OperationBase = __webpack_require__(1018).OperationBase; +const toError = __webpack_require__(1371).toError; + +class FindOneOperation extends OperationBase { + constructor(collection, query, options) { + super(options); + + this.collection = collection; + this.query = query; + } + + execute(callback) { + const coll = this.collection; + const query = this.query; + const options = this.options; + + try { + const cursor = coll + .find(query, options) + .limit(-1) + .batchSize(1); + + // Return the item + cursor.next((err, item) => { + if (err != null) return handleCallback(callback, toError(err), null); + handleCallback(callback, null, item); + }); + } catch (e) { + callback(e); + } + } +} + +module.exports = FindOneOperation; + + +/***/ }), + +/***/ 5841: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const FindAndModifyOperation = __webpack_require__(711); + +class FindOneAndDeleteOperation extends FindAndModifyOperation { + constructor(collection, filter, options) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.remove = true; + + // Basic validation + if (filter == null || typeof filter !== 'object') { + throw new TypeError('Filter parameter must be an object'); + } + + super(collection, filter, finalOptions.sort, null, finalOptions); + } +} + +module.exports = FindOneAndDeleteOperation; + + +/***/ }), + +/***/ 4316: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const FindAndModifyOperation = __webpack_require__(711); +const hasAtomicOperators = __webpack_require__(1371).hasAtomicOperators; + +class FindOneAndReplaceOperation extends FindAndModifyOperation { + constructor(collection, filter, replacement, options) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.update = true; + finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false; + finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false; + + if (filter == null || typeof filter !== 'object') { + throw new TypeError('Filter parameter must be an object'); + } + + if (replacement == null || typeof replacement !== 'object') { + throw new TypeError('Replacement parameter must be an object'); + } + + if (hasAtomicOperators(replacement)) { + throw new TypeError('Replacement document must not contain atomic operators'); + } + + super(collection, filter, finalOptions.sort, replacement, finalOptions); + } +} + +module.exports = FindOneAndReplaceOperation; + + +/***/ }), + +/***/ 1925: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const FindAndModifyOperation = __webpack_require__(711); +const hasAtomicOperators = __webpack_require__(1371).hasAtomicOperators; + +class FindOneAndUpdateOperation extends FindAndModifyOperation { + constructor(collection, filter, update, options) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.update = true; + finalOptions.new = + typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false; + finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false; + + if (filter == null || typeof filter !== 'object') { + throw new TypeError('Filter parameter must be an object'); + } + + if (update == null || typeof update !== 'object') { + throw new TypeError('Update parameter must be an object'); + } + + if (!hasAtomicOperators(update)) { + throw new TypeError('Update document requires atomic operators'); + } + + super(collection, filter, finalOptions.sort, update, finalOptions); + } +} + +module.exports = FindOneAndUpdateOperation; + + +/***/ }), + +/***/ 8169: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; +const OperationBase = __webpack_require__(1018).OperationBase; +const decorateCommand = __webpack_require__(1371).decorateCommand; +const decorateWithReadConcern = __webpack_require__(1371).decorateWithReadConcern; +const executeCommand = __webpack_require__(2226).executeCommand; +const handleCallback = __webpack_require__(1371).handleCallback; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const toError = __webpack_require__(1371).toError; + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @class + * @property {Collection} a Collection instance. + * @property {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @property {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @property {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. + */ +class GeoHaystackSearchOperation extends OperationBase { + /** + * Construct a GeoHaystackSearch operation. + * + * @param {Collection} a Collection instance. + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. + */ + constructor(collection, x, y, options) { + super(options); + + this.collection = collection; + this.x = x; + this.y = y; + } + + /** + * Execute the operation. + * + * @param {Collection~resultCallback} [callback] The command result callback + */ + execute(callback) { + const coll = this.collection; + const x = this.x; + const y = this.y; + let options = this.options; + + // Build command object + let commandObject = { + geoSearch: coll.collectionName, + near: [x, y] + }; + + // Remove read preference from hash if it exists + commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = ReadPreference.resolve(coll, options); + + // Do we have a readConcern specified + decorateWithReadConcern(commandObject, coll, options); + + // Execute the command + executeCommand(coll.s.db, commandObject, options, (err, res) => { + if (err) return handleCallback(callback, err); + if (res.err || res.errmsg) handleCallback(callback, toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); + } +} + +defineAspects(GeoHaystackSearchOperation, Aspect.READ_OPERATION); + +module.exports = GeoHaystackSearchOperation; + + +/***/ }), + +/***/ 7809: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const handleCallback = __webpack_require__(1371).handleCallback; +const indexInformationDb = __webpack_require__(2226).indexInformation; + +class IndexExistsOperation extends OperationBase { + constructor(collection, indexes, options) { + super(options); + + this.collection = collection; + this.indexes = indexes; + } + + execute(callback) { + const coll = this.collection; + const indexes = this.indexes; + const options = this.options; + + indexInformationDb(coll.s.db, coll.collectionName, options, (err, indexInformation) => { + // If we have an error return + if (err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if (!Array.isArray(indexes)) + return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); + } +} + +module.exports = IndexExistsOperation; + + +/***/ }), + +/***/ 4245: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const indexInformation = __webpack_require__(2296).indexInformation; + +class IndexInformationOperation extends OperationBase { + constructor(db, name, options) { + super(options); + + this.db = db; + this.name = name; + } + + execute(callback) { + const db = this.db; + const name = this.name; + const options = this.options; + + indexInformation(db, name, options, callback); + } +} + +module.exports = IndexInformationOperation; + + +/***/ }), + +/***/ 4218: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const indexInformation = __webpack_require__(2296).indexInformation; + +class IndexesOperation extends OperationBase { + constructor(collection, options) { + super(options); + + this.collection = collection; + } + + execute(callback) { + const coll = this.collection; + let options = this.options; + + options = Object.assign({}, { full: true }, options); + indexInformation(coll.s.db, coll.collectionName, options, callback); + } +} + +module.exports = IndexesOperation; + + +/***/ }), + +/***/ 3592: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const BulkWriteOperation = __webpack_require__(6976); +const MongoError = __webpack_require__(3994).MongoError; +const prepareDocs = __webpack_require__(2296).prepareDocs; + +class InsertManyOperation extends OperationBase { + constructor(collection, docs, options) { + super(options); + + this.collection = collection; + this.docs = docs; + } + + execute(callback) { + const coll = this.collection; + let docs = this.docs; + const options = this.options; + + if (!Array.isArray(docs)) { + return callback( + MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) + ); + } + + // If keep going set unordered + options['serializeFunctions'] = options['serializeFunctions'] || coll.s.serializeFunctions; + + docs = prepareDocs(coll, docs, options); + + // Generate the bulk write operations + const operations = [ + { + insertMany: docs + } + ]; + + const bulkWriteOperation = new BulkWriteOperation(coll, operations, options); + + bulkWriteOperation.execute((err, result) => { + if (err) return callback(err, null); + callback(null, mapInsertManyResults(docs, result)); + }); + } +} + +function mapInsertManyResults(docs, r) { + const finalResult = { + result: { ok: 1, n: r.insertedCount }, + ops: docs, + insertedCount: r.insertedCount, + insertedIds: r.insertedIds + }; + + if (r.getLastOp()) { + finalResult.result.opTime = r.getLastOp(); + } + + return finalResult; +} + +module.exports = InsertManyOperation; + + +/***/ }), + +/***/ 9915: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const MongoError = __webpack_require__(3994).MongoError; +const OperationBase = __webpack_require__(1018).OperationBase; +const insertDocuments = __webpack_require__(2296).insertDocuments; + +class InsertOneOperation extends OperationBase { + constructor(collection, doc, options) { + super(options); + + this.collection = collection; + this.doc = doc; + } + + execute(callback) { + const coll = this.collection; + const doc = this.doc; + const options = this.options; + + if (Array.isArray(doc)) { + return callback( + MongoError.create({ message: 'doc parameter must be an object', driver: true }) + ); + } + + insertDocuments(coll, [doc], options, (err, r) => { + if (callback == null) return; + if (err && callback) return callback(err); + // Workaround for pre 2.6 servers + if (r == null) return callback(null, { result: { ok: 1 } }); + // Add values to top level to ensure crud spec compatibility + r.insertedCount = r.result.n; + r.insertedId = doc._id; + if (callback) callback(null, r); + }); + } +} + +module.exports = InsertOneOperation; + + +/***/ }), + +/***/ 4956: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OptionsOperation = __webpack_require__(43); +const handleCallback = __webpack_require__(1371).handleCallback; + +class IsCappedOperation extends OptionsOperation { + constructor(collection, options) { + super(collection, options); + } + + execute(callback) { + super.execute((err, document) => { + if (err) return handleCallback(callback, err); + handleCallback(callback, null, !!(document && document.capped)); + }); + } +} + +module.exports = IsCappedOperation; + + +/***/ }), + +/***/ 840: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const CommandOperationV2 = __webpack_require__(1189); +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; +const CONSTANTS = __webpack_require__(147); + +const LIST_COLLECTIONS_WIRE_VERSION = 3; + +function listCollectionsTransforms(databaseName) { + const matching = `${databaseName}.`; + + return { + doc: doc => { + const index = doc.name.indexOf(matching); + // Remove database name if available + if (doc.name && index === 0) { + doc.name = doc.name.substr(index + matching.length); + } + + return doc; + } + }; +} + +class ListCollectionsOperation extends CommandOperationV2 { + constructor(db, filter, options) { + super(db, options, { fullResponse: true }); + + this.db = db; + this.filter = filter; + this.nameOnly = !!this.options.nameOnly; + + if (typeof this.options.batchSize === 'number') { + this.batchSize = this.options.batchSize; + } + } + + execute(server, callback) { + if (maxWireVersion(server) < LIST_COLLECTIONS_WIRE_VERSION) { + let filter = this.filter; + const databaseName = this.db.s.namespace.db; + + // If we have legacy mode and have not provided a full db name filter it + if ( + typeof filter.name === 'string' && + !new RegExp('^' + databaseName + '\\.').test(filter.name) + ) { + filter = Object.assign({}, filter); + filter.name = this.db.s.namespace.withCollection(filter.name).toString(); + } + + // No filter, filter by current database + if (filter == null) { + filter.name = `/${databaseName}/`; + } + + // Rewrite the filter to use $and to filter out indexes + if (filter.name) { + filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; + } else { + filter = { name: /^((?!\$).)*$/ }; + } + + const transforms = listCollectionsTransforms(databaseName); + server.query( + `${databaseName}.${CONSTANTS.SYSTEM_NAMESPACE_COLLECTION}`, + { query: filter }, + { batchSize: this.batchSize || 1000 }, + {}, + (err, result) => { + if ( + result && + result.message && + result.message.documents && + Array.isArray(result.message.documents) + ) { + result.message.documents = result.message.documents.map(transforms.doc); + } + + callback(err, result); + } + ); + + return; + } + + const command = { + listCollections: 1, + filter: this.filter, + cursor: this.batchSize ? { batchSize: this.batchSize } : {}, + nameOnly: this.nameOnly + }; + + return super.executeCommand(server, command, callback); + } +} + +defineAspects(ListCollectionsOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = ListCollectionsOperation; + + +/***/ }), + +/***/ 9929: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const CommandOperationV2 = __webpack_require__(1189); +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; +const MongoDBNamespace = __webpack_require__(1371).MongoDBNamespace; + +class ListDatabasesOperation extends CommandOperationV2 { + constructor(db, options) { + super(db, options); + this.ns = new MongoDBNamespace('admin', '$cmd'); + } + + execute(server, callback) { + const cmd = { listDatabases: 1 }; + if (this.options.nameOnly) { + cmd.nameOnly = Number(cmd.nameOnly); + } + + if (this.options.filter) { + cmd.filter = this.options.filter; + } + + if (typeof this.options.authorizedDatabases === 'boolean') { + cmd.authorizedDatabases = this.options.authorizedDatabases; + } + + super.executeCommand(server, cmd, callback); + } +} + +defineAspects(ListDatabasesOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = ListDatabasesOperation; + + +/***/ }), + +/***/ 28: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const CommandOperationV2 = __webpack_require__(1189); +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; +const maxWireVersion = __webpack_require__(1178).maxWireVersion; + +const LIST_INDEXES_WIRE_VERSION = 3; + +class ListIndexesOperation extends CommandOperationV2 { + constructor(collection, options) { + super(collection, options, { fullResponse: true }); + + this.collectionNamespace = collection.s.namespace; + } + + execute(server, callback) { + const serverWireVersion = maxWireVersion(server); + if (serverWireVersion < LIST_INDEXES_WIRE_VERSION) { + const systemIndexesNS = this.collectionNamespace.withCollection('system.indexes').toString(); + const collectionNS = this.collectionNamespace.toString(); + + server.query(systemIndexesNS, { query: { ns: collectionNS } }, {}, this.options, callback); + return; + } + + const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; + super.executeCommand( + server, + { listIndexes: this.collectionNamespace.collection, cursor }, + callback + ); + } +} + +defineAspects(ListIndexesOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = ListIndexesOperation; + + +/***/ }), + +/***/ 2779: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const applyWriteConcern = __webpack_require__(1371).applyWriteConcern; +const Code = __webpack_require__(3994).BSON.Code; +const decorateWithCollation = __webpack_require__(1371).decorateWithCollation; +const decorateWithReadConcern = __webpack_require__(1371).decorateWithReadConcern; +const executeCommand = __webpack_require__(2226).executeCommand; +const handleCallback = __webpack_require__(1371).handleCallback; +const isObject = __webpack_require__(1371).isObject; +const loadDb = __webpack_require__(8275).loadDb; +const OperationBase = __webpack_require__(1018).OperationBase; +const ReadPreference = __webpack_require__(3994).ReadPreference; +const toError = __webpack_require__(1371).toError; + +const exclusionList = [ + 'readPreference', + 'session', + 'bypassDocumentValidation', + 'w', + 'wtimeout', + 'j', + 'writeConcern' +]; + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @class + * @property {Collection} a Collection instance. + * @property {(function|string)} map The mapping function. + * @property {(function|string)} reduce The reduce function. + * @property {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. + */ +class MapReduceOperation extends OperationBase { + /** + * Constructs a MapReduce operation. + * + * @param {Collection} a Collection instance. + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. + */ + constructor(collection, map, reduce, options) { + super(options); + + this.collection = collection; + this.map = map; + this.reduce = reduce; + } + + /** + * Execute the operation. + * + * @param {Collection~resultCallback} [callback] The command result callback + */ + execute(callback) { + const coll = this.collection; + const map = this.map; + const reduce = this.reduce; + let options = this.options; + + const mapCommandHash = { + mapReduce: coll.collectionName, + map: map, + reduce: reduce + }; + + // Add any other options passed in + for (let n in options) { + if ('scope' === n) { + mapCommandHash[n] = processScope(options[n]); + } else { + // Only include if not in exclusion list + if (exclusionList.indexOf(n) === -1) { + mapCommandHash[n] = options[n]; + } + } + } + + options = Object.assign({}, options); + + // Ensure we have the right read preference inheritance + options.readPreference = ReadPreference.resolve(coll, options); + + // If we have a read preference and inline is not set as output fail hard + if ( + options.readPreference !== false && + options.readPreference !== 'primary' && + options['out'] && + options['out'].inline !== 1 && + options['out'] !== 'inline' + ) { + // Force readPreference to primary + options.readPreference = 'primary'; + // Decorate command with writeConcern if supported + applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); + } else { + decorateWithReadConcern(mapCommandHash, coll, options); + } + + // Is bypassDocumentValidation specified + if (options.bypassDocumentValidation === true) { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Have we specified collation + try { + decorateWithCollation(mapCommandHash, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute command + executeCommand(coll.s.db, mapCommandHash, options, (err, result) => { + if (err) return handleCallback(callback, err); + // Check if we have an error + if (1 !== result.ok || result.err || result.errmsg) { + return handleCallback(callback, toError(result)); + } + + // Create statistics value + const stats = {}; + if (result.timeMillis) stats['processtime'] = result.timeMillis; + if (result.counts) stats['counts'] = result.counts; + if (result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if (result.results) { + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, null, result.results); + } + + return handleCallback(callback, null, { results: result.results, stats: stats }); + } + + // The returned collection + let collection = null; + + // If we have an object it's a different db + if (result.result != null && typeof result.result === 'object') { + const doc = result.result; + // Return a collection from another db + let Db = loadDb(); + collection = new Db(doc.db, coll.s.db.s.topology, coll.s.db.s.options).collection( + doc.collection + ); + } else { + // Create a collection object that wraps the result collection + collection = coll.s.db.collection(result.result); + } + + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, err, collection); + } + + // Return stats as third set of values + handleCallback(callback, err, { collection: collection, stats: stats }); + }); + } +} + +/** + * Functions that are passed as scope args must + * be converted to Code instances. + * @ignore + */ +function processScope(scope) { + if (!isObject(scope) || scope._bsontype === 'ObjectID') { + return scope; + } + + const keys = Object.keys(scope); + let key; + const new_scope = {}; + + for (let i = keys.length - 1; i >= 0; i--) { + key = keys[i]; + if ('function' === typeof scope[key]) { + new_scope[key] = new Code(String(scope[key])); + } else { + new_scope[key] = processScope(scope[key]); + } + } + + return new_scope; +} + +module.exports = MapReduceOperation; + + +/***/ }), + +/***/ 1018: +/***/ ((module) => { + +"use strict"; + + +const Aspect = { + READ_OPERATION: Symbol('READ_OPERATION'), + WRITE_OPERATION: Symbol('WRITE_OPERATION'), + RETRYABLE: Symbol('RETRYABLE'), + EXECUTE_WITH_SELECTION: Symbol('EXECUTE_WITH_SELECTION'), + NO_INHERIT_OPTIONS: Symbol('NO_INHERIT_OPTIONS') +}; + +/** + * This class acts as a parent class for any operation and is responsible for setting this.options, + * as well as setting and getting a session. + * Additionally, this class implements `hasAspect`, which determines whether an operation has + * a specific aspect. + */ +class OperationBase { + constructor(options) { + this.options = Object.assign({}, options); + } + + hasAspect(aspect) { + if (this.constructor.aspects == null) { + return false; + } + return this.constructor.aspects.has(aspect); + } + + set session(session) { + Object.assign(this.options, { session }); + } + + get session() { + return this.options.session; + } + + clearSession() { + delete this.options.session; + } + + get canRetryRead() { + return true; + } + + execute() { + throw new TypeError('`execute` must be implemented for OperationBase subclasses'); + } +} + +function defineAspects(operation, aspects) { + if (!Array.isArray(aspects) && !(aspects instanceof Set)) { + aspects = [aspects]; + } + aspects = new Set(aspects); + Object.defineProperty(operation, 'aspects', { + value: aspects, + writable: false + }); + return aspects; +} + +module.exports = { + Aspect, + defineAspects, + OperationBase +}; + + +/***/ }), + +/***/ 43: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const handleCallback = __webpack_require__(1371).handleCallback; +const MongoError = __webpack_require__(3994).MongoError; + +class OptionsOperation extends OperationBase { + constructor(collection, options) { + super(options); + + this.collection = collection; + } + + execute(callback) { + const coll = this.collection; + const opts = this.options; + + coll.s.db.listCollections({ name: coll.collectionName }, opts).toArray((err, collections) => { + if (err) return handleCallback(callback, err); + if (collections.length === 0) { + return handleCallback( + callback, + MongoError.create({ message: `collection ${coll.namespace} not found`, driver: true }) + ); + } + + handleCallback(callback, err, collections[0].options || null); + }); + } +} + +module.exports = OptionsOperation; + + +/***/ }), + +/***/ 3969: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const CommandOperation = __webpack_require__(499); + +class ProfilingLevelOperation extends CommandOperation { + constructor(db, command, options) { + super(db, options); + } + + _buildCommand() { + const command = { profile: -1 }; + + return command; + } + + execute(callback) { + super.execute((err, doc) => { + if (err == null && doc.ok === 1) { + const was = doc.was; + if (was === 0) return callback(null, 'off'); + if (was === 1) return callback(null, 'slow_only'); + if (was === 2) return callback(null, 'all'); + return callback(new Error('Error: illegal profiling level value ' + was), null); + } else { + err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); + } + }); + } +} + +module.exports = ProfilingLevelOperation; + + +/***/ }), + +/***/ 6331: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const defineAspects = __webpack_require__(1018).defineAspects; +const CommandOperationV2 = __webpack_require__(1189); +const serverType = __webpack_require__(2291).serverType; +const ServerType = __webpack_require__(2291).ServerType; +const MongoError = __webpack_require__(3994).MongoError; + +class ReIndexOperation extends CommandOperationV2 { + constructor(collection, options) { + super(collection, options); + this.collectionName = collection.collectionName; + } + + execute(server, callback) { + if (serverType(server) !== ServerType.Standalone) { + callback(new MongoError(`reIndex can only be executed on standalone servers.`)); + return; + } + super.executeCommand(server, { reIndex: this.collectionName }, (err, result) => { + if (err) { + callback(err); + return; + } + callback(null, !!result.ok); + }); + } +} + +defineAspects(ReIndexOperation, [Aspect.EXECUTE_WITH_SELECTION]); + +module.exports = ReIndexOperation; + + +/***/ }), + +/***/ 1969: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const CommandOperation = __webpack_require__(499); +const defineAspects = __webpack_require__(1018).defineAspects; +const handleCallback = __webpack_require__(1371).handleCallback; +const WriteConcern = __webpack_require__(2481); + +class RemoveUserOperation extends CommandOperation { + constructor(db, username, options) { + const commandOptions = {}; + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern != null) { + commandOptions.writeConcern = writeConcern; + } + + if (options.dbName) { + commandOptions.dbName = options.dbName; + } + + // Add maxTimeMS to options if set + if (typeof options.maxTimeMS === 'number') { + commandOptions.maxTimeMS = options.maxTimeMS; + } + + super(db, commandOptions); + + this.username = username; + } + + _buildCommand() { + const username = this.username; + + // Build the command to execute + const command = { dropUser: username }; + + return command; + } + + execute(callback) { + // Attempt to execute command + super.execute((err, result) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, err, result.ok ? true : false); + }); + } +} + +defineAspects(RemoveUserOperation, Aspect.WRITE_OPERATION); + +module.exports = RemoveUserOperation; + + +/***/ }), + +/***/ 2808: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const applyWriteConcern = __webpack_require__(1371).applyWriteConcern; +const checkCollectionName = __webpack_require__(1371).checkCollectionName; +const executeDbAdminCommand = __webpack_require__(2226).executeDbAdminCommand; +const handleCallback = __webpack_require__(1371).handleCallback; +const loadCollection = __webpack_require__(8275).loadCollection; +const toError = __webpack_require__(1371).toError; + +class RenameOperation extends OperationBase { + constructor(collection, newName, options) { + super(options); + + this.collection = collection; + this.newName = newName; + } + + execute(callback) { + const coll = this.collection; + const newName = this.newName; + const options = this.options; + + let Collection = loadCollection(); + // Check the collection name + checkCollectionName(newName); + // Build the command + const renameCollection = coll.namespace; + const toCollection = coll.s.namespace.withCollection(newName).toString(); + const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; + const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; + + // Decorate command with writeConcern if supported + applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); + + // Execute against admin + executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => { + if (err) return handleCallback(callback, err, null); + // We have an error + if (doc.errmsg) return handleCallback(callback, toError(doc), null); + try { + return handleCallback( + callback, + null, + new Collection( + coll.s.db, + coll.s.topology, + coll.s.namespace.db, + newName, + coll.s.pkFactory, + coll.s.options + ) + ); + } catch (err) { + return handleCallback(callback, toError(err), null); + } + }); + } +} + +module.exports = RenameOperation; + + +/***/ }), + +/***/ 2508: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const updateDocuments = __webpack_require__(2296).updateDocuments; +const hasAtomicOperators = __webpack_require__(1371).hasAtomicOperators; + +class ReplaceOneOperation extends OperationBase { + constructor(collection, filter, replacement, options) { + super(options); + + if (hasAtomicOperators(replacement)) { + throw new TypeError('Replacement document must not contain atomic operators'); + } + + this.collection = collection; + this.filter = filter; + this.replacement = replacement; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const replacement = this.replacement; + const options = this.options; + + // Set single document update + options.multi = false; + + // Execute update + updateDocuments(coll, filter, replacement, options, (err, r) => + replaceCallback(err, r, replacement, callback) + ); + } +} + +function replaceCallback(err, r, doc, callback) { + if (callback == null) return; + if (err && callback) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + r.ops = [doc]; // TODO: Should we still have this? + if (callback) callback(null, r); +} + +module.exports = ReplaceOneOperation; + + +/***/ }), + +/***/ 1363: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const CommandOperationV2 = __webpack_require__(1189); +const defineAspects = __webpack_require__(1018).defineAspects; +const Aspect = __webpack_require__(1018).Aspect; + +class RunCommandOperation extends CommandOperationV2 { + constructor(parent, command, options) { + super(parent, options); + this.command = command; + } + execute(server, callback) { + const command = this.command; + this.executeCommand(server, command, callback); + } +} +defineAspects(RunCommandOperation, [Aspect.EXECUTE_WITH_SELECTION, Aspect.NO_INHERIT_OPTIONS]); + +module.exports = RunCommandOperation; + + +/***/ }), + +/***/ 6301: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const CommandOperation = __webpack_require__(499); +const levelValues = new Set(['off', 'slow_only', 'all']); + +class SetProfilingLevelOperation extends CommandOperation { + constructor(db, level, options) { + let profile = 0; + + if (level === 'off') { + profile = 0; + } else if (level === 'slow_only') { + profile = 1; + } else if (level === 'all') { + profile = 2; + } + + super(db, options); + this.level = level; + this.profile = profile; + } + + _buildCommand() { + const profile = this.profile; + + // Set up the profile number + const command = { profile }; + + return command; + } + + execute(callback) { + const level = this.level; + + if (!levelValues.has(level)) { + return callback(new Error('Error: illegal profiling level value ' + level)); + } + + super.execute((err, doc) => { + if (err == null && doc.ok === 1) return callback(null, level); + return err != null + ? callback(err, null) + : callback(new Error('Error with profile command'), null); + }); + } +} + +module.exports = SetProfilingLevelOperation; + + +/***/ }), + +/***/ 968: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Aspect = __webpack_require__(1018).Aspect; +const CommandOperation = __webpack_require__(499); +const defineAspects = __webpack_require__(1018).defineAspects; + +/** + * Get all the collection statistics. + * + * @class + * @property {Collection} a Collection instance. + * @property {object} [options] Optional settings. See Collection.prototype.stats for a list of options. + */ +class StatsOperation extends CommandOperation { + /** + * Construct a Stats operation. + * + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options. + */ + constructor(collection, options) { + super(collection.s.db, options, collection); + } + + _buildCommand() { + const collection = this.collection; + const options = this.options; + + // Build command object + const command = { + collStats: collection.collectionName + }; + + // Check if we have the scale value + if (options['scale'] != null) { + command['scale'] = options['scale']; + } + + return command; + } +} + +defineAspects(StatsOperation, Aspect.READ_OPERATION); + +module.exports = StatsOperation; + + +/***/ }), + +/***/ 9350: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const updateCallback = __webpack_require__(2296).updateCallback; +const updateDocuments = __webpack_require__(2296).updateDocuments; +const hasAtomicOperators = __webpack_require__(1371).hasAtomicOperators; + +class UpdateManyOperation extends OperationBase { + constructor(collection, filter, update, options) { + super(options); + + if (!hasAtomicOperators(update)) { + throw new TypeError('Update document requires atomic operators'); + } + + this.collection = collection; + this.filter = filter; + this.update = update; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const update = this.update; + const options = this.options; + + // Set single document update + options.multi = true; + // Execute update + updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); + } +} + +module.exports = UpdateManyOperation; + + +/***/ }), + +/***/ 9068: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const OperationBase = __webpack_require__(1018).OperationBase; +const updateDocuments = __webpack_require__(2296).updateDocuments; +const hasAtomicOperators = __webpack_require__(1371).hasAtomicOperators; + +class UpdateOneOperation extends OperationBase { + constructor(collection, filter, update, options) { + super(options); + + if (!hasAtomicOperators(update)) { + throw new TypeError('Update document requires atomic operators'); + } + + this.collection = collection; + this.filter = filter; + this.update = update; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const update = this.update; + const options = this.options; + + // Set single document update + options.multi = false; + // Execute update + updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); + } +} + +function updateCallback(err, r, callback) { + if (callback == null) return; + if (err) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + callback(null, r); +} + +module.exports = UpdateOneOperation; + + +/***/ }), + +/***/ 9263: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const CommandOperation = __webpack_require__(499); + +class ValidateCollectionOperation extends CommandOperation { + constructor(admin, collectionName, options) { + // Decorate command with extra options + let command = { validate: collectionName }; + const keys = Object.keys(options); + for (let i = 0; i < keys.length; i++) { + if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { + command[keys[i]] = options[keys[i]]; + } + } + + super(admin.s.db, options, null, command); + this.collectionName = collectionName; + } + + execute(callback) { + const collectionName = this.collectionName; + + super.execute((err, doc) => { + if (err != null) return callback(err, null); + + if (doc.ok === 0) return callback(new Error('Error with validate command'), null); + if (doc.result != null && doc.result.constructor !== String) + return callback(new Error('Error with validation data'), null); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new Error('Error: invalid collection ' + collectionName), null); + if (doc.valid != null && !doc.valid) + return callback(new Error('Error: invalid collection ' + collectionName), null); + + return callback(null, doc); + }); + } +} + +module.exports = ValidateCollectionOperation; + + +/***/ }), + +/***/ 7289: +/***/ ((module) => { + +"use strict"; + + +/** + * The **ReadConcern** class is a class that represents a MongoDB ReadConcern. + * @class + * @property {string} level The read concern level + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html + */ +class ReadConcern { + /** + * Constructs a ReadConcern from the read concern properties. + * @param {string} [level] The read concern level ({'local'|'available'|'majority'|'linearizable'|'snapshot'}) + */ + constructor(level) { + if (level != null) { + this.level = level; + } + } + + /** + * Construct a ReadConcern given an options object. + * + * @param {object} options The options object from which to extract the write concern. + * @return {ReadConcern} + */ + static fromOptions(options) { + if (options == null) { + return; + } + + if (options.readConcern) { + if (options.readConcern instanceof ReadConcern) { + return options.readConcern; + } + + return new ReadConcern(options.readConcern.level); + } + + if (options.level) { + return new ReadConcern(options.level); + } + } + + static get MAJORITY() { + return 'majority'; + } + + static get AVAILABLE() { + return 'available'; + } + + static get LINEARIZABLE() { + return 'linearizable'; + } + + static get SNAPSHOT() { + return 'snapshot'; + } +} + +module.exports = ReadConcern; + + +/***/ }), + +/***/ 2048: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const TopologyBase = __webpack_require__(8589)/* .TopologyBase */ .oF; +const MongoError = __webpack_require__(3994).MongoError; +const CMongos = __webpack_require__(3994).Mongos; +const Cursor = __webpack_require__(7159); +const Server = __webpack_require__(8421); +const Store = __webpack_require__(8589)/* .Store */ .yh; +const MAX_JS_INT = __webpack_require__(1371).MAX_JS_INT; +const translateOptions = __webpack_require__(1371).translateOptions; +const filterOptions = __webpack_require__(1371).filterOptions; +const mergeOptions = __webpack_require__(1371).mergeOptions; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * **Mongos Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'acceptableLatencyMS', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCRL', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'promiseLibrary', + 'monitorCommands' +]; + +/** + * Creates a new Mongos instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out + * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires Mongos#connect + * @fires Mongos#ha + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#fullsetup + * @fires Mongos#open + * @fires Mongos#close + * @fires Mongos#error + * @fires Mongos#timeout + * @fires Mongos#parseError + * @fires Mongos#commandStarted + * @fires Mongos#commandSucceeded + * @fires Mongos#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {Mongos} a Mongos instance. + */ +class Mongos extends TopologyBase { + constructor(servers, options) { + super(); + + options = options || {}; + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure all the instances are Server + for (var i = 0; i < servers.length; i++) { + if (!(servers[i] instanceof Server)) { + throw MongoError.create({ + message: 'all seed list instances must be of the Server type', + driver: true + }); + } + } + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Build seed list + var seedlist = servers.map(function(x) { + return { host: x.host, port: x.port }; + }); + + // Get the reconnect option + var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: reconnect, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Internal state + this.s = { + // Create the Mongos + coreTopology: new CMongos(seedlist, clonedOptions), + // Server capabilities + sCapabilities: null, + // Debug turned on + debug: clonedOptions.debug, + // Store option defaults + storeOptions: storeOptions, + // Cloned options + clonedOptions: clonedOptions, + // Actual store of callbacks + store: store, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: new Set(), + // Promise library + promiseLibrary: options.promiseLibrary || Promise + }; + } + + // Connect + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = {}; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.removeListener(e, connectErrorHandler); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + // Force close the topology + self.close(true); + + // Try to callback + try { + callback(err); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Error handler + var reconnectHandler = function() { + self.emit('reconnect'); + self.s.store.execute(); + }; + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + var events = ['timeout', 'error', 'close', 'fullsetup']; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up listeners + self.s.coreTopology.on('timeout', errorHandler('timeout')); + self.s.coreTopology.on('error', errorHandler('error')); + self.s.coreTopology.on('close', errorHandler('close')); + + // Set up serverConfig listeners + self.s.coreTopology.on('fullsetup', function() { + self.emit('fullsetup', self); + }); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Clear out all the current handlers left over + var events = [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed' + ]; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + + // Set up listeners + self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); + self.s.coreTopology.once('error', connectErrorHandler('error')); + self.s.coreTopology.once('close', connectErrorHandler('close')); + self.s.coreTopology.once('connect', connectHandler); + // Join and leave events + self.s.coreTopology.on('joined', relay('joined')); + self.s.coreTopology.on('left', relay('left')); + + // Reconnect server + self.s.coreTopology.on('reconnect', reconnectHandler); + + // Start connection + self.s.coreTopology.connect(_options); + } +} + +Object.defineProperty(Mongos.prototype, 'haInterval', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.haInterval; + } +}); + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * The mongos high availability event + * + * @event Mongos#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the mongos set + * + * @event Mongos#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos set + * + * @event Mongos#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * Mongos open event, emitted when mongos can start processing commands. + * + * @event Mongos#open + * @type {Mongos} + */ + +/** + * Mongos close event + * + * @event Mongos#close + * @type {object} + */ + +/** + * Mongos error event, emitted if there is an error listener. + * + * @event Mongos#error + * @type {MongoError} + */ + +/** + * Mongos timeout event + * + * @event Mongos#timeout + * @type {object} + */ + +/** + * Mongos parseError event + * + * @event Mongos#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Mongos#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Mongos#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Mongos#commandFailed + * @type {object} + */ + +module.exports = Mongos; + + +/***/ }), + +/***/ 2632: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Topology = __webpack_require__(3994).Topology; +const ServerCapabilities = __webpack_require__(8589)/* .ServerCapabilities */ .ug; +const Cursor = __webpack_require__(7159); +const translateOptions = __webpack_require__(1371).translateOptions; + +class NativeTopology extends Topology { + constructor(servers, options) { + options = options || {}; + + let clonedOptions = Object.assign( + {}, + { + cursorFactory: Cursor, + reconnect: false, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + maxPoolSize: + typeof options.maxPoolSize === 'number' + ? options.maxPoolSize + : typeof options.poolSize === 'number' + ? options.poolSize + : 10, + minPoolSize: + typeof options.minPoolSize === 'number' + ? options.minPoolSize + : typeof options.minSize === 'number' + ? options.minSize + : 0, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + super(servers, clonedOptions); + } + + capabilities() { + if (this.s.sCapabilities) return this.s.sCapabilities; + if (this.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.lastIsMaster()); + return this.s.sCapabilities; + } + + // Command + command(ns, cmd, options, callback) { + super.command(ns.toString(), cmd, options, callback); + } + + // Insert + insert(ns, ops, options, callback) { + super.insert(ns.toString(), ops, options, callback); + } + + // Update + update(ns, ops, options, callback) { + super.update(ns.toString(), ops, options, callback); + } + + // Remove + remove(ns, ops, options, callback) { + super.remove(ns.toString(), ops, options, callback); + } +} + +module.exports = NativeTopology; + + +/***/ }), + +/***/ 382: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const Server = __webpack_require__(8421); +const Cursor = __webpack_require__(7159); +const MongoError = __webpack_require__(3994).MongoError; +const TopologyBase = __webpack_require__(8589)/* .TopologyBase */ .oF; +const Store = __webpack_require__(8589)/* .Store */ .yh; +const CReplSet = __webpack_require__(3994).ReplSet; +const MAX_JS_INT = __webpack_require__(1371).MAX_JS_INT; +const translateOptions = __webpack_require__(1371).translateOptions; +const filterOptions = __webpack_require__(1371).filterOptions; +const mergeOptions = __webpack_require__(1371).mergeOptions; + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connections. + * + * **ReplSet Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'replicaSet', + 'rs_name', + 'secondaryAcceptableLatencyMS', + 'connectWithNoPrimary', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslCRL', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'strategy', + 'debug', + 'family', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'maxStalenessSeconds', + 'promiseLibrary', + 'minSize', + 'monitorCommands' +]; + +/** + * Creates a new ReplSet instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options] Optional settings. + * @param {boolean} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=10000] Time between each replicaset status check. + * @param {string} [options.replicaSet] The name of the replicaset to connect to. + * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher. + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out + * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#fullsetup + * @fires ReplSet#open + * @fires ReplSet#close + * @fires ReplSet#error + * @fires ReplSet#timeout + * @fires ReplSet#parseError + * @fires ReplSet#commandStarted + * @fires ReplSet#commandSucceeded + * @fires ReplSet#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {ReplSet} a ReplSet instance. + */ +class ReplSet extends TopologyBase { + constructor(servers, options) { + super(); + + options = options || {}; + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure all the instances are Server + for (var i = 0; i < servers.length; i++) { + if (!(servers[i] instanceof Server)) { + throw MongoError.create({ + message: 'all seed list instances must be of the Server type', + driver: true + }); + } + } + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Build seed list + var seedlist = servers.map(function(x) { + return { host: x.host, port: x.port }; + }); + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: false, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Create the ReplSet + var coreTopology = new CReplSet(seedlist, clonedOptions); + + // Listen to reconnect event + coreTopology.on('reconnect', function() { + self.emit('reconnect'); + store.execute(); + }); + + // Internal state + this.s = { + // Replicaset + coreTopology: coreTopology, + // Server capabilities + sCapabilities: null, + // Debug tag + tag: options.tag, + // Store options + storeOptions: storeOptions, + // Cloned options + clonedOptions: clonedOptions, + // Store + store: store, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: new Set(), + // Promise library + promiseLibrary: options.promiseLibrary || Promise + }; + + // Debug + if (clonedOptions.debug) { + // Last ismaster + Object.defineProperty(this, 'replset', { + enumerable: true, + get: function() { + return coreTopology; + } + }); + } + } + + // Connect method + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = {}; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Clear out all the current handlers left over + var events = [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha' + ]; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Replset events relay + var replsetRelay = function(event) { + return function(t, server) { + self.emit(event, t, server.lastIsMaster(), server); + }; + }; + + // Relay ha + var relayHa = function(t, state) { + self.emit('ha', t, state); + + if (t === 'start') { + self.emit('ha_connect', t, state); + } else if (t === 'end') { + self.emit('ha_ismaster', t, state); + } + }; + + // Set up serverConfig listeners + self.s.coreTopology.on('joined', replsetRelay('joined')); + self.s.coreTopology.on('left', relay('left')); + self.s.coreTopology.on('ping', relay('ping')); + self.s.coreTopology.on('ha', relayHa); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + + self.s.coreTopology.on('fullsetup', function() { + self.emit('fullsetup', self, self); + }); + + self.s.coreTopology.on('all', function() { + self.emit('all', null, self); + }); + + // Connect handler + var connectHandler = function() { + // Set up listeners + self.s.coreTopology.once('timeout', errorHandler('timeout')); + self.s.coreTopology.once('error', errorHandler('error')); + self.s.coreTopology.once('close', errorHandler('close')); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + ['timeout', 'error', 'close'].forEach(function(e) { + self.s.coreTopology.removeListener(e, connectErrorHandler); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + // Destroy the replset + self.s.coreTopology.destroy(); + + // Try to callback + try { + callback(err); + } catch (err) { + if (!self.s.coreTopology.isConnected()) + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Set up listeners + self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); + self.s.coreTopology.once('error', connectErrorHandler('error')); + self.s.coreTopology.once('close', connectErrorHandler('close')); + self.s.coreTopology.once('connect', connectHandler); + + // Start connection + self.s.coreTopology.connect(_options); + } + + close(forceClosed, callback) { + ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e)); + super.close(forceClosed, callback); + } +} + +Object.defineProperty(ReplSet.prototype, 'haInterval', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.haInterval; + } +}); + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * ReplSet open event, emitted when replicaset can start processing commands. + * + * @event ReplSet#open + * @type {Replset} + */ + +/** + * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. + * + * @event ReplSet#fullsetup + * @type {Replset} + */ + +/** + * ReplSet close event + * + * @event ReplSet#close + * @type {object} + */ + +/** + * ReplSet error event, emitted if there is an error listener. + * + * @event ReplSet#error + * @type {MongoError} + */ + +/** + * ReplSet timeout event + * + * @event ReplSet#timeout + * @type {object} + */ + +/** + * ReplSet parseError event + * + * @event ReplSet#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event ReplSet#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event ReplSet#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event ReplSet#commandFailed + * @type {object} + */ + +module.exports = ReplSet; + + +/***/ }), + +/***/ 8421: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const CServer = __webpack_require__(3994).Server; +const Cursor = __webpack_require__(7159); +const TopologyBase = __webpack_require__(8589)/* .TopologyBase */ .oF; +const Store = __webpack_require__(8589)/* .Store */ .yh; +const MongoError = __webpack_require__(3994).MongoError; +const MAX_JS_INT = __webpack_require__(1371).MAX_JS_INT; +const translateOptions = __webpack_require__(1371).translateOptions; +const filterOptions = __webpack_require__(1371).filterOptions; +const mergeOptions = __webpack_require__(1371).mergeOptions; + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * **Server Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'acceptableLatencyMS', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCRL', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'family', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'reconnectInterval', + 'monitoring', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'compression', + 'promiseLibrary', + 'monitorCommands' +]; + +/** + * Creates a new Server instance + * @class + * @deprecated + * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. + * @param {number} [port] The server port if IP4. + * @param {object} [options] Optional settings. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out + * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.monitoring=true] Triggers the server instance to call ismaster + * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @fires Server#commandStarted + * @fires Server#commandSucceeded + * @fires Server#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {Server} a Server instance. + */ +class Server extends TopologyBase { + constructor(host, port, options) { + super(); + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Promise library + const promiseLibrary = options.promiseLibrary; + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Detect if we have a socket connection + if (host.indexOf('/') !== -1) { + if (port != null && typeof port === 'object') { + options = port; + port = null; + } + } else if (port == null) { + throw MongoError.create({ message: 'port must be specified', driver: true }); + } + + // Get the reconnect option + var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + host: host, + port: port, + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: reconnect, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Define the internal properties + this.s = { + // Create an instance of a server instance from core module + coreTopology: new CServer(clonedOptions), + // Server capabilities + sCapabilities: null, + // Cloned options + clonedOptions: clonedOptions, + // Reconnect + reconnect: clonedOptions.reconnect, + // Emit error + emitError: clonedOptions.emitError, + // Pool size + poolSize: clonedOptions.size, + // Store Options + storeOptions: storeOptions, + // Store + store: store, + // Host + host: host, + // Port + port: port, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: new Set(), + // Promise library + promiseLibrary: promiseLibrary || Promise + }; + } + + // Connect + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = this.s.clonedOptions; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.s.coreTopology.removeListener(e, connectHandlers[e]); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Error handler + var reconnectHandler = function() { + self.emit('reconnect', self); + self.s.store.execute(); + }; + + // Reconnect failed + var reconnectFailedHandler = function(err) { + self.emit('reconnectFailed', err); + self.s.store.flush(err); + }; + + // Destroy called on topology, perform cleanup + var destroyHandler = function() { + self.s.store.flush(); + }; + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ['timeout', 'error', 'close', 'destroy'].forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up listeners + self.s.coreTopology.on('timeout', errorHandler('timeout')); + self.s.coreTopology.once('error', errorHandler('error')); + self.s.coreTopology.on('close', errorHandler('close')); + // Only called on destroy + self.s.coreTopology.on('destroy', destroyHandler); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Set up listeners + var connectHandlers = { + timeout: connectErrorHandler('timeout'), + error: connectErrorHandler('error'), + close: connectErrorHandler('close') + }; + + // Clear out all the current handlers left over + [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed' + ].forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Add the event handlers + self.s.coreTopology.once('timeout', connectHandlers.timeout); + self.s.coreTopology.once('error', connectHandlers.error); + self.s.coreTopology.once('close', connectHandlers.close); + self.s.coreTopology.once('connect', connectHandler); + // Reconnect server + self.s.coreTopology.on('reconnect', reconnectHandler); + self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect')); + self.s.coreTopology.on('monitoring', relay('monitoring')); + + // Start connection + self.s.coreTopology.connect(_options); + } +} + +Object.defineProperty(Server.prototype, 'poolSize', { + enumerable: true, + get: function() { + return this.s.coreTopology.connections().length; + } +}); + +Object.defineProperty(Server.prototype, 'autoReconnect', { + enumerable: true, + get: function() { + return this.s.reconnect; + } +}); + +Object.defineProperty(Server.prototype, 'host', { + enumerable: true, + get: function() { + return this.s.host; + } +}); + +Object.defineProperty(Server.prototype, 'port', { + enumerable: true, + get: function() { + return this.s.port; + } +}); + +/** + * Server connect event + * + * @event Server#connect + * @type {object} + */ + +/** + * Server close event + * + * @event Server#close + * @type {object} + */ + +/** + * Server reconnect event + * + * @event Server#reconnect + * @type {object} + */ + +/** + * Server error event + * + * @event Server#error + * @type {MongoError} + */ + +/** + * Server timeout event + * + * @event Server#timeout + * @type {object} + */ + +/** + * Server parseError event + * + * @event Server#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Server#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Server#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Server#commandFailed + * @type {object} + */ + +module.exports = Server; + + +/***/ }), + +/***/ 8589: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +const EventEmitter = __webpack_require__(8614), + MongoError = __webpack_require__(3994).MongoError, + f = __webpack_require__(1669).format, + ReadPreference = __webpack_require__(3994).ReadPreference, + ClientSession = __webpack_require__(3994).Sessions.ClientSession; + +// The store of ops +var Store = function(topology, storeOptions) { + var self = this; + var storedOps = []; + storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; + + // Internal state + this.s = { + storedOps: storedOps, + storeOptions: storeOptions, + topology: topology + }; + + Object.defineProperty(this, 'length', { + enumerable: true, + get: function() { + return self.s.storedOps.length; + } + }); +}; + +Store.prototype.add = function(opType, ns, ops, options, callback) { + if (this.s.storeOptions.force) { + return callback(MongoError.create({ message: 'db closed by application', driver: true })); + } + + if (this.s.storeOptions.bufferMaxEntries === 0) { + return callback( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + if ( + this.s.storeOptions.bufferMaxEntries > 0 && + this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries + ) { + while (this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + return; + } + + this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback }); +}; + +Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { + if (this.s.storeOptions.force) { + return callback(MongoError.create({ message: 'db closed by application', driver: true })); + } + + if (this.s.storeOptions.bufferMaxEntries === 0) { + return callback( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + if ( + this.s.storeOptions.bufferMaxEntries > 0 && + this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries + ) { + while (this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + return; + } + + this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback }); +}; + +Store.prototype.flush = function(err) { + while (this.s.storedOps.length > 0) { + this.s.storedOps + .shift() + .c( + err || + MongoError.create({ message: f('no connection available for operation'), driver: true }) + ); + } +}; + +var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; +var secondaryOptions = ['secondary', 'secondaryPreferred']; + +Store.prototype.execute = function(options) { + options = options || {}; + // Get current ops + var ops = this.s.storedOps; + // Reset the ops + this.s.storedOps = []; + + // Unpack options + var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true; + var executeSecondary = + typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true; + + // Execute all the stored ops + while (ops.length > 0) { + var op = ops.shift(); + + if (op.t === 'cursor') { + if (executePrimary && executeSecondary) { + op.o[op.m].apply(op.o, op.p); + } else if ( + executePrimary && + op.o.options && + op.o.options.readPreference && + primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 + ) { + op.o[op.m].apply(op.o, op.p); + } else if ( + !executePrimary && + executeSecondary && + op.o.options && + op.o.options.readPreference && + secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 + ) { + op.o[op.m].apply(op.o, op.p); + } + } else if (op.t === 'auth') { + this.s.topology[op.t].apply(this.s.topology, op.o); + } else { + if (executePrimary && executeSecondary) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } else if ( + executePrimary && + op.op && + op.op.readPreference && + primaryOptions.indexOf(op.op.readPreference.mode) !== -1 + ) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } else if ( + !executePrimary && + executeSecondary && + op.op && + op.op.readPreference && + secondaryOptions.indexOf(op.op.readPreference.mode) !== -1 + ) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } + } + } +}; + +Store.prototype.all = function() { + return this.s.storedOps; +}; + +// Server capabilities +var ServerCapabilities = function(ismaster) { + var setup_get_property = function(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, + get: function() { + return value; + } + }); + }; + + // Capabilities + var aggregationCursor = false; + var writeCommands = false; + var textSearch = false; + var authCommands = false; + var listCollections = false; + var listIndexes = false; + var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; + var commandsTakeWriteConcern = false; + var commandsTakeCollation = false; + + if (ismaster.minWireVersion >= 0) { + textSearch = true; + } + + if (ismaster.maxWireVersion >= 1) { + aggregationCursor = true; + authCommands = true; + } + + if (ismaster.maxWireVersion >= 2) { + writeCommands = true; + } + + if (ismaster.maxWireVersion >= 3) { + listCollections = true; + listIndexes = true; + } + + if (ismaster.maxWireVersion >= 5) { + commandsTakeWriteConcern = true; + commandsTakeCollation = true; + } + + // If no min or max wire version set to 0 + if (ismaster.minWireVersion == null) { + ismaster.minWireVersion = 0; + } + + if (ismaster.maxWireVersion == null) { + ismaster.maxWireVersion = 0; + } + + // Map up read only parameters + setup_get_property(this, 'hasAggregationCursor', aggregationCursor); + setup_get_property(this, 'hasWriteCommands', writeCommands); + setup_get_property(this, 'hasTextSearch', textSearch); + setup_get_property(this, 'hasAuthCommands', authCommands); + setup_get_property(this, 'hasListCollectionsCommand', listCollections); + setup_get_property(this, 'hasListIndexesCommand', listIndexes); + setup_get_property(this, 'minWireVersion', ismaster.minWireVersion); + setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion); + setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch); + setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern); + setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation); +}; + +class TopologyBase extends EventEmitter { + constructor() { + super(); + this.setMaxListeners(Infinity); + } + + // Sessions related methods + hasSessionSupport() { + return this.logicalSessionTimeoutMinutes != null; + } + + startSession(options, clientOptions) { + const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); + + session.once('ended', () => { + this.s.sessions.delete(session); + }); + + this.s.sessions.add(session); + return session; + } + + endSessions(sessions, callback) { + return this.s.coreTopology.endSessions(sessions, callback); + } + + get clientMetadata() { + return this.s.coreTopology.s.options.metadata; + } + + // Server capabilities + capabilities() { + if (this.s.sCapabilities) return this.s.sCapabilities; + if (this.s.coreTopology.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster()); + return this.s.sCapabilities; + } + + // Command + command(ns, cmd, options, callback) { + this.s.coreTopology.command(ns.toString(), cmd, ReadPreference.translate(options), callback); + } + + // Insert + insert(ns, ops, options, callback) { + this.s.coreTopology.insert(ns.toString(), ops, options, callback); + } + + // Update + update(ns, ops, options, callback) { + this.s.coreTopology.update(ns.toString(), ops, options, callback); + } + + // Remove + remove(ns, ops, options, callback) { + this.s.coreTopology.remove(ns.toString(), ops, options, callback); + } + + // IsConnected + isConnected(options) { + options = options || {}; + options = ReadPreference.translate(options); + + return this.s.coreTopology.isConnected(options); + } + + // IsDestroyed + isDestroyed() { + return this.s.coreTopology.isDestroyed(); + } + + // Cursor + cursor(ns, cmd, options) { + options = options || {}; + options = ReadPreference.translate(options); + options.disconnectHandler = this.s.store; + options.topology = this; + + return this.s.coreTopology.cursor(ns, cmd, options); + } + + lastIsMaster() { + return this.s.coreTopology.lastIsMaster(); + } + + selectServer(selector, options, callback) { + return this.s.coreTopology.selectServer(selector, options, callback); + } + + /** + * Unref all sockets + * @method + */ + unref() { + return this.s.coreTopology.unref(); + } + + /** + * All raw connections + * @method + * @return {array} + */ + connections() { + return this.s.coreTopology.connections(); + } + + close(forceClosed, callback) { + // If we have sessions, we want to individually move them to the session pool, + // and then send a single endSessions call. + this.s.sessions.forEach(session => session.endSession()); + + if (this.s.sessionPool) { + this.s.sessionPool.endAllPooledSessions(); + } + + // We need to wash out all stored processes + if (forceClosed === true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } + + this.s.coreTopology.destroy( + { + force: typeof forceClosed === 'boolean' ? forceClosed : false + }, + callback + ); + } +} + +// Properties +Object.defineProperty(TopologyBase.prototype, 'bson', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.bson; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'parserType', { + enumerable: true, + get: function() { + return this.s.coreTopology.parserType; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + return this.s.coreTopology.logicalSessionTimeoutMinutes; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'type', { + enumerable: true, + get: function() { + return this.s.coreTopology.type; + } +}); + +exports.yh = Store; +exports.ug = ServerCapabilities; +exports.oF = TopologyBase; + + +/***/ }), + +/***/ 8729: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const ReadPreference = __webpack_require__(3994).ReadPreference, + parser = __webpack_require__(8835), + f = __webpack_require__(1669).format, + Logger = __webpack_require__(3994).Logger, + dns = __webpack_require__(881); +const ReadConcern = __webpack_require__(7289); + +module.exports = function(url, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + let result; + try { + result = parser.parse(url, true); + } catch (e) { + return callback(new Error('URL malformed, cannot be parsed')); + } + + if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') { + return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`')); + } + + if (result.protocol === 'mongodb:') { + return parseHandler(url, options, callback); + } + + // Otherwise parse this as an SRV record + if (result.hostname.split('.').length < 3) { + return callback(new Error('URI does not have hostname, domain name and tld')); + } + + result.domainLength = result.hostname.split('.').length; + + if (result.pathname && result.pathname.match(',')) { + return callback(new Error('Invalid URI, cannot contain multiple hostnames')); + } + + if (result.port) { + return callback(new Error('Ports not accepted with `mongodb+srv` URIs')); + } + + let srvAddress = `_mongodb._tcp.${result.host}`; + dns.resolveSrv(srvAddress, function(err, addresses) { + if (err) return callback(err); + + if (addresses.length === 0) { + return callback(new Error('No addresses found at host')); + } + + for (let i = 0; i < addresses.length; i++) { + if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { + return callback(new Error('Server record does not share hostname with parent URI')); + } + } + + let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; + let connectionStrings = addresses.map(function(address, i) { + if (i === 0) return `${base}${address.name}:${address.port}`; + else return `${address.name}:${address.port}`; + }); + + let connectionString = connectionStrings.join(',') + '/'; + let connectionStringOptions = []; + + // Add the default database if needed + if (result.path) { + let defaultDb = result.path.slice(1); + if (defaultDb.indexOf('?') !== -1) { + defaultDb = defaultDb.slice(0, defaultDb.indexOf('?')); + } + + connectionString += defaultDb; + } + + // Default to SSL true + if (!options.ssl && !result.search) { + connectionStringOptions.push('ssl=true'); + } else if (!options.ssl && result.search && !result.search.match('ssl')) { + connectionStringOptions.push('ssl=true'); + } + + // Keep original uri options + if (result.search) { + connectionStringOptions.push(result.search.replace('?', '')); + } + + dns.resolveTxt(result.host, function(err, record) { + if (err && err.code !== 'ENODATA') return callback(err); + if (err && err.code === 'ENODATA') record = null; + + if (record) { + if (record.length > 1) { + return callback(new Error('Multiple text records not allowed')); + } + + record = record[0]; + if (record.length > 1) record = record.join(''); + else record = record[0]; + + if (!record.includes('authSource') && !record.includes('replicaSet')) { + return callback(new Error('Text record must only set `authSource` or `replicaSet`')); + } + + connectionStringOptions.push(record); + } + + // Add any options to the connection string + if (connectionStringOptions.length) { + connectionString += `?${connectionStringOptions.join('&')}`; + } + + parseHandler(connectionString, options, callback); + }); + }); +}; + +function matchesParentDomain(srvAddress, parentDomain) { + let regex = /^.*?\./; + let srv = `.${srvAddress.replace(regex, '')}`; + let parent = `.${parentDomain.replace(regex, '')}`; + if (srv.endsWith(parent)) return true; + else return false; +} + +function parseHandler(address, options, callback) { + let result, err; + try { + result = parseConnectionString(address, options); + } catch (e) { + err = e; + } + + return err ? callback(err, null) : callback(null, result); +} + +function parseConnectionString(url, options) { + // Variables + let connection_part = ''; + let auth_part = ''; + let query_string_part = ''; + let dbName = 'admin'; + + // Url parser result + let result = parser.parse(url, true); + if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) { + throw new Error('No hostname or hostnames provided in connection string'); + } + + if (result.port === '0') { + throw new Error('Invalid port (zero) with hostname'); + } + + if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { + throw new Error('Invalid port (larger than 65535) with hostname'); + } + + if ( + result.path && + result.path.length > 0 && + result.path[0] !== '/' && + url.indexOf('.sock') === -1 + ) { + throw new Error('Missing delimiting slash between hosts and options'); + } + + if (result.query) { + for (let name in result.query) { + if (name.indexOf('::') !== -1) { + throw new Error('Double colon in host identifier'); + } + + if (result.query[name] === '') { + throw new Error('Query parameter ' + name + ' is an incomplete value pair'); + } + } + } + + if (result.auth) { + let parts = result.auth.split(':'); + if (url.indexOf(result.auth) !== -1 && parts.length > 2) { + throw new Error('Username with password containing an unescaped colon'); + } + + if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) { + throw new Error('Username containing an unescaped at-sign'); + } + } + + // Remove query + let clean = url.split('?').shift(); + + // Extract the list of hosts + let strings = clean.split(','); + let hosts = []; + + for (let i = 0; i < strings.length; i++) { + let hostString = strings[i]; + + if (hostString.indexOf('mongodb') !== -1) { + if (hostString.indexOf('@') !== -1) { + hosts.push(hostString.split('@').pop()); + } else { + hosts.push(hostString.substr('mongodb://'.length)); + } + } else if (hostString.indexOf('/') !== -1) { + hosts.push(hostString.split('/').shift()); + } else if (hostString.indexOf('/') === -1) { + hosts.push(hostString.trim()); + } + } + + for (let i = 0; i < hosts.length; i++) { + let r = parser.parse(f('mongodb://%s', hosts[i].trim())); + if (r.path && r.path.indexOf('.sock') !== -1) continue; + if (r.path && r.path.indexOf(':') !== -1) { + // Not connecting to a socket so check for an extra slash in the hostname. + // Using String#split as perf is better than match. + if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) { + throw new Error('Slash in host identifier'); + } else { + throw new Error('Double colon in host identifier'); + } + } + } + + // If we have a ? mark cut the query elements off + if (url.indexOf('?') !== -1) { + query_string_part = url.substr(url.indexOf('?') + 1); + connection_part = url.substring('mongodb://'.length, url.indexOf('?')); + } else { + connection_part = url.substring('mongodb://'.length); + } + + // Check if we have auth params + if (connection_part.indexOf('@') !== -1) { + auth_part = connection_part.split('@')[0]; + connection_part = connection_part.split('@')[1]; + } + + // Check there is not more than one unescaped slash + if (connection_part.split('/').length > 2) { + throw new Error( + "Unsupported host '" + + connection_part.split('?')[0] + + "', hosts must be URL encoded and contain at most one unencoded slash" + ); + } + + // Check if the connection string has a db + if (connection_part.indexOf('.sock') !== -1) { + if (connection_part.indexOf('.sock/') !== -1) { + dbName = connection_part.split('.sock/')[1]; + // Check if multiple database names provided, or just an illegal trailing backslash + if (dbName.indexOf('/') !== -1) { + if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + connection_part = connection_part.split( + '/', + connection_part.indexOf('.sock') + '.sock'.length + ); + } + } else if (connection_part.indexOf('/') !== -1) { + // Check if multiple database names provided, or just an illegal trailing backslash + if (connection_part.split('/').length > 2) { + if (connection_part.split('/')[2].length === 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + dbName = connection_part.split('/')[1]; + connection_part = connection_part.split('/')[0]; + } + + // URI decode the host information + connection_part = decodeURIComponent(connection_part); + + // Result object + let object = {}; + + // Pick apart the authentication part of the string + let authPart = auth_part || ''; + let auth = authPart.split(':', 2); + + // Decode the authentication URI components and verify integrity + let user = decodeURIComponent(auth[0]); + if (auth[0] !== encodeURIComponent(user)) { + throw new Error('Username contains an illegal unescaped character'); + } + auth[0] = user; + + if (auth[1]) { + let pass = decodeURIComponent(auth[1]); + if (auth[1] !== encodeURIComponent(pass)) { + throw new Error('Password contains an illegal unescaped character'); + } + auth[1] = pass; + } + + // Add auth to final object if we have 2 elements + if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] }; + // if user provided auth options, use that + if (options && options.auth != null) object.auth = options.auth; + + // Variables used for temporary storage + let hostPart; + let urlOptions; + let servers; + let compression; + let serverOptions = { socketOptions: {} }; + let dbOptions = { read_preference_tags: [] }; + let replSetServersOptions = { socketOptions: {} }; + let mongosOptions = { socketOptions: {} }; + // Add server options to final object + object.server_options = serverOptions; + object.db_options = dbOptions; + object.rs_options = replSetServersOptions; + object.mongos_options = mongosOptions; + + // Let's check if we are using a domain socket + if (url.match(/\.sock/)) { + // Split out the socket part + let domainSocket = url.substring( + url.indexOf('mongodb://') + 'mongodb://'.length, + url.lastIndexOf('.sock') + '.sock'.length + ); + // Clean out any auth stuff if any + if (domainSocket.indexOf('@') !== -1) domainSocket = domainSocket.split('@')[1]; + domainSocket = decodeURIComponent(domainSocket); + servers = [{ domain_socket: domainSocket }]; + } else { + // Split up the db + hostPart = connection_part; + // Deduplicate servers + let deduplicatedServers = {}; + + // Parse all server results + servers = hostPart + .split(',') + .map(function(h) { + let _host, _port, ipv6match; + //check if it matches [IPv6]:port, where the port number is optional + if ((ipv6match = /\[([^\]]+)\](?::(.+))?/.exec(h))) { + _host = ipv6match[1]; + _port = parseInt(ipv6match[2], 10) || 27017; + } else { + //otherwise assume it's IPv4, or plain hostname + let hostPort = h.split(':', 2); + _host = hostPort[0] || 'localhost'; + _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; + // Check for localhost?safe=true style case + if (_host.indexOf('?') !== -1) _host = _host.split(/\?/)[0]; + } + + // No entry returned for duplicate server + if (deduplicatedServers[_host + '_' + _port]) return null; + deduplicatedServers[_host + '_' + _port] = 1; + + // Return the mapped object + return { host: _host, port: _port }; + }) + .filter(function(x) { + return x != null; + }); + } + + // Get the db name + object.dbName = dbName || 'admin'; + // Split up all the options + urlOptions = (query_string_part || '').split(/[&;]/); + // Ugh, we have to figure out which options go to which constructor manually. + urlOptions.forEach(function(opt) { + if (!opt) return; + var splitOpt = opt.split('='), + name = splitOpt[0], + value = splitOpt[1]; + + // Options implementations + switch (name) { + case 'slaveOk': + case 'slave_ok': + serverOptions.slave_ok = value === 'true'; + dbOptions.slaveOk = value === 'true'; + break; + case 'maxPoolSize': + case 'poolSize': + serverOptions.poolSize = parseInt(value, 10); + replSetServersOptions.poolSize = parseInt(value, 10); + break; + case 'appname': + object.appname = decodeURIComponent(value); + break; + case 'autoReconnect': + case 'auto_reconnect': + serverOptions.auto_reconnect = value === 'true'; + break; + case 'ssl': + if (value === 'prefer') { + serverOptions.ssl = value; + replSetServersOptions.ssl = value; + mongosOptions.ssl = value; + break; + } + serverOptions.ssl = value === 'true'; + replSetServersOptions.ssl = value === 'true'; + mongosOptions.ssl = value === 'true'; + break; + case 'sslValidate': + serverOptions.sslValidate = value === 'true'; + replSetServersOptions.sslValidate = value === 'true'; + mongosOptions.sslValidate = value === 'true'; + break; + case 'replicaSet': + case 'rs_name': + replSetServersOptions.rs_name = value; + break; + case 'reconnectWait': + replSetServersOptions.reconnectWait = parseInt(value, 10); + break; + case 'retries': + replSetServersOptions.retries = parseInt(value, 10); + break; + case 'readSecondary': + case 'read_secondary': + replSetServersOptions.read_secondary = value === 'true'; + break; + case 'fsync': + dbOptions.fsync = value === 'true'; + break; + case 'journal': + dbOptions.j = value === 'true'; + break; + case 'safe': + dbOptions.safe = value === 'true'; + break; + case 'nativeParser': + case 'native_parser': + dbOptions.native_parser = value === 'true'; + break; + case 'readConcernLevel': + dbOptions.readConcern = new ReadConcern(value); + break; + case 'connectTimeoutMS': + serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + break; + case 'socketTimeoutMS': + serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + break; + case 'w': + dbOptions.w = parseInt(value, 10); + if (isNaN(dbOptions.w)) dbOptions.w = value; + break; + case 'authSource': + dbOptions.authSource = value; + break; + case 'gssapiServiceName': + dbOptions.gssapiServiceName = value; + break; + case 'authMechanism': + if (value === 'GSSAPI') { + // If no password provided decode only the principal + if (object.auth == null) { + let urlDecodeAuthPart = decodeURIComponent(authPart); + if (urlDecodeAuthPart.indexOf('@') === -1) + throw new Error('GSSAPI requires a provided principal'); + object.auth = { user: urlDecodeAuthPart, password: null }; + } else { + object.auth.user = decodeURIComponent(object.auth.user); + } + } else if (value === 'MONGODB-X509') { + object.auth = { user: decodeURIComponent(authPart) }; + } + + // Only support GSSAPI or MONGODB-CR for now + if ( + value !== 'GSSAPI' && + value !== 'MONGODB-X509' && + value !== 'MONGODB-CR' && + value !== 'DEFAULT' && + value !== 'SCRAM-SHA-1' && + value !== 'SCRAM-SHA-256' && + value !== 'PLAIN' + ) + throw new Error( + 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism' + ); + + // Authentication mechanism + dbOptions.authMechanism = value; + break; + case 'authMechanismProperties': + { + // Split up into key, value pairs + let values = value.split(','); + let o = {}; + // For each value split into key, value + values.forEach(function(x) { + let v = x.split(':'); + o[v[0]] = v[1]; + }); + + // Set all authMechanismProperties + dbOptions.authMechanismProperties = o; + // Set the service name value + if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; + if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; + if (typeof o.CANONICALIZE_HOST_NAME === 'string') + dbOptions.gssapiCanonicalizeHostName = + o.CANONICALIZE_HOST_NAME === 'true' ? true : false; + } + break; + case 'wtimeoutMS': + dbOptions.wtimeout = parseInt(value, 10); + break; + case 'readPreference': + if (!ReadPreference.isValid(value)) + throw new Error( + 'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest' + ); + dbOptions.readPreference = value; + break; + case 'maxStalenessSeconds': + dbOptions.maxStalenessSeconds = parseInt(value, 10); + break; + case 'readPreferenceTags': + { + // Decode the value + value = decodeURIComponent(value); + // Contains the tag object + let tagObject = {}; + if (value == null || value === '') { + dbOptions.read_preference_tags.push(tagObject); + break; + } + + // Split up the tags + let tags = value.split(/,/); + for (let i = 0; i < tags.length; i++) { + let parts = tags[i].trim().split(/:/); + tagObject[parts[0]] = parts[1]; + } + + // Set the preferences tags + dbOptions.read_preference_tags.push(tagObject); + } + break; + case 'compressors': + { + compression = serverOptions.compression || {}; + let compressors = value.split(','); + if ( + !compressors.every(function(compressor) { + return compressor === 'snappy' || compressor === 'zlib'; + }) + ) { + throw new Error('Compressors must be at least one of snappy or zlib'); + } + + compression.compressors = compressors; + serverOptions.compression = compression; + } + break; + case 'zlibCompressionLevel': + { + compression = serverOptions.compression || {}; + let zlibCompressionLevel = parseInt(value, 10); + if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) { + throw new Error('zlibCompressionLevel must be an integer between -1 and 9'); + } + + compression.zlibCompressionLevel = zlibCompressionLevel; + serverOptions.compression = compression; + } + break; + case 'retryWrites': + dbOptions.retryWrites = value === 'true'; + break; + case 'minSize': + dbOptions.minSize = parseInt(value, 10); + break; + default: + { + let logger = Logger('URL Parser'); + logger.warn(`${name} is not supported as a connection string option`); + } + break; + } + }); + + // No tags: should be null (not []) + if (dbOptions.read_preference_tags.length === 0) { + dbOptions.read_preference_tags = null; + } + + // Validate if there are an invalid write concern combinations + if ( + (dbOptions.w === -1 || dbOptions.w === 0) && + (dbOptions.journal === true || dbOptions.fsync === true || dbOptions.safe === true) + ) + throw new Error('w set to -1 or 0 cannot be combined with safe/w/journal/fsync'); + + // If no read preference set it to primary + if (!dbOptions.readPreference) { + dbOptions.readPreference = 'primary'; + } + + // make sure that user-provided options are applied with priority + dbOptions = Object.assign(dbOptions, options); + + // Add servers to result + object.servers = servers; + + // Returned parsed object + return object; +} + + +/***/ }), + +/***/ 1371: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; + +const MongoError = __webpack_require__(3111).MongoError; +const WriteConcern = __webpack_require__(2481); + +var shallowClone = function(obj) { + var copy = {}; + for (var name in obj) copy[name] = obj[name]; + return copy; +}; + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable: true, + get: function() { + return value; + } + }); +}; + +var formatSortValue = (exports.formatSortValue = function(sortDirection) { + var value = ('' + sortDirection).toLowerCase(); + + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new Error( + 'Illegal sort clause, must be of the form ' + + "[['field1', '(ascending|descending)'], " + + "['field2', '(ascending|descending)']]" + ); + } +}); + +var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) { + var orderBy = {}; + if (sortValue == null) return null; + if (Array.isArray(sortValue)) { + if (sortValue.length === 0) { + return null; + } + + for (var i = 0; i < sortValue.length; i++) { + if (sortValue[i].constructor === String) { + orderBy[sortValue[i]] = 1; + } else { + orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); + } + } + } else if (sortValue != null && typeof sortValue === 'object') { + orderBy = sortValue; + } else if (typeof sortValue === 'string') { + orderBy[sortValue] = 1; + } else { + throw new Error( + 'Illegal sort clause, must be of the form ' + + "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" + ); + } + + return orderBy; +}); + +var checkCollectionName = function checkCollectionName(collectionName) { + if ('string' !== typeof collectionName) { + throw new MongoError('collection name must be a String'); + } + + if (!collectionName || collectionName.indexOf('..') !== -1) { + throw new MongoError('collection names cannot be empty'); + } + + if ( + collectionName.indexOf('$') !== -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null + ) { + throw new MongoError("collection names must not contain '$'"); + } + + if (collectionName.match(/^\.|\.$/) != null) { + throw new MongoError("collection names must not start or end with '.'"); + } + + // Validate that we are not passing 0x00 in the collection name + if (collectionName.indexOf('\x00') !== -1) { + throw new MongoError('collection names cannot contain a null character'); + } +}; + +var handleCallback = function(callback, err, value1, value2) { + try { + if (callback == null) return; + + if (callback) { + return value2 ? callback(err, value1, value2) : callback(err, value1); + } + } catch (err) { + process.nextTick(function() { + throw err; + }); + return false; + } + + return true; +}; + +/** + * Wrap a Mongo error document in an Error instance + * @ignore + * @api private + */ +var toError = function(error) { + if (error instanceof Error) return error; + + var msg = error.err || error.errmsg || error.errMessage || error; + var e = MongoError.create({ message: msg, driver: true }); + + // Get all object keys + var keys = typeof error === 'object' ? Object.keys(error) : []; + + for (var i = 0; i < keys.length; i++) { + try { + e[keys[i]] = error[keys[i]]; + } catch (err) { + // continue + } + } + + return e; +}; + +/** + * @ignore + */ +var normalizeHintField = function normalizeHintField(hint) { + var finalHint = null; + + if (typeof hint === 'string') { + finalHint = hint; + } else if (Array.isArray(hint)) { + finalHint = {}; + + hint.forEach(function(param) { + finalHint[param] = 1; + }); + } else if (hint != null && typeof hint === 'object') { + finalHint = {}; + for (var name in hint) { + finalHint[name] = hint[name]; + } + } + + return finalHint; +}; + +/** + * Create index name based on field spec + * + * @ignore + * @api private + */ +var parseIndexOptions = function(fieldOrSpec) { + var fieldHash = {}; + var indexes = []; + var keys; + + // Get all the fields accordingly + if ('string' === typeof fieldOrSpec) { + // 'type' + indexes.push(fieldOrSpec + '_' + 1); + fieldHash[fieldOrSpec] = 1; + } else if (Array.isArray(fieldOrSpec)) { + fieldOrSpec.forEach(function(f) { + if ('string' === typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } else if (Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } else if (isObject(f)) { + // [{location:'2d'}, {type:1}] + keys = Object.keys(f); + keys.forEach(function(k) { + indexes.push(k + '_' + f[k]); + fieldHash[k] = f[k]; + }); + } else { + // undefined (ignore) + } + }); + } else if (isObject(fieldOrSpec)) { + // {location:'2d', type:1} + keys = Object.keys(fieldOrSpec); + keys.forEach(function(key) { + indexes.push(key + '_' + fieldOrSpec[key]); + fieldHash[key] = fieldOrSpec[key]; + }); + } + + return { + name: indexes.join('_'), + keys: keys, + fieldHash: fieldHash + }; +}; + +var isObject = (exports.isObject = function(arg) { + return '[object Object]' === Object.prototype.toString.call(arg); +}); + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +}; + +var decorateCommand = function(command, options, exclude) { + for (var name in options) { + if (exclude.indexOf(name) === -1) command[name] = options[name]; + } + + return command; +}; + +var mergeOptions = function(target, source) { + for (var name in source) { + target[name] = source[name]; + } + + return target; +}; + +// Merge options with translation +var translateOptions = function(target, source) { + var translations = { + // SSL translation options + sslCA: 'ca', + sslCRL: 'crl', + sslValidate: 'rejectUnauthorized', + sslKey: 'key', + sslCert: 'cert', + sslPass: 'passphrase', + // SocketTimeout translation options + socketTimeoutMS: 'socketTimeout', + connectTimeoutMS: 'connectionTimeout', + // Replicaset options + replicaSet: 'setName', + rs_name: 'setName', + secondaryAcceptableLatencyMS: 'acceptableLatency', + connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', + // Mongos options + acceptableLatencyMS: 'localThresholdMS' + }; + + for (var name in source) { + if (translations[name]) { + target[translations[name]] = source[name]; + } else { + target[name] = source[name]; + } + } + + return target; +}; + +var filterOptions = function(options, names) { + var filterOptions = {}; + + for (var name in options) { + if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; + } + + // Filtered options + return filterOptions; +}; + +// Write concern keys +var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync']; + +// Merge the write concern options +var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) { + // Mix in any allowed options + for (var i = 0; i < keys.length; i++) { + if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { + targetOptions[keys[i]] = sourceOptions[keys[i]]; + } + } + + // No merging of write concern + if (!mergeWriteConcern) return targetOptions; + + // Found no write Concern options + var found = false; + for (i = 0; i < writeConcernKeys.length; i++) { + if (targetOptions[writeConcernKeys[i]]) { + found = true; + break; + } + } + + if (!found) { + for (i = 0; i < writeConcernKeys.length; i++) { + if (sourceOptions[writeConcernKeys[i]]) { + targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; + } + } + } + + return targetOptions; +}; + +/** + * Executes the given operation with provided arguments. + * + * This method reduces large amounts of duplication in the entire codebase by providing + * a single point for determining whether callbacks or promises should be used. Additionally + * it allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided + * + * @param {object} topology The topology to execute this operation on + * @param {function} operation The operation to execute + * @param {array} args Arguments to apply the provided operation + * @param {object} [options] Options that modify the behavior of the method + */ +const executeLegacyOperation = (topology, operation, args, options) => { + if (topology == null) { + throw new TypeError('This method requires a valid topology instance'); + } + + if (!Array.isArray(args)) { + throw new TypeError('This method requires an array of arguments to apply'); + } + + options = options || {}; + const Promise = topology.s.promiseLibrary; + let callback = args[args.length - 1]; + + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session, opOptions, owner; + if (!options.skipSessions && topology.hasSessionSupport()) { + opOptions = args[args.length - 2]; + if (opOptions == null || opOptions.session == null) { + owner = Symbol(); + session = topology.startSession({ owner }); + const optionsIndex = args.length - 2; + args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); + } else if (opOptions.session && opOptions.session.hasEnded) { + throw new MongoError('Use of expired sessions is not permitted'); + } + } + + const makeExecuteCallback = (resolve, reject) => + function executeCallback(err, result) { + if (session && session.owner === owner && !options.returnsCursor) { + session.endSession(() => { + delete opOptions.session; + if (err) return reject(err); + resolve(result); + }); + } else { + if (err) return reject(err); + resolve(result); + } + }; + + // Execute using callback + if (typeof callback === 'function') { + callback = args.pop(); + const handler = makeExecuteCallback( + result => callback(null, result), + err => callback(err, null) + ); + args.push(handler); + + try { + return operation.apply(null, args); + } catch (e) { + handler(e); + throw e; + } + } + + // Return a Promise + if (args[args.length - 1] != null) { + throw new TypeError('final argument to `executeLegacyOperation` must be a callback'); + } + + return new Promise(function(resolve, reject) { + const handler = makeExecuteCallback(resolve, reject); + args[args.length - 1] = handler; + + try { + return operation.apply(null, args); + } catch (e) { + handler(e); + } + }); +}; + +/** + * Applies retryWrites: true to a command if retryWrites is set on the command's database. + * + * @param {object} target The target command to which we will apply retryWrites. + * @param {object} db The database from which we can inherit a retryWrites value. + */ +function applyRetryableWrites(target, db) { + if (db && db.s.options.retryWrites) { + target.retryWrites = true; + } + + return target; +} + +/** + * Applies a write concern to a command based on well defined inheritance rules, optionally + * detecting support for the write concern in the first place. + * + * @param {Object} target the target command we will be applying the write concern to + * @param {Object} sources sources where we can inherit default write concerns from + * @param {Object} [options] optional settings passed into a command for write concern overrides + * @returns {Object} the (now) decorated target + */ +function applyWriteConcern(target, sources, options) { + options = options || {}; + const db = sources.db; + const coll = sources.collection; + + if (options.session && options.session.inTransaction()) { + // writeConcern is not allowed within a multi-statement transaction + if (target.writeConcern) { + delete target.writeConcern; + } + + return target; + } + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern) { + return Object.assign(target, { writeConcern }); + } + + if (coll && coll.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); + } + + if (db && db.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); + } + + return target; +} + +/** + * Checks if a given value is a Promise + * + * @param {*} maybePromise + * @return true if the provided value is a Promise + */ +function isPromiseLike(maybePromise) { + return maybePromise && typeof maybePromise.then === 'function'; +} + +/** + * Applies collation to a given command. + * + * @param {object} [command] the command on which to apply collation + * @param {(Cursor|Collection)} [target] target of command + * @param {object} [options] options containing collation settings + */ +function decorateWithCollation(command, target, options) { + const topology = (target.s && target.s.topology) || target.topology; + + if (!topology) { + throw new TypeError('parameter "target" is missing a topology'); + } + + const capabilities = topology.capabilities(); + if (options.collation && typeof options.collation === 'object') { + if (capabilities && capabilities.commandsTakeCollation) { + command.collation = options.collation; + } else { + throw new MongoError(`Current topology does not support collation`); + } + } +} + +/** + * Applies a read concern to a given command. + * + * @param {object} command the command on which to apply the read concern + * @param {Collection} coll the parent collection of the operation calling this method + */ +function decorateWithReadConcern(command, coll, options) { + if (options && options.session && options.session.inTransaction()) { + return; + } + let readConcern = Object.assign({}, command.readConcern || {}); + if (coll.s.readConcern) { + Object.assign(readConcern, coll.s.readConcern); + } + + if (Object.keys(readConcern).length > 0) { + Object.assign(command, { readConcern: readConcern }); + } +} + +const emitProcessWarning = msg => process.emitWarning(msg, 'DeprecationWarning'); +const emitConsoleWarning = msg => console.error(msg); +const emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning; + +/** + * Default message handler for generating deprecation warnings. + * + * @param {string} name function name + * @param {string} option option name + * @return {string} warning message + * @ignore + * @api private + */ +function defaultMsgHandler(name, option) { + return `${name} option [${option}] is deprecated and will be removed in a later version.`; +} + +/** + * Deprecates a given function's options. + * + * @param {object} config configuration for deprecation + * @param {string} config.name function name + * @param {Array} config.deprecatedOptions options to deprecate + * @param {number} config.optionsIndex index of options object in function arguments array + * @param {function} [config.msgHandler] optional custom message handler to generate warnings + * @param {function} fn the target function of deprecation + * @return {function} modified function that warns once per deprecated option, and executes original function + * @ignore + * @api private + */ +function deprecateOptions(config, fn) { + if (process.noDeprecation === true) { + return fn; + } + + const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; + + const optionsWarned = new Set(); + function deprecated() { + const options = arguments[config.optionsIndex]; + + // ensure options is a valid, non-empty object, otherwise short-circuit + if (!isObject(options) || Object.keys(options).length === 0) { + return fn.apply(this, arguments); + } + + config.deprecatedOptions.forEach(deprecatedOption => { + if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) { + optionsWarned.add(deprecatedOption); + const msg = msgHandler(config.name, deprecatedOption); + emitDeprecationWarning(msg); + if (this && this.getLogger) { + const logger = this.getLogger(); + if (logger) { + logger.warn(msg); + } + } + } + }); + + return fn.apply(this, arguments); + } + + // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 + // The wrapper will keep the same prototype as fn to maintain prototype chain + Object.setPrototypeOf(deprecated, fn); + if (fn.prototype) { + // Setting this (rather than using Object.setPrototype, as above) ensures + // that calling the unwrapped constructor gives an instanceof the wrapped + // constructor. + deprecated.prototype = fn.prototype; + } + + return deprecated; +} + +const SUPPORTS = {}; +// Test asyncIterator support +try { + __webpack_require__(1749); + SUPPORTS.ASYNC_ITERATOR = true; +} catch (e) { + SUPPORTS.ASYNC_ITERATOR = false; +} + +class MongoDBNamespace { + constructor(db, collection) { + this.db = db; + this.collection = collection; + } + + toString() { + return this.collection ? `${this.db}.${this.collection}` : this.db; + } + + withCollection(collection) { + return new MongoDBNamespace(this.db, collection); + } + + static fromString(namespace) { + if (!namespace) { + throw new Error(`Cannot parse namespace from "${namespace}"`); + } + + const index = namespace.indexOf('.'); + return new MongoDBNamespace(namespace.substring(0, index), namespace.substring(index + 1)); + } +} + +function* makeCounter(seed) { + let count = seed || 0; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } +} + +/** + * Helper function for either accepting a callback, or returning a promise + * + * @param {Object} parent an instance of parent with promiseLibrary. + * @param {object} parent.s an object containing promiseLibrary. + * @param {function} parent.s.promiseLibrary an object containing promiseLibrary. + * @param {[Function]} callback an optional callback. + * @param {Function} fn A function that takes a callback + * @returns {Promise|void} Returns nothing if a callback is supplied, else returns a Promise. + */ +function maybePromise(parent, callback, fn) { + const PromiseLibrary = (parent && parent.s && parent.s.promiseLibrary) || Promise; + + let result; + if (typeof callback !== 'function') { + result = new PromiseLibrary((resolve, reject) => { + callback = (err, res) => { + if (err) return reject(err); + resolve(res); + }; + }); + } + + fn(function(err, res) { + if (err != null) { + try { + callback(err); + } catch (error) { + return process.nextTick(() => { + throw error; + }); + } + return; + } + + callback(err, res); + }); + + return result; +} + +function now() { + const hrtime = process.hrtime(); + return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1000000); +} + +function calculateDurationInMs(started) { + if (typeof started !== 'number') { + throw TypeError('numeric value required to calculate duration'); + } + + const elapsed = now() - started; + return elapsed < 0 ? 0 : elapsed; +} + +/** + * Creates an interval timer which is able to be woken up sooner than + * the interval. The timer will also debounce multiple calls to wake + * ensuring that the function is only ever called once within a minimum + * interval window. + * + * @param {function} fn An async function to run on an interval, must accept a `callback` as its only parameter + * @param {object} [options] Optional settings + * @param {number} [options.interval] The interval at which to run the provided function + * @param {number} [options.minInterval] The minimum time which must pass between invocations of the provided function + * @param {boolean} [options.immediate] Execute the function immediately when the interval is started + */ +function makeInterruptableAsyncInterval(fn, options) { + let timerId; + let lastCallTime; + let lastWakeTime; + let stopped = false; + + options = options || {}; + const interval = options.interval || 1000; + const minInterval = options.minInterval || 500; + const immediate = typeof options.immediate === 'boolean' ? options.immediate : false; + + function wake() { + const currentTime = now(); + const timeSinceLastWake = currentTime - lastWakeTime; + const timeSinceLastCall = currentTime - lastCallTime; + const timeUntilNextCall = Math.max(interval - timeSinceLastCall, 0); + lastWakeTime = currentTime; + + // For the streaming protocol: there is nothing obviously stopping this + // interval from being woken up again while we are waiting "infinitely" + // for `fn` to be called again`. Since the function effectively + // never completes, the `timeUntilNextCall` will continue to grow + // negatively unbounded, so it will never trigger a reschedule here. + + // debounce multiple calls to wake within the `minInterval` + if (timeSinceLastWake < minInterval) { + return; + } + + // reschedule a call as soon as possible, ensuring the call never happens + // faster than the `minInterval` + if (timeUntilNextCall > minInterval) { + reschedule(minInterval); + } + } + + function stop() { + stopped = true; + if (timerId) { + clearTimeout(timerId); + timerId = null; + } + + lastCallTime = 0; + lastWakeTime = 0; + } + + function reschedule(ms) { + if (stopped) return; + clearTimeout(timerId); + timerId = setTimeout(executeAndReschedule, ms || interval); + } + + function executeAndReschedule() { + lastWakeTime = 0; + lastCallTime = now(); + + fn(err => { + if (err) throw err; + reschedule(interval); + }); + } + + if (immediate) { + executeAndReschedule(); + } else { + lastCallTime = now(); + reschedule(); + } + + return { wake, stop }; +} + +function hasAtomicOperators(doc) { + if (Array.isArray(doc)) { + return doc.reduce((err, u) => err || hasAtomicOperators(u), null); + } + + const keys = Object.keys(doc); + return keys.length > 0 && keys[0][0] === '$'; +} + +module.exports = { + filterOptions, + mergeOptions, + translateOptions, + shallowClone, + getSingleProperty, + checkCollectionName, + toError, + formattedOrderClause, + parseIndexOptions, + normalizeHintField, + handleCallback, + decorateCommand, + isObject, + debugOptions, + MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1, + mergeOptionsAndWriteConcern, + executeLegacyOperation, + applyRetryableWrites, + applyWriteConcern, + isPromiseLike, + decorateWithCollation, + decorateWithReadConcern, + deprecateOptions, + SUPPORTS, + MongoDBNamespace, + emitDeprecationWarning, + makeCounter, + maybePromise, + now, + calculateDurationInMs, + makeInterruptableAsyncInterval, + hasAtomicOperators +}; + + +/***/ }), + +/***/ 2481: +/***/ ((module) => { + +"use strict"; + + +const kWriteConcernKeys = new Set(['w', 'wtimeout', 'j', 'fsync']); + +/** + * The **WriteConcern** class is a class that represents a MongoDB WriteConcern. + * @class + * @property {(number|string)} w The write concern + * @property {number} wtimeout The write concern timeout + * @property {boolean} j The journal write concern + * @property {boolean} fsync The file sync write concern + * @see https://docs.mongodb.com/manual/reference/write-concern/index.html + */ +class WriteConcern { + /** + * Constructs a WriteConcern from the write concern properties. + * @param {(number|string)} [w] The write concern + * @param {number} [wtimeout] The write concern timeout + * @param {boolean} [j] The journal write concern + * @param {boolean} [fsync] The file sync write concern + */ + constructor(w, wtimeout, j, fsync) { + if (w != null) { + this.w = w; + } + if (wtimeout != null) { + this.wtimeout = wtimeout; + } + if (j != null) { + this.j = j; + } + if (fsync != null) { + this.fsync = fsync; + } + } + + /** + * Construct a WriteConcern given an options object. + * + * @param {object} options The options object from which to extract the write concern. + * @return {WriteConcern} + */ + static fromOptions(options) { + if ( + options == null || + (options.writeConcern == null && + options.w == null && + options.wtimeout == null && + options.j == null && + options.fsync == null) + ) { + return; + } + + if (options.writeConcern) { + if (typeof options.writeConcern === 'string') { + return new WriteConcern(options.writeConcern); + } + + if (!Object.keys(options.writeConcern).some(key => kWriteConcernKeys.has(key))) { + return; + } + + return new WriteConcern( + options.writeConcern.w, + options.writeConcern.wtimeout, + options.writeConcern.j, + options.writeConcern.fsync + ); + } + + return new WriteConcern(options.w, options.wtimeout, options.j, options.fsync); + } +} + +module.exports = WriteConcern; + + +/***/ }), + +/***/ 467: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(__webpack_require__(2413)); +var http = _interopDefault(__webpack_require__(8605)); +var Url = _interopDefault(__webpack_require__(8835)); +var https = _interopDefault(__webpack_require__(7211)); +var zlib = _interopDefault(__webpack_require__(8761)); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = __webpack_require__(2877).convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parse_url(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parse_url(`${input}`); + } + input = {}; + } else { + parsedURL = parse_url(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; +const resolve_url = Url.resolve; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + const locationURL = location === null ? null : resolve_url(request.url, location); + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; + + +/***/ }), + +/***/ 1223: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var wrappy = __webpack_require__(2940) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +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 + }) +}) + +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 +} + +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 +} + + +/***/ }), + +/***/ 7684: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const pTry = __webpack_require__(746); + +const pLimit = concurrency => { + if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { + return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up')); + } + + const queue = []; + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.length > 0) { + queue.shift()(); + } + }; + + const run = (fn, resolve, ...args) => { + activeCount++; + + const result = pTry(fn, ...args); + + resolve(result); + + result.then(next, next); + }; + + const enqueue = (fn, resolve, ...args) => { + if (activeCount < concurrency) { + run(fn, resolve, ...args); + } else { + queue.push(run.bind(null, fn, resolve, ...args)); + } + }; + + const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args)); + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.length + }, + clearQueue: { + value: () => { + queue.length = 0; + } + } + }); + + return generator; +}; + +module.exports = pLimit; +module.exports.default = pLimit; + + +/***/ }), + +/***/ 746: +/***/ ((module) => { + +"use strict"; + + +const pTry = (fn, ...arguments_) => new Promise(resolve => { + resolve(fn(...arguments_)); +}); + +module.exports = pTry; +// TODO [$5f5fbe42fcabad09c1c241ba]: remove this in the next major version +module.exports.default = pTry; + + +/***/ }), + +/***/ 1691: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const chalk = __webpack_require__(6857) +const jmespath = __webpack_require__(7783) +const colors = __webpack_require__(1297) +const { ERROR_LIKE_KEYS, MESSAGE_KEY, TIMESTAMP_KEY } = __webpack_require__(2186) +const { + isObject, + prettifyErrorLog, + prettifyLevel, + prettifyMessage, + prettifyMetadata, + prettifyObject, + prettifyTime +} = __webpack_require__(4694) + +const bourne = __webpack_require__(7174) +const jsonParser = input => { + try { + return { value: bourne.parse(input, { protoAction: 'remove' }) } + } catch (err) { + return { err } + } +} + +const defaultOptions = { + colorize: chalk.supportsColor, + crlf: false, + errorLikeObjectKeys: ERROR_LIKE_KEYS, + errorProps: '', + levelFirst: false, + messageKey: MESSAGE_KEY, + messageFormat: false, + timestampKey: TIMESTAMP_KEY, + translateTime: false, + useMetadata: false, + outputStream: process.stdout, + customPrettifiers: {} +} + +module.exports = function prettyFactory (options) { + const opts = Object.assign({}, defaultOptions, options) + const EOL = opts.crlf ? '\r\n' : '\n' + const IDENT = ' ' + const messageKey = opts.messageKey + const levelKey = opts.levelKey + const messageFormat = opts.messageFormat + const timestampKey = opts.timestampKey + const errorLikeObjectKeys = opts.errorLikeObjectKeys + const errorProps = opts.errorProps.split(',') + const customPrettifiers = opts.customPrettifiers + const ignoreKeys = opts.ignore ? new Set(opts.ignore.split(',')) : undefined + + const colorizer = colors(opts.colorize) + const search = opts.search + + return pretty + + function pretty (inputData) { + let log + if (!isObject(inputData)) { + const parsed = jsonParser(inputData) + if (parsed.err || !isObject(parsed.value)) { + // pass through + return inputData + EOL + } + log = parsed.value + } else { + log = inputData + } + + // Short-circuit for spec allowed primitive values. + if ([null, true, false].includes(log) || Number.isFinite(log)) { + return `${log}\n` + } + + if (search && !jmespath.search(log, search)) { + return + } + + const prettifiedMessage = prettifyMessage({ log, messageKey, colorizer, messageFormat }) + + if (ignoreKeys) { + log = Object.keys(log) + .filter(key => !ignoreKeys.has(key)) + .reduce((res, key) => { + res[key] = log[key] + return res + }, {}) + } + + const prettifiedLevel = prettifyLevel({ log, colorizer, levelKey }) + const prettifiedMetadata = prettifyMetadata({ log }) + const prettifiedTime = prettifyTime({ log, translateFormat: opts.translateTime, timestampKey }) + + let line = '' + if (opts.levelFirst && prettifiedLevel) { + line = `${prettifiedLevel}` + } + + if (prettifiedTime && line === '') { + line = `${prettifiedTime}` + } else if (prettifiedTime) { + line = `${line} ${prettifiedTime}` + } + + if (!opts.levelFirst && prettifiedLevel) { + if (line.length > 0) { + line = `${line} ${prettifiedLevel}` + } else { + line = prettifiedLevel + } + } + + if (prettifiedMetadata) { + line = `${line} ${prettifiedMetadata}:` + } + + if (line.endsWith(':') === false && line !== '') { + line += ':' + } + + if (prettifiedMessage) { + line = `${line} ${prettifiedMessage}` + } + + if (line.length > 0) { + line += EOL + } + + if (log.type === 'Error' && log.stack) { + const prettifiedErrorLog = prettifyErrorLog({ + log, + errorLikeKeys: errorLikeObjectKeys, + errorProperties: errorProps, + ident: IDENT, + eol: EOL + }) + line += prettifiedErrorLog + } else { + const skipKeys = [messageKey, levelKey].filter(key => typeof log[key] === 'string') + const prettifiedObject = prettifyObject({ + input: log, + skipKeys, + customPrettifiers, + errorLikeKeys: errorLikeObjectKeys, + eol: EOL, + ident: IDENT + }) + line += prettifiedObject + } + + return line + } +} + + +/***/ }), + +/***/ 1297: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const { LEVELS, LEVEL_NAMES } = __webpack_require__(2186) + +const nocolor = input => input +const plain = { + default: nocolor, + 60: nocolor, + 50: nocolor, + 40: nocolor, + 30: nocolor, + 20: nocolor, + 10: nocolor, + message: nocolor +} + +const chalk = __webpack_require__(6857) +const ctx = new chalk.constructor({ enabled: true, level: 3 }) +const colored = { + default: ctx.white, + 60: ctx.bgRed, + 50: ctx.red, + 40: ctx.yellow, + 30: ctx.green, + 20: ctx.blue, + 10: ctx.grey, + message: ctx.cyan +} + +function colorizeLevel (level, colorizer) { + if (Number.isInteger(+level)) { + return Object.prototype.hasOwnProperty.call(LEVELS, level) + ? colorizer[level](LEVELS[level]) + : colorizer.default(LEVELS.default) + } + const levelNum = LEVEL_NAMES[level.toLowerCase()] || 'default' + return colorizer[levelNum](LEVELS[levelNum]) +} + +function plainColorizer (level) { + return colorizeLevel(level, plain) +} +plainColorizer.message = plain.message + +function coloredColorizer (level) { + return colorizeLevel(level, colored) +} +coloredColorizer.message = colored.message + +/** + * Factory function get a function to colorized levels. The returned function + * also includes a `.message(str)` method to colorize strings. + * + * @param {bool} [useColors=false] When `true` a function that applies standard + * terminal colors is returned. + * + * @returns {function} `function (level) {}` has a `.message(str)` method to + * apply colorization to a string. The core function accepts either an integer + * `level` or a `string` level. The integer level will map to a known level + * string or to `USERLVL` if not known. The string `level` will map to the same + * colors as the integer `level` and will also default to `USERLVL` if the given + * string is not a recognized level name. + */ +module.exports = function getColorizer (useColors = false) { + return useColors ? coloredColorizer : plainColorizer +} + + +/***/ }), + +/***/ 2186: +/***/ ((module) => { + +"use strict"; + + +module.exports = { + DATE_FORMAT: 'yyyy-mm-dd HH:MM:ss.l o', + + ERROR_LIKE_KEYS: ['err', 'error'], + + MESSAGE_KEY: 'msg', + + LEVEL_KEY: 'level', + + TIMESTAMP_KEY: 'time', + + LEVELS: { + default: 'USERLVL', + 60: 'FATAL', + 50: 'ERROR', + 40: 'WARN ', + 30: 'INFO ', + 20: 'DEBUG', + 10: 'TRACE' + }, + + LEVEL_NAMES: { + fatal: 60, + error: 50, + warn: 40, + info: 30, + debug: 20, + trace: 10 + }, + + // Object keys that probably came from a logger like Pino or Bunyan. + LOGGER_KEYS: [ + 'pid', + 'hostname', + 'name', + 'level', + 'time', + 'timestamp', + 'v', + 'caller' + ] +} + + +/***/ }), + +/***/ 4694: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const dateformat = __webpack_require__(1512) +const stringifySafe = __webpack_require__(7676) +const defaultColorizer = __webpack_require__(1297)() +const { + DATE_FORMAT, + ERROR_LIKE_KEYS, + MESSAGE_KEY, + LEVEL_KEY, + TIMESTAMP_KEY, + LOGGER_KEYS +} = __webpack_require__(2186) + +module.exports = { + isObject, + prettifyErrorLog, + prettifyLevel, + prettifyMessage, + prettifyMetadata, + prettifyObject, + prettifyTime +} + +module.exports.internals = { + formatTime, + joinLinesWithIndentation +} + +/** + * Converts a given `epoch` to a desired display format. + * + * @param {number|string} epoch The time to convert. May be any value that is + * valid for `new Date()`. + * @param {bool|string} [translateTime=false] When `false`, the given `epoch` + * will simply be returned. When `true`, the given `epoch` will be converted + * to a string at UTC using the `DATE_FORMAT` constant. If `translateTime` is + * a string, the following rules are available: + * + * - ``: The string is a literal format string. This format + * string will be used to interpret the `epoch` and return a display string + * at UTC. + * - `SYS:STANDARD`: The returned display string will follow the `DATE_FORMAT` + * constant at the system's local timezone. + * - `SYS:`: The returned display string will follow the given + * `` at the system's local timezone. + * - `UTC:`: The returned display string will follow the given + * `` at UTC. + * + * @returns {number|string} The formatted time. + */ +function formatTime (epoch, translateTime = false) { + if (translateTime === false) { + return epoch + } + + const instant = new Date(epoch) + if (translateTime === true) { + return dateformat(instant, 'UTC:' + DATE_FORMAT) + } + + const upperFormat = translateTime.toUpperCase() + if (upperFormat === 'SYS:STANDARD') { + return dateformat(instant, DATE_FORMAT) + } + + const prefix = upperFormat.substr(0, 4) + if (prefix === 'SYS:' || prefix === 'UTC:') { + if (prefix === 'UTC:') { + return dateformat(instant, translateTime) + } + return dateformat(instant, translateTime.slice(4)) + } + + return dateformat(instant, `UTC:${translateTime}`) +} + +function isObject (input) { + return Object.prototype.toString.apply(input) === '[object Object]' +} + +/** + * Given a string with line separators, either `\r\n` or `\n`, add indentation + * to all lines subsequent to the first line and rejoin the lines using an + * end of line sequence. + * + * @param {object} input + * @param {string} input.input The string to split and reformat. + * @param {string} [input.ident] The indentation string. Default: ` ` (4 spaces). + * @param {string} [input.eol] The end of line sequence to use when rejoining + * the lines. Default: `'\n'`. + * + * @returns {string} A string with lines subsequent to the first indented + * with the given indentation sequence. + */ +function joinLinesWithIndentation ({ input, ident = ' ', eol = '\n' }) { + const lines = input.split(/\r?\n/) + for (var i = 1; i < lines.length; i += 1) { + lines[i] = ident + lines[i] + } + return lines.join(eol) +} + +/** + * Given a log object that has a `type: 'Error'` key, prettify the object and + * return the result. In other + * + * @param {object} input + * @param {object} input.log The error log to prettify. + * @param {string} [input.messageKey] The name of the key that contains a + * general log message. This is not the error's message property but the logger + * messsage property. Default: `MESSAGE_KEY` constant. + * @param {string} [input.ident] The sequence to use for indentation. Default: `' '`. + * @param {string} [input.eol] The sequence to use for EOL. Default: `'\n'`. + * @param {string[]} [input.errorLikeKeys] A set of keys that should be considered + * to have error objects as values. Default: `ERROR_LIKE_KEYS` constant. + * @param {string[]} [input.errorProperties] A set of specific error object + * properties, that are not the value of `messageKey`, `type`, or `stack`, to + * include in the prettified result. The first entry in the list may be `'*'` + * to indicate that all sibiling properties should be prettified. Default: `[]`. + * + * @returns {string} A sring that represents the prettified error log. + */ +function prettifyErrorLog ({ + log, + messageKey = MESSAGE_KEY, + ident = ' ', + eol = '\n', + errorLikeKeys = ERROR_LIKE_KEYS, + errorProperties = [] +}) { + const stack = log.stack + const joinedLines = joinLinesWithIndentation({ input: stack, ident, eol }) + let result = `${ident}${joinedLines}${eol}` + + if (errorProperties.length > 0) { + const excludeProperties = LOGGER_KEYS.concat(messageKey, 'type', 'stack') + let propertiesToPrint + if (errorProperties[0] === '*') { + // Print all sibling properties except for the standard exclusions. + propertiesToPrint = Object.keys(log).filter(k => excludeProperties.includes(k) === false) + } else { + // Print only sepcified properties unless the property is a standard exclusion. + propertiesToPrint = errorProperties.filter(k => excludeProperties.includes(k) === false) + } + + for (var i = 0; i < propertiesToPrint.length; i += 1) { + const key = propertiesToPrint[i] + if (key in log === false) continue + if (isObject(log[key])) { + // The nested object may have "logger" type keys but since they are not + // at the root level of the object being processed, we want to print them. + // Thus, we invoke with `excludeLoggerKeys: false`. + const prettifiedObject = prettifyObject({ input: log[key], errorLikeKeys, excludeLoggerKeys: false, eol, ident }) + result = `${result}${key}: {${eol}${prettifiedObject}}${eol}` + continue + } + result = `${result}${key}: ${log[key]}${eol}` + } + } + + return result +} + +/** + * Checks if the passed in log has a `level` value and returns a prettified + * string for that level if so. + * + * @param {object} input + * @param {object} input.log The log object. + * @param {function} [input.colorizer] A colorizer function that accepts a level + * value and returns a colorized string. Default: a no-op colorizer. + * @param {string} [levelKey='level'] The key to find the level under. + * + * @returns {undefined|string} If `log` does not have a `level` property then + * `undefined` will be returned. Otherwise, a string from the specified + * `colorizer` is returned. + */ +function prettifyLevel ({ log, colorizer = defaultColorizer, levelKey = LEVEL_KEY }) { + if (levelKey in log === false) return undefined + return colorizer(log[levelKey]) +} + +/** + * Prettifies a message string if the given `log` has a message property. + * + * @param {object} input + * @param {object} input.log The log object with the message to colorize. + * @param {string} [input.messageKey='msg'] The property of the `log` that is the + * message to be prettified. + * @param {string} [input.messageFormat=undefined] A format string that defines how the + * logged message should be formatted, e.g. `'{level} - {pid}'`. + * @param {function} [input.colorizer] A colorizer function that has a + * `.message(str)` method attached to it. This function should return a colorized + * string which will be the "prettified" message. Default: a no-op colorizer. + * + * @returns {undefined|string} If the message key is not found, or the message + * key is not a string, then `undefined` will be returned. Otherwise, a string + * that is the prettified message. + */ +function prettifyMessage ({ log, messageFormat, messageKey = MESSAGE_KEY, colorizer = defaultColorizer }) { + if (messageFormat) { + const message = String(messageFormat).replace(/{([^{}]+)}/g, function (match, p1) { + if (p1 && log[p1]) { + return log[p1] + } + return '' + }) + return colorizer.message(message) + } + if (messageKey in log === false) return undefined + if (typeof log[messageKey] !== 'string') return undefined + return colorizer.message(log[messageKey]) +} + +/** + * Prettifies metadata that is usually present in a Pino log line. It looks for + * fields `name`, `pid`, `hostname`, and `caller` and returns a formatted string using + * the fields it finds. + * + * @param {object} input + * @param {object} input.log The log that may or may not contain metadata to + * be prettified. + * + * @returns {undefined|string} If no metadata is found then `undefined` is + * returned. Otherwise, a string of prettified metadata is returned. + */ +function prettifyMetadata ({ log }) { + let line = '' + + if (log.name || log.pid || log.hostname) { + line += '(' + + if (log.name) { + line += log.name + } + + if (log.name && log.pid) { + line += '/' + log.pid + } else if (log.pid) { + line += log.pid + } + + if (log.hostname) { + // If `pid` and `name` were in the ignore keys list then we don't need + // the leading space. + line += `${line === '(' ? 'on' : ' on'} ${log.hostname}` + } + + line += ')' + } + + if (log.caller) { + line += `${line === '' ? '' : ' '}<${log.caller}>` + } + + if (line === '') { + return undefined + } else { + return line + } +} + +/** + * Prettifies a standard object. Special care is taken when processing the object + * to handle child objects that are attached to keys known to contain error + * objects. + * + * @param {object} input + * @param {object} input.input The object to prettify. + * @param {string} [input.ident] The identation sequence to use. Default: `' '`. + * @param {string} [input.eol] The EOL sequence to use. Default: `'\n'`. + * @param {string[]} [input.skipKeys] A set of object keys to exclude from the + * prettified result. Default: `[]`. + * @param {Object} [input.customPrettifiers] Dictionary of + * custom prettifiers. Default: `{}`. + * @param {string[]} [input.errorLikeKeys] A set of object keys that contain + * error objects. Default: `ERROR_LIKE_KEYS` constant. + * @param {boolean} [input.excludeLoggerKeys] Indicates if known logger specific + * keys should be excluded from prettification. Default: `true`. + * + * @returns {string} The prettified string. This can be as little as `''` if + * there was nothing to prettify. + */ +function prettifyObject ({ + input, + ident = ' ', + eol = '\n', + skipKeys = [], + customPrettifiers = {}, + errorLikeKeys = ERROR_LIKE_KEYS, + excludeLoggerKeys = true +}) { + const objectKeys = Object.keys(input) + const keysToIgnore = [].concat(skipKeys) + + if (excludeLoggerKeys === true) Array.prototype.push.apply(keysToIgnore, LOGGER_KEYS) + + let result = '' + + const keysToIterate = objectKeys.filter(k => keysToIgnore.includes(k) === false) + for (var i = 0; i < objectKeys.length; i += 1) { + const keyName = keysToIterate[i] + const keyValue = input[keyName] + + if (keyValue === undefined) continue + + let lines + if (typeof customPrettifiers[keyName] === 'function') { + lines = customPrettifiers[keyName](keyValue, keyName, input) + } else { + lines = stringifySafe(keyValue, null, 2) + } + + if (lines === undefined) continue + const joinedLines = joinLinesWithIndentation({ input: lines, ident, eol }) + + if (errorLikeKeys.includes(keyName) === true) { + const splitLines = `${ident}${keyName}: ${joinedLines}${eol}`.split(eol) + for (var j = 0; j < splitLines.length; j += 1) { + if (j !== 0) result += eol + + const line = splitLines[j] + if (/^\s*"stack"/.test(line)) { + const matches = /^(\s*"stack":)\s*(".*"),?$/.exec(line) + if (matches && matches.length === 3) { + const indentSize = /^\s*/.exec(line)[0].length + 4 + const indentation = ' '.repeat(indentSize) + const stackMessage = matches[2] + result += matches[1] + eol + indentation + JSON.parse(stackMessage).replace(/\n/g, eol + indentation) + } + } else { + result += line + } + } + } else { + result += `${ident}${keyName}: ${joinedLines}${eol}` + } + } + + return result +} + +/** + * Prettifies a timestamp if the given `log` has either `time`, `timestamp` or custom specified timestamp + * property. + * + * @param {object} input + * @param {object} input.log The log object with the timestamp to be prettified. + * @param {string} [input.timestampKey='time'] The log property that should be used to resolve timestamp value + * @param {bool|string} [input.translateFormat=undefined] When `true` the + * timestamp will be prettified into a string at UTC using the default + * `DATE_FORMAT`. If a string, then `translateFormat` will be used as the format + * string to determine the output; see the `formatTime` function for details. + * + * @returns {undefined|string} If a timestamp property cannot be found then + * `undefined` is returned. Otherwise, the prettified time is returned as a + * string. + */ +function prettifyTime ({ log, timestampKey = TIMESTAMP_KEY, translateFormat = undefined }) { + let time = null + + if (timestampKey in log) { + time = log[timestampKey] + } else if ('timestamp' in log) { + time = log.timestamp + } + + if (time === null) return undefined + if (translateFormat) { + return '[' + formatTime(time, translateFormat) + ']' + } + + return `[${time}]` +} + + +/***/ }), + +/***/ 5645: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* module decorator */ module = __webpack_require__.nmd(module); + +const colorConvert = __webpack_require__(5452); + +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + 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], + + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); + + +/***/ }), + +/***/ 6857: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const escapeStringRegexp = __webpack_require__(8691); +const ansiStyles = __webpack_require__(5645); +const stdoutColor = __webpack_require__(5103).stdout; + +const template = __webpack_require__(4773); + +const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); + +const styles = Object.create(null); + +function applyOptions(obj, options) { + options = options || {}; + + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; +} + +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = Chalk; + + return chalk.template; + } + + applyOptions(this, options); +} + +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; +} + +for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; +} + +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } +}; + +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); +for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +const proto = Object.defineProperties(() => {}, styles); + +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + + const self = this; + + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; +} + +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + + // 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. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // 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; + + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; + + return str; +} + +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return template(chalk, parts.join('')); +} + +Object.defineProperties(Chalk.prototype, styles); + +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript + + +/***/ }), + +/***/ 4773: +/***/ ((module) => { + +"use strict"; + +const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; + +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); + +function unescape(c) { + if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES.get(c) || c; +} + +function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; +} + +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; +} + +function buildStyle(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; +} + +module.exports = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; + + // eslint-disable-next-line max-params + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); + } + + return chunks.join(''); +}; + + +/***/ }), + +/***/ 5701: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* MIT license */ +var cssKeywords = __webpack_require__(4222); + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +var reverseKeywords = {}; +for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } +} + +var convert = module.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +// hide .channels and .labels properties +for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } +} + +convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; +}; + +convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +/** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ +function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); +} + +convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; +}; + +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; + +convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; +}; + +convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; +}; + +convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; + +convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; +}; + +convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; +}; + +convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + + return [l, c, h]; +}; + +convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + + return [l, a, b]; +}; + +convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; +}; + +convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; + +convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; +}; + +convert.ansi16.rgb = function (args) { + var color = args % 10; + + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; +}; + +convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; + + return [r, g, b]; +}; + +convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; + + return [r, g, b]; +}; + +convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = (max - min); + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; +}; + +convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; +}; + +convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; + +convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = (h % 1) * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; + +convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; +}; + +convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; +}; + +convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; + +convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; +}; + +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; + +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; + +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; +}; + +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; + + +/***/ }), + +/***/ 5452: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var conversions = __webpack_require__(5701); +var route = __webpack_require__(3629); + +var convert = {}; + +var models = Object.keys(conversions); + +function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); + + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models.forEach(function (fromModel) { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + var routes = route(fromModel); + var routeModels = Object.keys(routes); + + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); + +module.exports = convert; + + +/***/ }), + +/***/ 3629: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var conversions = __webpack_require__(5701); + +/* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +module.exports = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; + + + +/***/ }), + +/***/ 4222: +/***/ ((module) => { + +"use strict"; + + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; + + +/***/ }), + +/***/ 5103: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const os = __webpack_require__(2087); +const hasFlag = __webpack_require__(1621); + +const env = process.env; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; + + +/***/ }), + +/***/ 2571: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var errSerializer = __webpack_require__(6522) +var reqSerializers = __webpack_require__(5492) +var resSerializers = __webpack_require__(9048) + +module.exports = { + err: errSerializer, + mapHttpRequest: reqSerializers.mapHttpRequest, + mapHttpResponse: resSerializers.mapHttpResponse, + req: reqSerializers.reqSerializer, + res: resSerializers.resSerializer, + + wrapErrorSerializer: function wrapErrorSerializer (customSerializer) { + if (customSerializer === errSerializer) return customSerializer + return function wrapErrSerializer (err) { + return customSerializer(errSerializer(err)) + } + }, + + wrapRequestSerializer: function wrapRequestSerializer (customSerializer) { + if (customSerializer === reqSerializers.reqSerializer) return customSerializer + return function wrappedReqSerializer (req) { + return customSerializer(reqSerializers.reqSerializer(req)) + } + }, + + wrapResponseSerializer: function wrapResponseSerializer (customSerializer) { + if (customSerializer === resSerializers.resSerializer) return customSerializer + return function wrappedResSerializer (res) { + return customSerializer(resSerializers.resSerializer(res)) + } + } +} + + +/***/ }), + +/***/ 6522: +/***/ ((module) => { + +"use strict"; + + +module.exports = errSerializer + +const seen = Symbol('circular-ref-tag') +const rawSymbol = Symbol('pino-raw-err-ref') +const pinoErrProto = Object.create({}, { + type: { + enumerable: true, + writable: true, + value: undefined + }, + message: { + enumerable: true, + writable: true, + value: undefined + }, + stack: { + enumerable: true, + writable: true, + value: undefined + }, + raw: { + enumerable: false, + get: function () { + return this[rawSymbol] + }, + set: function (val) { + this[rawSymbol] = val + } + } +}) +Object.defineProperty(pinoErrProto, rawSymbol, { + writable: true, + value: {} +}) + +function errSerializer (err) { + if (!(err instanceof Error)) { + return err + } + + err[seen] = undefined // tag to prevent re-looking at this + const _err = Object.create(pinoErrProto) + _err.type = err.constructor.name + _err.message = err.message + _err.stack = err.stack + for (const key in err) { + if (_err[key] === undefined) { + const val = err[key] + if (val instanceof Error) { + if (!val.hasOwnProperty(seen)) { + _err[key] = errSerializer(val) + } + } else { + _err[key] = val + } + } + } + + delete err[seen] // clean up tag in case err is serialized again later + _err.raw = err + return _err +} + + +/***/ }), + +/***/ 5492: +/***/ ((module) => { + +"use strict"; + + +module.exports = { + mapHttpRequest, + reqSerializer +} + +var rawSymbol = Symbol('pino-raw-req-ref') +var pinoReqProto = Object.create({}, { + id: { + enumerable: true, + writable: true, + value: '' + }, + method: { + enumerable: true, + writable: true, + value: '' + }, + url: { + enumerable: true, + writable: true, + value: '' + }, + headers: { + enumerable: true, + writable: true, + value: {} + }, + remoteAddress: { + enumerable: true, + writable: true, + value: '' + }, + remotePort: { + enumerable: true, + writable: true, + value: '' + }, + raw: { + enumerable: false, + get: function () { + return this[rawSymbol] + }, + set: function (val) { + this[rawSymbol] = val + } + } +}) +Object.defineProperty(pinoReqProto, rawSymbol, { + writable: true, + value: {} +}) + +function reqSerializer (req) { + // req.info is for hapi compat. + var connection = req.info || req.connection + const _req = Object.create(pinoReqProto) + _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined))) + _req.method = req.method + // req.originalUrl is for expressjs compat. + if (req.originalUrl) { + _req.url = req.originalUrl + } else { + // req.url.path is for hapi compat. + _req.url = req.path || (req.url ? (req.url.path || req.url) : undefined) + } + _req.headers = req.headers + _req.remoteAddress = connection && connection.remoteAddress + _req.remotePort = connection && connection.remotePort + // req.raw is for hapi compat/equivalence + _req.raw = req.raw || req + return _req +} + +function mapHttpRequest (req) { + return { + req: reqSerializer(req) + } +} + + +/***/ }), + +/***/ 9048: +/***/ ((module) => { + +"use strict"; + + +module.exports = { + mapHttpResponse, + resSerializer +} + +var rawSymbol = Symbol('pino-raw-res-ref') +var pinoResProto = Object.create({}, { + statusCode: { + enumerable: true, + writable: true, + value: 0 + }, + headers: { + enumerable: true, + writable: true, + value: '' + }, + raw: { + enumerable: false, + get: function () { + return this[rawSymbol] + }, + set: function (val) { + this[rawSymbol] = val + } + } +}) +Object.defineProperty(pinoResProto, rawSymbol, { + writable: true, + value: {} +}) + +function resSerializer (res) { + const _res = Object.create(pinoResProto) + _res.statusCode = res.statusCode + _res.headers = res.getHeaders ? res.getHeaders() : res._headers + _res.raw = res + return _res +} + +function mapHttpResponse (res) { + return { + res: resSerializer(res) + } +} + + +/***/ }), + +/***/ 591: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const flatstr = __webpack_require__(5298) +const { + lsCacheSym, + levelValSym, + useLevelLabelsSym, + levelKeySym, + useOnlyCustomLevelsSym, + streamSym +} = __webpack_require__(3957) +const { noop, genLog } = __webpack_require__(1521) + +const levels = { + trace: 10, + debug: 20, + info: 30, + warn: 40, + error: 50, + fatal: 60 +} +const logFatal = genLog(levels.fatal) +const levelMethods = { + fatal (...args) { + const stream = this[streamSym] + logFatal.call(this, ...args) + if (typeof stream.flushSync === 'function') { + try { + stream.flushSync() + } catch (e) { + // https://github.com/pinojs/pino/pull/740#discussion_r346788313 + } + } + }, + error: genLog(levels.error), + warn: genLog(levels.warn), + info: genLog(levels.info), + debug: genLog(levels.debug), + trace: genLog(levels.trace) +} + +const nums = Object.keys(levels).reduce((o, k) => { + o[levels[k]] = k + return o +}, {}) + +const initialLsCache = Object.keys(nums).reduce((o, k) => { + o[k] = flatstr('{"level":' + Number(k)) + return o +}, {}) + +function genLsCache (instance) { + const levelName = instance[levelKeySym] + instance[lsCacheSym] = Object.keys(instance.levels.labels).reduce((o, k) => { + o[k] = instance[useLevelLabelsSym] + ? `{"${levelName}":"${instance.levels.labels[k]}"` + : flatstr(`{"${levelName}":` + Number(k)) + return o + }, Object.assign({}, instance[lsCacheSym])) + return instance +} + +function isStandardLevel (level, useOnlyCustomLevels) { + if (useOnlyCustomLevels) { + return false + } + + switch (level) { + case 'fatal': + case 'error': + case 'warn': + case 'info': + case 'debug': + case 'trace': + return true + default: + return false + } +} + +function setLevel (level) { + const { labels, values } = this.levels + if (typeof level === 'number') { + if (labels[level] === undefined) throw Error('unknown level value' + level) + level = labels[level] + } + if (values[level] === undefined) throw Error('unknown level ' + level) + const preLevelVal = this[levelValSym] + const levelVal = this[levelValSym] = values[level] + const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym] + + for (var key in values) { + if (levelVal > values[key]) { + this[key] = noop + continue + } + this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key] : genLog(values[key]) + } + + this.emit( + 'level-change', + level, + levelVal, + labels[preLevelVal], + preLevelVal + ) +} + +function getLevel (level) { + const { levels, levelVal } = this + return levels.labels[levelVal] +} + +function isLevelEnabled (logLevel) { + const { values } = this.levels + const logLevelVal = values[logLevel] + return logLevelVal !== undefined && (logLevelVal >= this[levelValSym]) +} + +function mappings (customLevels = null, useOnlyCustomLevels = false) { + const customNums = customLevels ? Object.keys(customLevels).reduce((o, k) => { + o[customLevels[k]] = k + return o + }, {}) : null + + const labels = Object.assign( + Object.create(Object.prototype, { Infinity: { value: 'silent' } }), + useOnlyCustomLevels ? null : nums, + customNums + ) + const values = Object.assign( + Object.create(Object.prototype, { silent: { value: Infinity } }), + useOnlyCustomLevels ? null : levels, + customLevels + ) + return { labels, values } +} + +function assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) { + if (typeof defaultLevel === 'number') { + const values = [].concat( + Object.keys(customLevels || {}).map(key => customLevels[key]), + useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level), + Infinity + ) + if (!values.includes(defaultLevel)) { + throw Error(`default level:${defaultLevel} must be included in custom levels`) + } + return + } + + const labels = Object.assign( + Object.create(Object.prototype, { silent: { value: Infinity } }), + useOnlyCustomLevels ? null : levels, + customLevels + ) + if (!(defaultLevel in labels)) { + throw Error(`default level:${defaultLevel} must be included in custom levels`) + } +} + +function assertNoLevelCollisions (levels, customLevels) { + const { labels, values } = levels + for (const k in customLevels) { + if (k in values) { + throw Error('levels cannot be overridden') + } + if (customLevels[k] in labels) { + throw Error('pre-existing level values cannot be used for new levels') + } + } +} + +module.exports = { + initialLsCache, + genLsCache, + levelMethods, + getLevel, + setLevel, + isLevelEnabled, + mappings, + assertNoLevelCollisions, + assertDefaultLevelFound +} + + +/***/ }), + +/***/ 8578: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const { version } = __webpack_require__(8686) + +const LOG_VERSION = 1 + +module.exports = { version, LOG_VERSION } + + +/***/ }), + +/***/ 6899: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/* eslint no-prototype-builtins: 0 */ + +const { EventEmitter } = __webpack_require__(8614) +const SonicBoom = __webpack_require__(3460) +const flatstr = __webpack_require__(5298) +const { + lsCacheSym, + levelValSym, + setLevelSym, + getLevelSym, + chindingsSym, + mixinSym, + asJsonSym, + messageKeySym, + writeSym, + timeSym, + timeSliceIndexSym, + streamSym, + serializersSym, + useOnlyCustomLevelsSym, + needsMetadataGsym +} = __webpack_require__(3957) +const { + getLevel, + setLevel, + isLevelEnabled, + mappings, + initialLsCache, + genLsCache, + assertNoLevelCollisions +} = __webpack_require__(591) +const { + asChindings, + asJson +} = __webpack_require__(1521) +const { + version, + LOG_VERSION +} = __webpack_require__(8578) + +// note: use of class is satirical +// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127 +const constructor = class Pino {} +const prototype = { + constructor, + child, + bindings, + setBindings, + flush, + isLevelEnabled, + version, + get level () { return this[getLevelSym]() }, + set level (lvl) { return this[setLevelSym](lvl) }, + get levelVal () { return this[levelValSym] }, + set levelVal (n) { throw Error('levelVal is read-only') }, + [lsCacheSym]: initialLsCache, + [writeSym]: write, + [asJsonSym]: asJson, + [getLevelSym]: getLevel, + [setLevelSym]: setLevel, + LOG_VERSION +} + +Object.setPrototypeOf(prototype, EventEmitter.prototype) + +module.exports = prototype + +function child (bindings) { + const { level } = this + const serializers = this[serializersSym] + const chindings = asChindings(this, bindings) + const instance = Object.create(this) + if (bindings.hasOwnProperty('serializers') === true) { + instance[serializersSym] = Object.create(null) + + for (var k in serializers) { + instance[serializersSym][k] = serializers[k] + } + const parentSymbols = Object.getOwnPropertySymbols(serializers) + for (var i = 0; i < parentSymbols.length; i++) { + const ks = parentSymbols[i] + instance[serializersSym][ks] = serializers[ks] + } + + for (var bk in bindings.serializers) { + instance[serializersSym][bk] = bindings.serializers[bk] + } + const bindingsSymbols = Object.getOwnPropertySymbols(bindings.serializers) + for (var bi = 0; bi < bindingsSymbols.length; bi++) { + const bks = bindingsSymbols[bi] + instance[serializersSym][bks] = bindings.serializers[bks] + } + } else instance[serializersSym] = serializers + if (bindings.hasOwnProperty('customLevels') === true) { + assertNoLevelCollisions(this.levels, bindings.customLevels) + instance.levels = mappings(bindings.customLevels, instance[useOnlyCustomLevelsSym]) + genLsCache(instance) + } + instance[chindingsSym] = chindings + const childLevel = bindings.level || level + instance[setLevelSym](childLevel) + + return instance +} + +function bindings () { + const chindings = this[chindingsSym] + var chindingsJson = `{${chindings.substr(1)}}` // at least contains ,"pid":7068,"hostname":"myMac" + var bindingsFromJson = JSON.parse(chindingsJson) + delete bindingsFromJson.pid + delete bindingsFromJson.hostname + return bindingsFromJson +} + +function setBindings (newBindings) { + const chindings = asChindings(this, newBindings) + this[chindingsSym] = chindings +} + +function write (_obj, msg, num) { + const t = this[timeSym]() + const messageKey = this[messageKeySym] + const mixin = this[mixinSym] + const objError = _obj instanceof Error + var obj + + if (_obj === undefined || _obj === null) { + obj = mixin ? mixin() : {} + obj[messageKey] = msg + } else { + obj = Object.assign(mixin ? mixin() : {}, _obj) + if (msg) { + obj[messageKey] = msg + } else if (objError) { + obj[messageKey] = _obj.message + } + + if (objError) { + obj.stack = _obj.stack + if (!obj.type) { + obj.type = 'Error' + } + } + } + + const s = this[asJsonSym](obj, num, t) + + const stream = this[streamSym] + if (stream[needsMetadataGsym] === true) { + stream.lastLevel = num + // TODO remove in the next major release, + // it is not needed anymore + stream.lastMsg = msg + stream.lastObj = obj + stream.lastTime = t.slice(this[timeSliceIndexSym]) + stream.lastLogger = this // for child loggers + } + if (stream instanceof SonicBoom) stream.write(s) + else stream.write(flatstr(s)) +} + +function flush () { + const stream = this[streamSym] + if ('flush' in stream) stream.flush() +} + + +/***/ }), + +/***/ 4219: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const fastRedact = __webpack_require__(4826) +const { redactFmtSym, wildcardFirstSym } = __webpack_require__(3957) +const { rx, validator } = fastRedact + +const validate = validator({ + ERR_PATHS_MUST_BE_STRINGS: () => 'pino – redacted paths must be strings', + ERR_INVALID_PATH: (s) => `pino – redact paths array contains an invalid path (${s})` +}) + +const CENSOR = '[Redacted]' +const strict = false // TODO should this be configurable? + +function redaction (opts, serialize) { + const { paths, censor } = handle(opts) + + const shape = paths.reduce((o, str) => { + rx.lastIndex = 0 + const first = rx.exec(str) + const next = rx.exec(str) + + // ns is the top-level path segment, brackets + quoting removed. + let ns = first[1] !== undefined + ? first[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/, '$1') + : first[0] + + if (ns === '*') { + ns = wildcardFirstSym + } + + // top level key: + if (next === null) { + o[ns] = null + return o + } + + // path with at least two segments: + // if ns is already redacted at the top level, ignore lower level redactions + if (o[ns] === null) { + return o + } + + const { index } = next + const nextPath = `${str.substr(index, str.length - 1)}` + + o[ns] = o[ns] || [] + + // shape is a mix of paths beginning with literal values and wildcard + // paths [ "a.b.c", "*.b.z" ] should reduce to a shape of + // { "a": [ "b.c", "b.z" ], *: [ "b.z" ] } + // note: "b.z" is in both "a" and * arrays because "a" matches the wildcard. + // (* entry has wildcardFirstSym as key) + if (ns !== wildcardFirstSym && o[ns].length === 0) { + // first time ns's get all '*' redactions so far + o[ns].push(...(o[wildcardFirstSym] || [])) + } + + if (ns === wildcardFirstSym) { + // new * path gets added to all previously registered literal ns's. + Object.keys(o).forEach(function (k) { + if (o[k]) { + o[k].push(nextPath) + } + }) + } + + o[ns].push(nextPath) + return o + }, {}) + + // the redactor assigned to the format symbol key + // provides top level redaction for instances where + // an object is interpolated into the msg string + const result = { + [redactFmtSym]: fastRedact({ paths, censor, serialize, strict }) + } + + const topCensor = (...args) => + typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor) + + return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => { + // top level key: + if (shape[k] === null) o[k] = topCensor + else o[k] = fastRedact({ paths: shape[k], censor, serialize, strict }) + return o + }, result) +} + +function handle (opts) { + if (Array.isArray(opts)) { + opts = { paths: opts, censor: CENSOR } + validate(opts) + return opts + } + var { paths, censor = CENSOR, remove } = opts + if (Array.isArray(paths) === false) { throw Error('pino – redact must contain an array of strings') } + if (remove === true) censor = undefined + validate({ paths, censor }) + + return { paths, censor } +} + +module.exports = redaction + + +/***/ }), + +/***/ 3957: +/***/ ((module) => { + +"use strict"; + + +const setLevelSym = Symbol('pino.setLevel') +const getLevelSym = Symbol('pino.getLevel') +const levelValSym = Symbol('pino.levelVal') +const useLevelLabelsSym = Symbol('pino.useLevelLabels') +const levelKeySym = Symbol('pino.levelKey') +const useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels') +const mixinSym = Symbol('pino.mixin') + +const lsCacheSym = Symbol('pino.lsCache') +const chindingsSym = Symbol('pino.chindings') +const parsedChindingsSym = Symbol('pino.parsedChindings') + +const asJsonSym = Symbol('pino.asJson') +const writeSym = Symbol('pino.write') +const redactFmtSym = Symbol('pino.redactFmt') + +const timeSym = Symbol('pino.time') +const timeSliceIndexSym = Symbol('pino.timeSliceIndex') +const streamSym = Symbol('pino.stream') +const stringifySym = Symbol('pino.stringify') +const stringifiersSym = Symbol('pino.stringifiers') +const endSym = Symbol('pino.end') +const formatOptsSym = Symbol('pino.formatOpts') +const messageKeySym = Symbol('pino.messageKey') +const nestedKeySym = Symbol('pino.nestedKey') + +const wildcardFirstSym = Symbol('pino.wildcardFirst') + +// public symbols, no need to use the same pino +// version for these +const serializersSym = Symbol.for('pino.serializers') +const wildcardGsym = Symbol.for('pino.*') +const needsMetadataGsym = Symbol.for('pino.metadata') + +module.exports = { + setLevelSym, + getLevelSym, + levelValSym, + useLevelLabelsSym, + mixinSym, + lsCacheSym, + chindingsSym, + parsedChindingsSym, + asJsonSym, + writeSym, + serializersSym, + redactFmtSym, + timeSym, + timeSliceIndexSym, + streamSym, + stringifySym, + stringifiersSym, + endSym, + formatOptsSym, + messageKeySym, + nestedKeySym, + wildcardFirstSym, + levelKeySym, + wildcardGsym, + needsMetadataGsym, + useOnlyCustomLevelsSym +} + + +/***/ }), + +/***/ 1866: +/***/ ((module) => { + +"use strict"; + + +const nullTime = () => '' + +const epochTime = () => `,"time":${Date.now()}` + +const unixTime = () => `,"time":${Math.round(Date.now() / 1000.0)}` + +const isoTime = () => `,"time":"${new Date(Date.now()).toISOString()}"` // using Date.now() for testability + +module.exports = { nullTime, epochTime, unixTime, isoTime } + + +/***/ }), + +/***/ 1521: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/* eslint no-prototype-builtins: 0 */ + +const format = __webpack_require__(5933) +const { mapHttpRequest, mapHttpResponse } = __webpack_require__(2571) +const SonicBoom = __webpack_require__(3460) +const stringifySafe = __webpack_require__(7676) +const { + lsCacheSym, + chindingsSym, + parsedChindingsSym, + writeSym, + serializersSym, + formatOptsSym, + endSym, + stringifiersSym, + stringifySym, + wildcardFirstSym, + needsMetadataGsym, + wildcardGsym, + redactFmtSym, + streamSym, + nestedKeySym +} = __webpack_require__(3957) + +function noop () {} + +function genLog (z) { + return function LOG (o, ...n) { + if (typeof o === 'object' && o !== null) { + if (o.method && o.headers && o.socket) { + o = mapHttpRequest(o) + } else if (typeof o.setHeader === 'function') { + o = mapHttpResponse(o) + } + if (this[nestedKeySym]) o = { [this[nestedKeySym]]: o } + this[writeSym](o, format(null, n, this[formatOptsSym]), z) + } else this[writeSym](null, format(o, n, this[formatOptsSym]), z) + } +} + +// magically escape strings for json +// relying on their charCodeAt +// everything below 32 needs JSON.stringify() +// 34 and 92 happens all the time, so we +// have a fast case for them +function asString (str) { + var result = '' + var last = 0 + var found = false + var point = 255 + const l = str.length + if (l > 100) { + return JSON.stringify(str) + } + for (var i = 0; i < l && point >= 32; i++) { + point = str.charCodeAt(i) + if (point === 34 || point === 92) { + result += str.slice(last, i) + '\\' + last = i + found = true + } + } + if (!found) { + result = str + } else { + result += str.slice(last) + } + return point < 32 ? JSON.stringify(str) : '"' + result + '"' +} + +function asJson (obj, num, time) { + const stringify = this[stringifySym] + const stringifiers = this[stringifiersSym] + const end = this[endSym] + const chindings = this[chindingsSym] + const serializers = this[serializersSym] + var data = this[lsCacheSym][num] + time + + // we need the child bindings added to the output first so instance logged + // objects can take precedence when JSON.parse-ing the resulting log line + data = data + chindings + + var value + var notHasOwnProperty = obj.hasOwnProperty === undefined + if (serializers[wildcardGsym]) { + obj = serializers[wildcardGsym](obj) + } + const wildcardStringifier = stringifiers[wildcardFirstSym] + for (var key in obj) { + value = obj[key] + if ((notHasOwnProperty || obj.hasOwnProperty(key)) && value !== undefined) { + value = serializers[key] ? serializers[key](value) : value + + const stringifier = stringifiers[key] || wildcardStringifier + + switch (typeof value) { + case 'undefined': + case 'function': + continue + case 'number': + /* eslint no-fallthrough: "off" */ + if (Number.isFinite(value) === false) { + value = null + } + // this case explicity falls through to the next one + case 'boolean': + if (stringifier) value = stringifier(value) + break + case 'string': + value = (stringifier || asString)(value) + break + default: + value = (stringifier || stringify)(value) + } + if (value === undefined) continue + data += ',"' + key + '":' + value + } + } + + return data + end +} + +function asChindings (instance, bindings) { + if (!bindings) { + throw Error('missing bindings for child Pino') + } + var key + var value + var data = instance[chindingsSym] + const stringify = instance[stringifySym] + const stringifiers = instance[stringifiersSym] + const serializers = instance[serializersSym] + if (serializers[wildcardGsym]) { + bindings = serializers[wildcardGsym](bindings) + } + for (key in bindings) { + value = bindings[key] + const valid = key !== 'level' && + key !== 'serializers' && + key !== 'customLevels' && + bindings.hasOwnProperty(key) && + value !== undefined + if (valid === true) { + value = serializers[key] ? serializers[key](value) : value + value = (stringifiers[key] || stringify)(value) + if (value === undefined) continue + data += ',"' + key + '":' + value + } + } + return data +} + +function getPrettyStream (opts, prettifier, dest, instance) { + if (prettifier && typeof prettifier === 'function') { + prettifier = prettifier.bind(instance) + return prettifierMetaWrapper(prettifier(opts), dest) + } + try { + var prettyFactory = __webpack_require__(1691) + prettyFactory.asMetaWrapper = prettifierMetaWrapper + return prettifierMetaWrapper(prettyFactory(opts), dest) + } catch (e) { + throw Error('Missing `pino-pretty` module: `pino-pretty` must be installed separately') + } +} + +function prettifierMetaWrapper (pretty, dest) { + var warned = false + return { + [needsMetadataGsym]: true, + lastLevel: 0, + lastMsg: null, + lastObj: null, + lastLogger: null, + flushSync () { + if (warned) { + return + } + warned = true + setMetadataProps(dest, this) + dest.write(pretty(Object.assign({ + level: 40, // warn + msg: 'pino.final with prettyPrint does not support flushing', + time: Date.now() + }, this.chindings()))) + }, + chindings () { + const lastLogger = this.lastLogger + var chindings = null + + // protection against flushSync being called before logging + // anything + if (!lastLogger) { + return null + } + + if (lastLogger.hasOwnProperty(parsedChindingsSym)) { + chindings = lastLogger[parsedChindingsSym] + } else { + chindings = JSON.parse('{"v":1' + lastLogger[chindingsSym] + '}') + lastLogger[parsedChindingsSym] = chindings + } + + return chindings + }, + write (chunk) { + const lastLogger = this.lastLogger + const chindings = this.chindings() + + var time = this.lastTime + + if (time.match(/^\d+/)) { + time = parseInt(time) + } + + var lastObj = this.lastObj + var errorProps = null + + const obj = Object.assign({ + level: this.lastLevel, + time + }, chindings, lastObj, errorProps) + + const serializers = lastLogger[serializersSym] + const keys = Object.keys(serializers) + var key + + for (var i = 0; i < keys.length; i++) { + key = keys[i] + if (obj[key] !== undefined) { + obj[key] = serializers[key](obj[key]) + } + } + + const stringifiers = lastLogger[stringifiersSym] + const redact = stringifiers[redactFmtSym] + + const formatted = pretty(typeof redact === 'function' ? redact(obj) : obj) + if (formatted === undefined) return + + setMetadataProps(dest, this) + dest.write(formatted) + } + } +} + +function hasBeenTampered (stream) { + return stream.write !== stream.constructor.prototype.write +} + +function buildSafeSonicBoom (dest, buffer = 0, sync = true) { + const stream = new SonicBoom(dest, buffer, sync) + stream.on('error', filterBrokenPipe) + return stream + + function filterBrokenPipe (err) { + // TODO verify on Windows + if (err.code === 'EPIPE') { + // If we get EPIPE, we should stop logging here + // however we have no control to the consumer of + // SonicBoom, so we just overwrite the write method + stream.write = noop + stream.end = noop + stream.flushSync = noop + stream.destroy = noop + return + } + stream.removeListener('error', filterBrokenPipe) + stream.emit('error', err) + } +} + +function createArgsNormalizer (defaultOptions) { + return function normalizeArgs (instance, opts = {}, stream) { + // support stream as a string + if (typeof opts === 'string') { + stream = buildSafeSonicBoom(opts) + opts = {} + } else if (typeof stream === 'string') { + stream = buildSafeSonicBoom(stream) + } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) { + stream = opts + opts = null + } + opts = Object.assign({}, defaultOptions, opts) + if ('extreme' in opts) { + throw Error('The extreme option has been removed, use pino.extreme instead') + } + if ('onTerminated' in opts) { + throw Error('The onTerminated option has been removed, use pino.final instead') + } + if ('changeLevelName' in opts) { + process.emitWarning( + 'The changeLevelName option is deprecated and will be removed in v7. Use levelKey instead.', + { code: 'changeLevelName_deprecation' } + ) + opts.levelKey = opts.changeLevelName + delete opts.changeLevelName + } + const { enabled, prettyPrint, prettifier, messageKey } = opts + if (enabled === false) opts.level = 'silent' + stream = stream || process.stdout + if (stream === process.stdout && stream.fd >= 0 && !hasBeenTampered(stream)) { + stream = buildSafeSonicBoom(stream.fd) + } + if (prettyPrint) { + const prettyOpts = Object.assign({ messageKey }, prettyPrint) + stream = getPrettyStream(prettyOpts, prettifier, stream, instance) + } + return { opts, stream } + } +} + +function final (logger, handler) { + if (typeof logger === 'undefined' || typeof logger.child !== 'function') { + throw Error('expected a pino logger instance') + } + const hasHandler = (typeof handler !== 'undefined') + if (hasHandler && typeof handler !== 'function') { + throw Error('if supplied, the handler parameter should be a function') + } + const stream = logger[streamSym] + if (typeof stream.flushSync !== 'function') { + throw Error('final requires a stream that has a flushSync method, such as pino.destination and pino.extreme') + } + + const finalLogger = new Proxy(logger, { + get: (logger, key) => { + if (key in logger.levels.values) { + return (...args) => { + logger[key](...args) + stream.flushSync() + } + } + return logger[key] + } + }) + + if (!hasHandler) { + return finalLogger + } + + return (err = null, ...args) => { + try { + stream.flushSync() + } catch (e) { + // it's too late to wait for the stream to be ready + // because this is a final tick scenario. + // in practice there shouldn't be a situation where it isn't + // however, swallow the error just in case (and for easier testing) + } + return handler(err, finalLogger, ...args) + } +} + +function stringify (obj) { + try { + return JSON.stringify(obj) + } catch (_) { + return stringifySafe(obj) + } +} + +function setMetadataProps (dest, that) { + if (dest[needsMetadataGsym] === true) { + dest.lastLevel = that.lastLevel + dest.lastMsg = that.lastMsg + dest.lastObj = that.lastObj + dest.lastTime = that.lastTime + dest.lastLogger = that.lastLogger + } +} + +module.exports = { + noop, + buildSafeSonicBoom, + getPrettyStream, + asChindings, + asJson, + genLog, + createArgsNormalizer, + final, + stringify +} + + +/***/ }), + +/***/ 9608: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const os = __webpack_require__(2087) +const stdSerializers = __webpack_require__(2571) +const redaction = __webpack_require__(4219) +const time = __webpack_require__(1866) +const proto = __webpack_require__(6899) +const symbols = __webpack_require__(3957) +const { assertDefaultLevelFound, mappings, genLsCache } = __webpack_require__(591) +const { + createArgsNormalizer, + asChindings, + final, + stringify, + buildSafeSonicBoom +} = __webpack_require__(1521) +const { version, LOG_VERSION } = __webpack_require__(8578) +const { + chindingsSym, + redactFmtSym, + serializersSym, + timeSym, + timeSliceIndexSym, + streamSym, + stringifySym, + stringifiersSym, + setLevelSym, + endSym, + formatOptsSym, + messageKeySym, + nestedKeySym, + useLevelLabelsSym, + levelKeySym, + mixinSym, + useOnlyCustomLevelsSym +} = symbols +const { epochTime, nullTime } = time +const { pid } = process +const hostname = os.hostname() +const defaultErrorSerializer = stdSerializers.err +const defaultOptions = { + level: 'info', + useLevelLabels: false, + messageKey: 'msg', + nestedKey: null, + enabled: true, + prettyPrint: false, + base: { pid, hostname }, + serializers: Object.assign(Object.create(null), { + err: defaultErrorSerializer + }), + timestamp: epochTime, + name: undefined, + redact: null, + customLevels: null, + levelKey: 'level', + useOnlyCustomLevels: false +} + +const normalize = createArgsNormalizer(defaultOptions) + +const serializers = Object.assign(Object.create(null), stdSerializers) + +function pino (...args) { + const instance = {} + const { opts, stream } = normalize(instance, ...args) + const { + redact, + crlf, + serializers, + timestamp, + messageKey, + nestedKey, + base, + name, + level, + customLevels, + useLevelLabels, + levelKey, + mixin, + useOnlyCustomLevels + } = opts + + const stringifiers = redact ? redaction(redact, stringify) : {} + const formatOpts = redact + ? { stringify: stringifiers[redactFmtSym] } + : { stringify } + const end = ',"v":' + LOG_VERSION + '}' + (crlf ? '\r\n' : '\n') + const coreChindings = asChindings.bind(null, { + [chindingsSym]: '', + [serializersSym]: serializers, + [stringifiersSym]: stringifiers, + [stringifySym]: stringify + }) + const chindings = base === null ? '' : (name === undefined) + ? coreChindings(base) : coreChindings(Object.assign({}, base, { name })) + const time = (timestamp instanceof Function) + ? timestamp : (timestamp ? epochTime : nullTime) + const timeSliceIndex = time().indexOf(':') + 1 + + if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true') + if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type "${typeof mixin}" - expected "function"`) + + assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels) + const levels = mappings(customLevels, useOnlyCustomLevels) + + Object.assign(instance, { + levels, + [useLevelLabelsSym]: useLevelLabels, + [levelKeySym]: levelKey, + [useOnlyCustomLevelsSym]: useOnlyCustomLevels, + [streamSym]: stream, + [timeSym]: time, + [timeSliceIndexSym]: timeSliceIndex, + [stringifySym]: stringify, + [stringifiersSym]: stringifiers, + [endSym]: end, + [formatOptsSym]: formatOpts, + [messageKeySym]: messageKey, + [nestedKeySym]: nestedKey, + [serializersSym]: serializers, + [mixinSym]: mixin, + [chindingsSym]: chindings + }) + Object.setPrototypeOf(instance, proto) + + if (customLevels || useLevelLabels || levelKey !== defaultOptions.levelKey) genLsCache(instance) + + instance[setLevelSym](level) + + return instance +} + +pino.extreme = (dest = process.stdout.fd) => buildSafeSonicBoom(dest, 4096, false) +pino.destination = (dest = process.stdout.fd) => buildSafeSonicBoom(dest, 0, true) + +pino.final = final +pino.levels = mappings() +pino.stdSerializers = serializers +pino.stdTimeFunctions = Object.assign({}, time) +pino.symbols = symbols +pino.version = version +pino.LOG_VERSION = LOG_VERSION + +module.exports = pino + + +/***/ }), + +/***/ 7810: +/***/ ((module) => { + +"use strict"; + + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} + +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); + }); + } +} + + + +/***/ }), + +/***/ 5933: +/***/ ((module) => { + +"use strict"; + +function tryStringify (o) { + try { return JSON.stringify(o) } catch(e) { return '"[Circular]"' } +} + +module.exports = format + +function format(f, args, opts) { + var ss = (opts && opts.stringify) || tryStringify + var offset = 1 + if (f === null) { + f = args[0] + offset = 0 + } + if (typeof f === 'object' && f !== null) { + var len = args.length + offset + if (len === 1) return f + var objects = new Array(len) + objects[0] = ss(f) + for (var index = 1; index < len; index++) { + objects[index] = ss(args[index]) + } + return objects.join(' ') + } + var argLen = args.length + if (argLen === 0) return f + var x = '' + var str = '' + var a = 1 - offset + var lastPos = 0 + var flen = (f && f.length) || 0 + for (var i = 0; i < flen;) { + if (f.charCodeAt(i) === 37 && i + 1 < flen) { + switch (f.charCodeAt(i + 1)) { + case 100: // 'd' + if (a >= argLen) + break + if (lastPos < i) + str += f.slice(lastPos, i) + if (args[a] == null) break + str += Number(args[a]) + lastPos = i = i + 2 + break + case 79: // 'O' + case 111: // 'o' + case 106: // 'j' + if (a >= argLen) + break + if (lastPos < i) + str += f.slice(lastPos, i) + if (args[a] === undefined) break + var type = typeof args[a] + if (type === 'string') { + str += '\'' + args[a] + '\'' + lastPos = i + 2 + i++ + break + } + if (type === 'function') { + str += args[a].name || '' + lastPos = i + 2 + i++ + break + } + str += ss(args[a]) + lastPos = i + 2 + i++ + break + case 115: // 's' + if (a >= argLen) + break + if (lastPos < i) + str += f.slice(lastPos, i) + str += String(args[a]) + lastPos = i + 2 + i++ + break + case 37: // '%' + if (lastPos < i) + str += f.slice(lastPos, i) + str += '%' + lastPos = i + 2 + i++ + break + } + ++a + } + ++i + } + if (lastPos === 0) + str = f + else if (lastPos < flen) { + str += f.slice(lastPos) + } + while (a < argLen) { + x = args[a++] + if (x === null || (typeof x !== 'object')) { + str += ' ' + String(x) + } else { + str += ' ' + ss(x) + } + } + + return str +} + + +/***/ }), + +/***/ 1359: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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. + +// 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. + + + +/**/ + +var pna = __webpack_require__(7810); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = Object.create(__webpack_require__(5898)); +util.inherits = __webpack_require__(4124); +/**/ + +var Readable = __webpack_require__(1433); +var Writable = __webpack_require__(6993); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + 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 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; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// 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; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; + +/***/ }), + +/***/ 1542: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + + + +module.exports = PassThrough; + +var Transform = __webpack_require__(4415); + +/**/ +var util = Object.create(__webpack_require__(5898)); +util.inherits = __webpack_require__(4124); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +/***/ }), + +/***/ 1433: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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. + + + +/**/ + +var pna = __webpack_require__(7810); +/**/ + +module.exports = Readable; + +/**/ +var isArray = __webpack_require__(893); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = __webpack_require__(8614).EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(2387); +/**/ + +/**/ + +var Buffer = __webpack_require__(110).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +/**/ +var util = Object.create(__webpack_require__(5898)); +util.inherits = __webpack_require__(4124); +/**/ + +/**/ +var debugUtil = __webpack_require__(1669); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = __webpack_require__(7053); +var destroyImpl = __webpack_require__(7049); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +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); + + // 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]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(1359); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // 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; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // 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 readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // 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; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // 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 read call. + this.sync = true; + + // 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; + + // has it been destroyed + this.destroyed = false; + + // 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'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = __webpack_require__(4841)/* .StringDecoder */ .s; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || __webpack_require__(1359); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// 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; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + 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); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// 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); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __webpack_require__(4841)/* .StringDecoder */ .s; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// 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; +} + +// 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; +} + +// 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; + + if (n !== 0) state.emittedReadable = false; + + // 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; + } + + n = howMuchToRead(n, state); + + // 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; + } + + // 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 we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // 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); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + 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; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +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; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// 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) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +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; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +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; +} + +// 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')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + 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 doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // 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); + + 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', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // 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(); + } + + // 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(); + } + } + + // 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); + + // 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); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +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; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // 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; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + 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, unpipeInfo); + }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, unpipeInfo); + + 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) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// 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; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +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; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// 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 _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // 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 ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // 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); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +// 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; +} + +// 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; +} + +// 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; +} + +// 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 = Buffer.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; +} + +function endReadable(stream) { + var state = stream._readableState; + + // 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'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +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'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +/***/ }), + +/***/ 4415: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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. + +// 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. + + + +module.exports = Transform; + +var Duplex = __webpack_require__(1359); + +/**/ +var util = Object.create(__webpack_require__(5898)); +util.inherits = __webpack_require__(4124); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // 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; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// 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'); +}; + +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); + } +}; + +// 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; + + 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; + } +}; + +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +/***/ }), + +/***/ 6993: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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. + +// 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 pna = __webpack_require__(7810); +/**/ + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = 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; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = Object.create(__webpack_require__(5898)); +util.inherits = __webpack_require__(4124); +/**/ + +/**/ +var internalUtil = { + deprecate: __webpack_require__(5278) +}; +/**/ + +/**/ +var Stream = __webpack_require__(2387); +/**/ + +/**/ + +var Buffer = __webpack_require__(110).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +var destroyImpl = __webpack_require__(7049); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || __webpack_require__(1359); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // 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 writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // 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; + + // has it been destroyed + this.destroyed = false; + + // 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; + + // 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'; + + // 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; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // 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; + + // 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; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +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.', 'DEP0003') + }); + } 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; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || __webpack_require__(1359); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // 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); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO [$5f5fbe42fcabad09c1c241bb]: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} + +// 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); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +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; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// 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) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + 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 = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +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 onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + 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); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// 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; + + 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; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // 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); + } + state.bufferedRequestCount = 0; + } 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; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // 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; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +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; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; + +/***/ }), + +/***/ 7053: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = __webpack_require__(110).Buffer; +var util = __webpack_require__(1669); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} + +/***/ }), + +/***/ 7049: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/**/ + +var pna = __webpack_require__(7810); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); + + return this; +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; + +/***/ }), + +/***/ 2387: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(2413); + + +/***/ }), + +/***/ 110: +/***/ ((module, exports, __webpack_require__) => { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(4293) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +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) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 1642: +/***/ ((module, exports, __webpack_require__) => { + +var Stream = __webpack_require__(2413); +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__(1433); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __webpack_require__(6993); + exports.Duplex = __webpack_require__(1359); + exports.Transform = __webpack_require__(4415); + exports.PassThrough = __webpack_require__(1542); +} + + +/***/ }), + +/***/ 9200: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var fs = __webpack_require__(5747), + join = __webpack_require__(5622).join, + resolve = __webpack_require__(5622).resolve, + dirname = __webpack_require__(5622).dirname, + defaultOptions = { + extensions: ['js', 'json', 'coffee'], + recurse: true, + rename: function (name) { + return name; + }, + visit: function (obj) { + return obj; + } + }; + +function checkFileInclusion(path, filename, options) { + return ( + // verify file has valid extension + (new RegExp('\\.(' + options.extensions.join('|') + ')$', 'i').test(filename)) && + + // if options.include is a RegExp, evaluate it and make sure the path passes + !(options.include && options.include instanceof RegExp && !options.include.test(path)) && + + // if options.include is a function, evaluate it and make sure the path passes + !(options.include && typeof options.include === 'function' && !options.include(path, filename)) && + + // if options.exclude is a RegExp, evaluate it and make sure the path doesn't pass + !(options.exclude && options.exclude instanceof RegExp && options.exclude.test(path)) && + + // if options.exclude is a function, evaluate it and make sure the path doesn't pass + !(options.exclude && typeof options.exclude === 'function' && options.exclude(path, filename)) + ); +} + +function requireDirectory(m, path, options) { + var retval = {}; + + // path is optional + if (path && !options && typeof path !== 'string') { + options = path; + path = null; + } + + // default options + options = options || {}; + for (var prop in defaultOptions) { + if (typeof options[prop] === 'undefined') { + options[prop] = defaultOptions[prop]; + } + } + + // if no path was passed in, assume the equivelant of __dirname from caller + // otherwise, resolve path relative to the equivalent of __dirname + path = !path ? dirname(m.filename) : resolve(dirname(m.filename), path); + + // get the path of each file in specified directory, append to current tree node, recurse + fs.readdirSync(path).forEach(function (filename) { + var joined = join(path, filename), + files, + key, + obj; + + if (fs.statSync(joined).isDirectory() && options.recurse) { + // this node is a directory; recurse + files = requireDirectory(m, joined, options); + // exclude empty directories + if (Object.keys(files).length) { + retval[options.rename(filename, joined, filename)] = files; + } + } else { + if (joined !== m.filename && checkFileInclusion(joined, filename, options)) { + // hash node key shouldn't include file extension + key = filename.substring(0, filename.lastIndexOf('.')); + obj = m.require(joined); + retval[options.rename(key, joined, filename)] = options.visit(obj, joined, filename) || obj; + } + } + }); + + return retval; +} + +module.exports = requireDirectory; +module.exports.defaults = defaultOptions; + + +/***/ }), + +/***/ 6829: +/***/ ((module) => { + +module.exports = function (_require) { + _require = _require || require + var main = _require.main + if (main && isIISNode(main)) return handleIISNode(main) + else return main ? main.filename : process.cwd() +} + +function isIISNode (main) { + return /\\iisnode\\/.test(main.filename) +} + +function handleIISNode (main) { + if (!main.children.length) { + return main.filename + } else { + return main.children[0].filename + } +} + + +/***/ }), + +/***/ 6985: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* module decorator */ module = __webpack_require__.nmd(module); +var path = __webpack_require__(5622), + fs = __webpack_require__(5747), + f = __webpack_require__(1669).format, + resolveFrom = __webpack_require__(7482), + semver = __webpack_require__(5911); + +var exists = fs.existsSync || path.existsSync; + +// Find the location of a package.json file near or above the given location +var find_package_json = function(location) { + var found = false; + + while(!found) { + if (exists(location + '/package.json')) { + found = location; + } else if (location !== '/') { + location = path.dirname(location); + } else { + return false; + } + } + + return location; +} + +// Find the package.json object of the module closest up the module call tree that contains name in that module's peerOptionalDependencies +var find_package_json_with_name = function(name) { + // Walk up the module call tree until we find a module containing name in its peerOptionalDependencies + var currentModule = module; + var found = false; + while (currentModule) { + // Check currentModule has a package.json + location = currentModule.filename; + var location = find_package_json(location) + if (!location) { + currentModule = currentModule.parent; + continue; + } + + // Read the package.json file + var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Is the name defined by interal file references + var parts = name.split(/\//); + + // Check whether this package.json contains peerOptionalDependencies containing the name we're searching for + if (!object.peerOptionalDependencies || (object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]])) { + currentModule = currentModule.parent; + continue; + } + found = true; + break; + } + + // Check whether name has been found in currentModule's peerOptionalDependencies + if (!found) { + throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in any package.json', parts[0])); + } + + return { + object: object, + parts: parts + } +} + +var require_optional = function(name, options) { + options = options || {}; + options.strict = typeof options.strict == 'boolean' ? options.strict : true; + + var res = find_package_json_with_name(name) + var object = res.object; + var parts = res.parts; + + // Unpack the expected version + var expectedVersions = object.peerOptionalDependencies[parts[0]]; + // The resolved package + var moduleEntry = undefined; + // Module file + var moduleEntryFile = name; + + try { + // Validate if it's possible to read the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + // Attempt to resolve in top level package + try { + // Get the module entry file + moduleEntryFile = resolveFrom(process.cwd(), name); + if(moduleEntryFile == null) return undefined; + // Attempt to resolve the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + if(err.code === 'MODULE_NOT_FOUND') return undefined; + } + } + + // Resolve the location of the module's package.json file + var location = find_package_json(require.resolve(moduleEntryFile)); + if(!location) { + throw new Error('package.json can not be located'); + } + + // Read the module file + var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Get the version + var version = dependentOnModule.version; + // Validate if the found module satisfies the version id + if(semver.satisfies(version, expectedVersions) == false + && options.strict) { + var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions)); + error.code = 'OPTIONAL_MODULE_NOT_FOUND'; + throw error; + } + + // Satifies the module requirement + return moduleEntry; +} + +require_optional.exists = function(name) { + try { + var m = require_optional(name); + if(m === undefined) return false; + return true; + } catch(err) { + return false; + } +} + +module.exports = require_optional; + + +/***/ }), + +/***/ 7482: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var path = __webpack_require__(5622); +var Module = __webpack_require__(2282); + +module.exports = function (fromDir, moduleId) { + if (typeof fromDir !== 'string' || typeof moduleId !== 'string') { + throw new TypeError('Expected `fromDir` and `moduleId` to be a string'); + } + + fromDir = path.resolve(fromDir); + + var fromFile = path.join(fromDir, 'noop.js'); + + try { + return Module._resolveFilename(moduleId, { + id: fromFile, + filename: fromFile, + paths: Module._nodeModulePaths(fromDir) + }); + } catch (err) { + return null; + } +}; + + +/***/ }), + +/***/ 1867: +/***/ ((module, exports, __webpack_require__) => { + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(4293) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +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) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 9178: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, +} = __webpack_require__(8916); + +module.exports = saslprep; + +// 2.1. Mapping + +/** + * non-ASCII space characters [StringPrep, C.1.2] that can be + * mapped to SPACE (U+0020) + */ +const mapping2space = non_ASCII_space_characters; + +/** + * the "commonly mapped to nothing" characters [StringPrep, B.1] + * that can be mapped to nothing. + */ +const mapping2nothing = commonly_mapped_to_nothing; + +// utils +const getCodePoint = character => character.codePointAt(0); +const first = x => x[0]; +const last = x => x[x.length - 1]; + +/** + * Convert provided string into an array of Unicode Code Points. + * Based on https://stackoverflow.com/a/21409165/1556249 + * and https://www.npmjs.com/package/code-point-at. + * @param {string} input + * @returns {number[]} + */ +function toCodePoints(input) { + const codepoints = []; + const size = input.length; + + for (let i = 0; i < size; i += 1) { + const before = input.charCodeAt(i); + + if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { + const next = input.charCodeAt(i + 1); + + if (next >= 0xdc00 && next <= 0xdfff) { + codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); + i += 1; + continue; + } + } + + codepoints.push(before); + } + + return codepoints; +} + +/** + * SASLprep. + * @param {string} input + * @param {Object} opts + * @param {boolean} opts.allowUnassigned + * @returns {string} + */ +function saslprep(input, opts = {}) { + if (typeof input !== 'string') { + throw new TypeError('Expected string.'); + } + + if (input.length === 0) { + return ''; + } + + // 1. Map + const mapped_input = toCodePoints(input) + // 1.1 mapping to space + .map(character => (mapping2space.get(character) ? 0x20 : character)) + // 1.2 mapping to nothing + .filter(character => !mapping2nothing.get(character)); + + // 2. Normalize + const normalized_input = String.fromCodePoint + .apply(null, mapped_input) + .normalize('NFKC'); + + const normalized_map = toCodePoints(normalized_input); + + // 3. Prohibit + const hasProhibited = normalized_map.some(character => + prohibited_characters.get(character) + ); + + if (hasProhibited) { + throw new Error( + 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' + ); + } + + // Unassigned Code Points + if (opts.allowUnassigned !== true) { + const hasUnassigned = normalized_map.some(character => + unassigned_code_points.get(character) + ); + + if (hasUnassigned) { + throw new Error( + 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' + ); + } + } + + // 4. check bidi + + const hasBidiRAL = normalized_map.some(character => + bidirectional_r_al.get(character) + ); + + const hasBidiL = normalized_map.some(character => + bidirectional_l.get(character) + ); + + // 4.1 If a string contains any RandALCat character, the string MUST NOT + // contain any LCat character. + if (hasBidiRAL && hasBidiL) { + throw new Error( + 'String must not contain RandALCat and LCat at the same time,' + + ' see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + /** + * 4.2 If a string contains any RandALCat character, a RandALCat + * character MUST be the first character of the string, and a + * RandALCat character MUST be the last character of the string. + */ + + const isFirstBidiRAL = bidirectional_r_al.get( + getCodePoint(first(normalized_input)) + ); + const isLastBidiRAL = bidirectional_r_al.get( + getCodePoint(last(normalized_input)) + ); + + if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { + throw new Error( + 'Bidirectional RandALCat character must be the first and the last' + + ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + return normalized_input; +} + + +/***/ }), + +/***/ 8916: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const fs = __webpack_require__(5747); +const path = __webpack_require__(5622); +const bitfield = __webpack_require__(1453); + +/* eslint-disable-next-line security/detect-non-literal-fs-filename */ +const memory = fs.readFileSync(__webpack_require__.ab + "code-points.mem"); +let offset = 0; + +/** + * Loads each code points sequence from buffer. + * @returns {bitfield} + */ +function read() { + const size = memory.readUInt32BE(offset); + offset += 4; + + const codepoints = memory.slice(offset, offset + size); + offset += size; + + return bitfield({ buffer: codepoints }); +} + +const unassigned_code_points = read(); +const commonly_mapped_to_nothing = read(); +const non_ASCII_space_characters = read(); +const prohibited_characters = read(); +const bidirectional_r_al = read(); +const bidirectional_l = read(); + +module.exports = { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, +}; + + +/***/ }), + +/***/ 5911: +/***/ ((module, exports) => { + +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} +} + +// 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' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var R = 0 + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++ +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' +var NUMERICIDENTIFIERLOOSE = R++ +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++ +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++ +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')' + +var MAINVERSIONLOOSE = R++ +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++ +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +var PRERELEASEIDENTIFIERLOOSE = R++ +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++ +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' + +var PRERELEASELOOSE = R++ +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++ +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++ +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// 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 FULL = R++ +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?' + +src[FULL] = '^' + FULLPLAIN + '$' + +// 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] + '?' + +var LOOSE = R++ +src[LOOSE] = '^' + LOOSEPLAIN + '$' + +var GTLT = R++ +src[GTLT] = '((?:<|>)?=?)' + +// 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 XRANGEPLAIN = R++ +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGEPLAINLOOSE = R++ +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGE = R++ +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' +var XRANGELOOSE = R++ +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++ +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' + +// 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~' + +var TILDE = R++ +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' +var TILDELOOSE = R++ +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++ +src[LONECARET] = '(?:\\^)' + +var CARETTRIM = R++ +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') +var caretTrimReplace = '$1^' + +var CARET = R++ +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' +var CARETLOOSE = R++ +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + +// 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 + ')$|^$' + +// 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' + +// 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*$' + +var HYPHENRANGELOOSE = R++ +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$' + +// Star ranges basically just allow anything at all. +var STAR = R++ +src[STAR] = '(<|>)?=?\\s*\\*' + +// 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]) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? re[LOOSE] : re[FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} + +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} + +exports.SemVer = SemVer + +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) + + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // 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 + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} + +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) +} + +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // 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 + } + + 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 + + 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 + + default: + throw new Error('invalid increment argument: ' + release) + } + 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 + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} + +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} + +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} + +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} + +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose) + }) +} + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +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 +} + +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} + +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) + } +} + +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + + 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.options.loose) + } +} + +Comparator.prototype.toString = function () { + return this.value +} + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY) { + return true + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + return cmp(version, this.operator, this.semver, this.options) +} + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + var rangeTmp + + if (this.operator === '') { + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} + +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options) + } + + if (!(this instanceof Range)) { + return new Range(range, options) + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // 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 + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) + } + + this.format() +} + +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} + +Range.prototype.toString = function () { + return this.range +} + +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `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]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.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, this.options) + }, this) + + return set +} + +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + }) + }) +} + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} + +// 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, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} + +// ~, ~> --> * (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, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} + +function replaceTilde (comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret + + 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) + 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' + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (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, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') +} + +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[CARETLOOSE] : re[CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + + 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 (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' + } + } + + debug('caret return', ret) + return ret + }) +} + +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} + +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.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 + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + 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 { + 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 + } + } + + 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' + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], '') +} + +// 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) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } + + 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 + } + + return (from + ' ' + to).trim() +} + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} + +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // 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 (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } + + 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 + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} + +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} + +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} + +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} + +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) + + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} + +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) +} + +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) + + 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 ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + var high = null + var low = null + + 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, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + 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 + } + + // 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 +} + +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} + +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce +function coerce (version) { + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + var match = version.match(re[COERCE]) + + if (match == null) { + return null + } + + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) +} + + +/***/ }), + +/***/ 9344: +/***/ ((module) => { + +module.exports = function (blocking) { + [process.stdout, process.stderr].forEach(function (stream) { + if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') { + stream._handle.setBlocking(blocking) + } + }) +} + + +/***/ }), + +/***/ 3460: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const fs = __webpack_require__(5747) +const EventEmitter = __webpack_require__(8614) +const flatstr = __webpack_require__(5298) +const inherits = __webpack_require__(1669).inherits + +const BUSY_WRITE_TIMEOUT = 100 + +const sleep = __webpack_require__(6950) + +// 16 MB - magic number +// This constant ensures that SonicBoom only needs +// 32 MB of free memory to run. In case of having 1GB+ +// of data to write, this prevents an out of memory +// condition. +const MAX_WRITE = 16 * 1024 * 1024 + +function openFile (file, sonic) { + sonic._opening = true + sonic._writing = true + sonic.file = file + fs.open(file, 'a', (err, fd) => { + if (err) { + sonic.emit('error', err) + return + } + + sonic.fd = fd + sonic._reopening = false + sonic._opening = false + sonic._writing = false + + sonic.emit('ready') + + if (sonic._reopening) { + return + } + + // start + var len = sonic._buf.length + if (len > 0 && len > sonic.minLength && !sonic.destroyed) { + actualWrite(sonic) + } + }) +} + +function SonicBoom (fd, minLength, sync) { + if (!(this instanceof SonicBoom)) { + return new SonicBoom(fd, minLength, sync) + } + + this._buf = '' + this.fd = -1 + this._writing = false + this._writingBuf = '' + this._ending = false + this._reopening = false + this._asyncDrainScheduled = false + this.file = null + this.destroyed = false + this.sync = sync || false + + this.minLength = minLength || 0 + + if (typeof fd === 'number') { + this.fd = fd + process.nextTick(() => this.emit('ready')) + } else if (typeof fd === 'string') { + openFile(fd, this) + } else { + throw new Error('SonicBoom supports only file descriptors and files') + } + + this.release = (err, n) => { + if (err) { + if (err.code === 'EAGAIN') { + if (this.sync) { + // This error code should not happen in sync mode, because it is + // not using the underlining operating system asynchronous functions. + // However it happens, and so we handle it. + // Ref: https://github.com/pinojs/pino/issues/783 + try { + sleep(BUSY_WRITE_TIMEOUT) + this.release(undefined, 0) + } catch (err) { + this.release(err) + } + } else { + // Let's give the destination some time to process the chunk. + setTimeout(() => { + fs.write(this.fd, this._writingBuf, 'utf8', this.release) + }, BUSY_WRITE_TIMEOUT) + } + } else { + this.emit('error', err) + } + return + } + + if (this._writingBuf.length !== n) { + this._writingBuf = this._writingBuf.slice(n) + if (this.sync) { + try { + do { + n = fs.writeSync(this.fd, this._writingBuf, 'utf8') + this._writingBuf = this._writingBuf.slice(n) + } while (this._writingBuf.length !== 0) + } catch (err) { + this.release(err) + return + } + } else { + fs.write(this.fd, this._writingBuf, 'utf8', this.release) + return + } + } + + this._writingBuf = '' + + if (this.destroyed) { + return + } + + var len = this._buf.length + if (this._reopening) { + this._writing = false + this._reopening = false + this.reopen() + } else if (len > 0 && len > this.minLength) { + actualWrite(this) + } else if (this._ending) { + if (len > 0) { + actualWrite(this) + } else { + this._writing = false + actualClose(this) + } + } else { + this._writing = false + if (this.sync) { + if (!this._asyncDrainScheduled) { + this._asyncDrainScheduled = true + process.nextTick(emitDrain, this) + } + } else { + this.emit('drain') + } + } + } +} + +function emitDrain (sonic) { + sonic._asyncDrainScheduled = false + sonic.emit('drain') +} + +inherits(SonicBoom, EventEmitter) + +SonicBoom.prototype.write = function (data) { + if (this.destroyed) { + throw new Error('SonicBoom destroyed') + } + + this._buf += data + var len = this._buf.length + if (!this._writing && len > this.minLength) { + actualWrite(this) + } + return len < 16384 +} + +SonicBoom.prototype.flush = function () { + if (this.destroyed) { + throw new Error('SonicBoom destroyed') + } + + if (this._writing || this.minLength <= 0) { + return + } + + actualWrite(this) +} + +SonicBoom.prototype.reopen = function (file) { + if (this.destroyed) { + throw new Error('SonicBoom destroyed') + } + + if (this._opening) { + this.once('ready', () => { + this.reopen(file) + }) + return + } + + if (this._ending) { + return + } + + if (!this.file) { + throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom') + } + + this._reopening = true + + if (this._writing) { + return + } + + fs.close(this.fd, (err) => { + if (err) { + return this.emit('error', err) + } + }) + + openFile(file || this.file, this) +} + +SonicBoom.prototype.end = function () { + if (this.destroyed) { + throw new Error('SonicBoom destroyed') + } + + if (this._opening) { + this.once('ready', () => { + this.end() + }) + return + } + + if (this._ending) { + return + } + + this._ending = true + + if (!this._writing && this._buf.length > 0 && this.fd >= 0) { + actualWrite(this) + return + } + + if (this._writing) { + return + } + + actualClose(this) +} + +SonicBoom.prototype.flushSync = function () { + if (this.destroyed) { + throw new Error('SonicBoom destroyed') + } + + if (this.fd < 0) { + throw new Error('sonic boom is not ready yet') + } + + if (this._buf.length > 0) { + fs.writeSync(this.fd, this._buf, 'utf8') + this._buf = '' + } +} + +SonicBoom.prototype.destroy = function () { + if (this.destroyed) { + return + } + actualClose(this) +} + +function actualWrite (sonic) { + sonic._writing = true + var buf = sonic._buf + var release = sonic.release + if (buf.length > MAX_WRITE) { + buf = buf.slice(0, MAX_WRITE) + sonic._buf = sonic._buf.slice(MAX_WRITE) + } else { + sonic._buf = '' + } + flatstr(buf) + sonic._writingBuf = buf + if (sonic.sync) { + try { + var written = fs.writeSync(sonic.fd, buf, 'utf8') + release(null, written) + } catch (err) { + release(err) + } + } else { + fs.write(sonic.fd, buf, 'utf8', release) + } +} + +function actualClose (sonic) { + if (sonic.fd === -1) { + sonic.once('ready', actualClose.bind(null, sonic)) + return + } + // TODO write a test to check if we are not leaking fds + fs.close(sonic.fd, (err) => { + if (err) { + sonic.emit('error', err) + return + } + + if (sonic._ending && !sonic._writing) { + sonic.emit('finish') + } + sonic.emit('close') + }) + sonic.destroyed = true + sonic._buf = '' +} + +module.exports = SonicBoom + + +/***/ }), + +/***/ 1453: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var pager = __webpack_require__(7147) + +module.exports = Bitfield + +function Bitfield (opts) { + if (!(this instanceof Bitfield)) return new Bitfield(opts) + if (!opts) opts = {} + if (Buffer.isBuffer(opts)) opts = {buffer: opts} + + this.pageOffset = opts.pageOffset || 0 + this.pageSize = opts.pageSize || 1024 + this.pages = opts.pages || pager(this.pageSize) + + this.byteLength = this.pages.length * this.pageSize + this.length = 8 * this.byteLength + + if (!powerOfTwo(this.pageSize)) throw new Error('The page size should be a power of two') + + this._trackUpdates = !!opts.trackUpdates + this._pageMask = this.pageSize - 1 + + if (opts.buffer) { + for (var i = 0; i < opts.buffer.length; i += this.pageSize) { + this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize)) + } + this.byteLength = opts.buffer.length + this.length = 8 * this.byteLength + } +} + +Bitfield.prototype.get = function (i) { + var o = i & 7 + var j = (i - o) / 8 + + return !!(this.getByte(j) & (128 >> o)) +} + +Bitfield.prototype.getByte = function (i) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, true) + + return page ? page.buffer[o + this.pageOffset] : 0 +} + +Bitfield.prototype.set = function (i, v) { + var o = i & 7 + var j = (i - o) / 8 + var b = this.getByte(j) + + return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))) +} + +Bitfield.prototype.toBuffer = function () { + var all = alloc(this.pages.length * this.pageSize) + + for (var i = 0; i < this.pages.length; i++) { + var next = this.pages.get(i, true) + var allOffset = i * this.pageSize + if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize) + } + + return all +} + +Bitfield.prototype.setByte = function (i, b) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, false) + + o += this.pageOffset + + if (page.buffer[o] === b) return false + page.buffer[o] = b + + if (i >= this.byteLength) { + this.byteLength = i + 1 + this.length = this.byteLength * 8 + } + + if (this._trackUpdates) this.pages.updated(page) + + return true +} + +function alloc (n) { + if (Buffer.alloc) return Buffer.alloc(n) + var b = new Buffer(n) + b.fill(0) + return b +} + +function powerOfTwo (x) { + return !(x & (x - 1)) +} + + +/***/ }), + +/***/ 2577: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const stripAnsi = __webpack_require__(3520); +const isFullwidthCodePoint = __webpack_require__(4882); +const emojiRegex = __webpack_require__(8212)(); + +module.exports = input => { + input = input.replace(emojiRegex, ' '); + + if (typeof input !== 'string' || input.length === 0) { + return 0; + } + + input = stripAnsi(input); + + let width = 0; + + for (let i = 0; i < input.length; i++) { + const code = input.codePointAt(i); + + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } + + // Surrogates + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint(code) ? 2 : 1; + } + + return width; +}; + + +/***/ }), + +/***/ 9139: +/***/ ((module) => { + +"use strict"; + + +module.exports = options => { + options = Object.assign({ + onlyFirst: false + }, options); + + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, options.onlyFirst ? undefined : 'g'); +}; + + +/***/ }), + +/***/ 3520: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const ansiRegex = __webpack_require__(9139); + +const stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; + +module.exports = stripAnsi; +module.exports.default = stripAnsi; + + +/***/ }), + +/***/ 4841: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"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. + + + +/**/ + +var Buffer = __webpack_require__(2279).Buffer; +/**/ + +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; + } +}; + +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; + } + } +}; + +// 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; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.s = 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); +} + +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 || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// 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. If an invalid byte is detected, -2 is returned. +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 byte >> 6 === 0x02 ? -1 : -2; +} + +// 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 || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) 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; +} + +// 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 +// a single UTF-8 replacement character ('\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'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// 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; +} + +// 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 is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + 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; +} + +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 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); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} + +/***/ }), + +/***/ 2279: +/***/ ((module, exports, __webpack_require__) => { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(4293) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +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) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 9694: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const yargs_1 = __importDefault(__webpack_require__(5804)); +const wrap = (yargs) => ({ + parse() { + yargs.parse(); + }, + command(command, description, builder, handler) { + return wrap(yargs.command(command, description, builder, handler)); + }, +}); +function cli(options = {}) { + return wrap(yargs_1.default + .demandCommand() + .strict() + .help() + .options(options)); +} +exports.cli = cli; +//# sourceMappingURL=CLI.js.map + +/***/ }), + +/***/ 2611: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const invariant_1 = __importDefault(__webpack_require__(6799)); +exports.invariant = invariant_1.default; +//# sourceMappingURL=Invariant.js.map + +/***/ }), + +/***/ 5528: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const pino_1 = __importDefault(__webpack_require__(9608)); +let forceMode = null; +let rootLogger = null; +class LoggerWrapper { + constructor(parentLogger, name) { + this.name = name; + this.debug = (thing, ...args) => this.instance.debug(thing, ...args); + this.info = (thing, ...args) => this.instance.info(thing, ...args); + this.warn = (thing, ...args) => this.instance.warn(thing, ...args); + this.error = (thing, ...args) => this.instance.error(thing, ...args); + this.instance = parentLogger.child({ name }); + } + child(name) { + return new LoggerWrapper(this.instance, this.name + ':' + name); + } +} +function logger(name) { + if (!rootLogger) { + rootLogger = pino_1.default({ + prettyPrint: forceMode === 'pretty' || (forceMode === null && process.stdout.isTTY) + ? { translateTime: true } + : false, + }); + } + return new LoggerWrapper(rootLogger, name); +} +exports.logger = logger; +logger.forcePretty = function () { + forceMode = 'pretty'; +}; +logger.forceJSON = function () { + forceMode = 'json'; +}; +//# sourceMappingURL=Logging.js.map + +/***/ }), + +/***/ 9508: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", ({ value: true })); +__export(__webpack_require__(9694)); +__export(__webpack_require__(5528)); +__export(__webpack_require__(2611)); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 6255: +/***/ ((module) => { + +"use strict"; + + +module.exports = options => { + options = Object.assign({ + onlyFirst: false + }, options); + + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, options.onlyFirst ? undefined : 'g'); +}; + + +/***/ }), + +/***/ 1328: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* module decorator */ module = __webpack_require__.nmd(module); + +const colorConvert = __webpack_require__(2913); + +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + 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], + + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); + + +/***/ }), + +/***/ 7897: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var stringWidth = __webpack_require__(2577) +var stripAnsi = __webpack_require__(4133) +var wrap = __webpack_require__(1971) +var align = { + right: alignRight, + center: alignCenter +} +var top = 0 +var right = 1 +var bottom = 2 +var left = 3 + +function UI (opts) { + this.width = opts.width + this.wrap = opts.wrap + this.rows = [] +} + +UI.prototype.span = function () { + var cols = this.div.apply(this, arguments) + cols.span = true +} + +UI.prototype.resetOutput = function () { + this.rows = [] +} + +UI.prototype.div = function () { + if (arguments.length === 0) this.div('') + if (this.wrap && this._shouldApplyLayoutDSL.apply(this, arguments)) { + return this._applyLayoutDSL(arguments[0]) + } + + var cols = [] + + for (var i = 0, arg; (arg = arguments[i]) !== undefined; i++) { + if (typeof arg === 'string') cols.push(this._colFromString(arg)) + else cols.push(arg) + } + + this.rows.push(cols) + return cols +} + +UI.prototype._shouldApplyLayoutDSL = function () { + return arguments.length === 1 && typeof arguments[0] === 'string' && + /[\t\n]/.test(arguments[0]) +} + +UI.prototype._applyLayoutDSL = function (str) { + var _this = this + var rows = str.split('\n') + var leftColumnWidth = 0 + + // simple heuristic for layout, make sure the + // second column lines up along the left-hand. + // don't allow the first column to take up more + // than 50% of the screen. + rows.forEach(function (row) { + var columns = row.split('\t') + if (columns.length > 1 && stringWidth(columns[0]) > leftColumnWidth) { + leftColumnWidth = Math.min( + Math.floor(_this.width * 0.5), + stringWidth(columns[0]) + ) + } + }) + + // generate a table: + // replacing ' ' with padding calculations. + // using the algorithmically generated width. + rows.forEach(function (row) { + var columns = row.split('\t') + _this.div.apply(_this, columns.map(function (r, i) { + return { + text: r.trim(), + padding: _this._measurePadding(r), + width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined + } + })) + }) + + return this.rows[this.rows.length - 1] +} + +UI.prototype._colFromString = function (str) { + return { + text: str, + padding: this._measurePadding(str) + } +} + +UI.prototype._measurePadding = function (str) { + // measure padding without ansi escape codes + var noAnsi = stripAnsi(str) + return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length] +} + +UI.prototype.toString = function () { + var _this = this + var lines = [] + + _this.rows.forEach(function (row, i) { + _this.rowToString(row, lines) + }) + + // don't display any lines with the + // hidden flag set. + lines = lines.filter(function (line) { + return !line.hidden + }) + + return lines.map(function (line) { + return line.text + }).join('\n') +} + +UI.prototype.rowToString = function (row, lines) { + var _this = this + var padding + var rrows = this._rasterize(row) + var str = '' + var ts + var width + var wrapWidth + + rrows.forEach(function (rrow, r) { + str = '' + rrow.forEach(function (col, c) { + ts = '' // temporary string used during alignment/padding. + width = row[c].width // the width with padding. + wrapWidth = _this._negatePadding(row[c]) // the width without padding. + + ts += col + + for (var i = 0; i < wrapWidth - stringWidth(col); i++) { + ts += ' ' + } + + // align the string within its column. + if (row[c].align && row[c].align !== 'left' && _this.wrap) { + ts = align[row[c].align](ts, wrapWidth) + if (stringWidth(ts) < wrapWidth) ts += new Array(width - stringWidth(ts)).join(' ') + } + + // apply border and padding to string. + padding = row[c].padding || [0, 0, 0, 0] + if (padding[left]) str += new Array(padding[left] + 1).join(' ') + str += addBorder(row[c], ts, '| ') + str += ts + str += addBorder(row[c], ts, ' |') + if (padding[right]) str += new Array(padding[right] + 1).join(' ') + + // if prior row is span, try to render the + // current row on the prior line. + if (r === 0 && lines.length > 0) { + str = _this._renderInline(str, lines[lines.length - 1]) + } + }) + + // remove trailing whitespace. + lines.push({ + text: str.replace(/ +$/, ''), + span: row.span + }) + }) + + return lines +} + +function addBorder (col, ts, style) { + if (col.border) { + if (/[.']-+[.']/.test(ts)) return '' + else if (ts.trim().length) return style + else return ' ' + } + return '' +} + +// if the full 'source' can render in +// the target line, do so. +UI.prototype._renderInline = function (source, previousLine) { + var leadingWhitespace = source.match(/^ */)[0].length + var target = previousLine.text + var targetTextWidth = stringWidth(target.trimRight()) + + if (!previousLine.span) return source + + // if we're not applying wrapping logic, + // just always append to the span. + if (!this.wrap) { + previousLine.hidden = true + return target + source + } + + if (leadingWhitespace < targetTextWidth) return source + + previousLine.hidden = true + + return target.trimRight() + new Array(leadingWhitespace - targetTextWidth + 1).join(' ') + source.trimLeft() +} + +UI.prototype._rasterize = function (row) { + var _this = this + var i + var rrow + var rrows = [] + var widths = this._columnWidths(row) + var wrapped + + // word wrap all columns, and create + // a data-structure that is easy to rasterize. + row.forEach(function (col, c) { + // leave room for left and right padding. + col.width = widths[c] + if (_this.wrap) wrapped = wrap(col.text, _this._negatePadding(col), { hard: true }).split('\n') + else wrapped = col.text.split('\n') + + if (col.border) { + wrapped.unshift('.' + new Array(_this._negatePadding(col) + 3).join('-') + '.') + wrapped.push("'" + new Array(_this._negatePadding(col) + 3).join('-') + "'") + } + + // add top and bottom padding. + if (col.padding) { + for (i = 0; i < (col.padding[top] || 0); i++) wrapped.unshift('') + for (i = 0; i < (col.padding[bottom] || 0); i++) wrapped.push('') + } + + wrapped.forEach(function (str, r) { + if (!rrows[r]) rrows.push([]) + + rrow = rrows[r] + + for (var i = 0; i < c; i++) { + if (rrow[i] === undefined) rrow.push('') + } + rrow.push(str) + }) + }) + + return rrows +} + +UI.prototype._negatePadding = function (col) { + var wrapWidth = col.width + if (col.padding) wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0) + if (col.border) wrapWidth -= 4 + return wrapWidth +} + +UI.prototype._columnWidths = function (row) { + var _this = this + var widths = [] + var unset = row.length + var unsetWidth + var remainingWidth = this.width + + // column widths can be set in config. + row.forEach(function (col, i) { + if (col.width) { + unset-- + widths[i] = col.width + remainingWidth -= col.width + } else { + widths[i] = undefined + } + }) + + // any unset widths should be calculated. + if (unset) unsetWidth = Math.floor(remainingWidth / unset) + widths.forEach(function (w, i) { + if (!_this.wrap) widths[i] = row[i].width || stringWidth(row[i].text) + else if (w === undefined) widths[i] = Math.max(unsetWidth, _minWidth(row[i])) + }) + + return widths +} + +// calculates the minimum width of +// a column, based on padding preferences. +function _minWidth (col) { + var padding = col.padding || [] + var minWidth = 1 + (padding[left] || 0) + (padding[right] || 0) + if (col.border) minWidth += 4 + return minWidth +} + +function getWindowWidth () { + if (typeof process === 'object' && process.stdout && process.stdout.columns) return process.stdout.columns +} + +function alignRight (str, width) { + str = str.trim() + var padding = '' + var strWidth = stringWidth(str) + + if (strWidth < width) { + padding = new Array(width - strWidth + 1).join(' ') + } + + return padding + str +} + +function alignCenter (str, width) { + str = str.trim() + var padding = '' + var strWidth = stringWidth(str.trim()) + + if (strWidth < width) { + padding = new Array(parseInt((width - strWidth) / 2, 10) + 1).join(' ') + } + + return padding + str +} + +module.exports = function (opts) { + opts = opts || {} + + return new UI({ + width: (opts || {}).width || getWindowWidth() || 80, + wrap: typeof opts.wrap === 'boolean' ? opts.wrap : true + }) +} + + +/***/ }), + +/***/ 2879: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* MIT license */ +var cssKeywords = __webpack_require__(8682); + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +var reverseKeywords = {}; +for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } +} + +var convert = module.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +// hide .channels and .labels properties +for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } +} + +convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; +}; + +convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +/** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ +function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); +} + +convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; +}; + +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; + +convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; +}; + +convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; +}; + +convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; + +convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; +}; + +convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; +}; + +convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + + return [l, c, h]; +}; + +convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + + return [l, a, b]; +}; + +convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; +}; + +convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; + +convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; +}; + +convert.ansi16.rgb = function (args) { + var color = args % 10; + + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; +}; + +convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; + + return [r, g, b]; +}; + +convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; + + return [r, g, b]; +}; + +convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = (max - min); + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; +}; + +convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; +}; + +convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; + +convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = (h % 1) * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; + +convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; +}; + +convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; +}; + +convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; + +convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; +}; + +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; + +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; + +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; +}; + +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; + + +/***/ }), + +/***/ 2913: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var conversions = __webpack_require__(2879); +var route = __webpack_require__(410); + +var convert = {}; + +var models = Object.keys(conversions); + +function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); + + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models.forEach(function (fromModel) { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + var routes = route(fromModel); + var routeModels = Object.keys(routes); + + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); + +module.exports = convert; + + +/***/ }), + +/***/ 410: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var conversions = __webpack_require__(2879); + +/* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +module.exports = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; + + + +/***/ }), + +/***/ 8682: +/***/ ((module) => { + +"use strict"; + + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; + + +/***/ }), + +/***/ 5763: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const path = __webpack_require__(5622); +const locatePath = __webpack_require__(4093); + +module.exports = (filename, opts = {}) => { + const startDir = path.resolve(opts.cwd || ''); + const {root} = path.parse(startDir); + + const filenames = [].concat(filename); + + return new Promise(resolve => { + (function find(dir) { + locatePath(filenames, {cwd: dir}).then(file => { + if (file) { + resolve(path.join(dir, file)); + } else if (dir === root) { + resolve(null); + } else { + find(path.dirname(dir)); + } + }); + })(startDir); + }); +}; + +module.exports.sync = (filename, opts = {}) => { + let dir = path.resolve(opts.cwd || ''); + const {root} = path.parse(dir); + + const filenames = [].concat(filename); + + // eslint-disable-next-line no-constant-condition + while (true) { + const file = locatePath.sync(filenames, {cwd: dir}); + + if (file) { + return path.join(dir, file); + } + + if (dir === root) { + return null; + } + + dir = path.dirname(dir); + } +}; + + +/***/ }), + +/***/ 4093: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const path = __webpack_require__(5622); +const pathExists = __webpack_require__(5019); +const pLocate = __webpack_require__(4040); + +module.exports = (iterable, options) => { + options = Object.assign({ + cwd: process.cwd() + }, options); + + return pLocate(iterable, el => pathExists(path.resolve(options.cwd, el)), options); +}; + +module.exports.sync = (iterable, options) => { + options = Object.assign({ + cwd: process.cwd() + }, options); + + for (const el of iterable) { + if (pathExists.sync(path.resolve(options.cwd, el))) { + return el; + } + } +}; + + +/***/ }), + +/***/ 4040: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const pLimit = __webpack_require__(7684); + +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} + +// The input can also be a promise, so we `Promise.resolve()` it +const testElement = (el, tester) => Promise.resolve(el).then(tester); + +// The input can also be a promise, so we `Promise.all()` them both +const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0]))); + +module.exports = (iterable, tester, opts) => { + opts = Object.assign({ + concurrency: Infinity, + preserveOrder: true + }, opts); + + const limit = pLimit(opts.concurrency); + + // Start all the promises concurrently with optional limit + const items = [...iterable].map(el => [el, limit(testElement, el, tester)]); + + // Check the promises either serially or concurrently + const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity); + + return Promise.all(items.map(el => checkLimit(finder, el))) + .then(() => {}) + .catch(err => err instanceof EndError ? err.value : Promise.reject(err)); +}; + + +/***/ }), + +/***/ 5019: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const fs = __webpack_require__(5747); + +module.exports = fp => new Promise(resolve => { + fs.access(fp, err => { + resolve(!err); + }); +}); + +module.exports.sync = fp => { + try { + fs.accessSync(fp); + return true; + } catch (err) { + return false; + } +}; + + +/***/ }), + +/***/ 4133: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const ansiRegex = __webpack_require__(6255); + +const stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; + +module.exports = stripAnsi; +module.exports.default = stripAnsi; + + +/***/ }), + +/***/ 1971: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const stringWidth = __webpack_require__(2577); +const stripAnsi = __webpack_require__(4133); +const ansiStyles = __webpack_require__(1328); + +const ESCAPES = new Set([ + '\u001B', + '\u009B' +]); + +const END_CODE = 39; + +const wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`; + +// Calculate the length of words split on ' ', ignoring +// the extra characters added by ansi escape codes +const wordLengths = string => string.split(' ').map(character => stringWidth(character)); + +// Wrap a long word across multiple rows +// Ansi escape codes do not count towards length +const wrapWord = (rows, word, columns) => { + const characters = [...word]; + + let insideEscape = false; + let visible = stringWidth(stripAnsi(rows[rows.length - 1])); + + for (const [index, character] of characters.entries()) { + const characterLength = stringWidth(character); + + if (visible + characterLength <= columns) { + rows[rows.length - 1] += character; + } else { + rows.push(character); + visible = 0; + } + + if (ESCAPES.has(character)) { + insideEscape = true; + } else if (insideEscape && character === 'm') { + insideEscape = false; + continue; + } + + if (insideEscape) { + continue; + } + + visible += characterLength; + + if (visible === columns && index < characters.length - 1) { + rows.push(''); + visible = 0; + } + } + + // It's possible that the last row we copy over is only + // ansi escape characters, handle this edge-case + if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { + rows[rows.length - 2] += rows.pop(); + } +}; + +// Trims spaces from a string ignoring invisible sequences +const stringVisibleTrimSpacesRight = str => { + const words = str.split(' '); + let last = words.length; + + while (last > 0) { + if (stringWidth(words[last - 1]) > 0) { + break; + } + + last--; + } + + if (last === words.length) { + return str; + } + + return words.slice(0, last).join(' ') + words.slice(last).join(''); +}; + +// The wrap-ansi module can be invoked +// in either 'hard' or 'soft' wrap mode +// +// 'hard' will never allow a string to take up more +// than columns characters +// +// 'soft' allows long words to expand past the column length +const exec = (string, columns, options = {}) => { + if (options.trim !== false && string.trim() === '') { + return ''; + } + + let pre = ''; + let ret = ''; + let escapeCode; + + const lengths = wordLengths(string); + let rows = ['']; + + for (const [index, word] of string.split(' ').entries()) { + if (options.trim !== false) { + rows[rows.length - 1] = rows[rows.length - 1].trimLeft(); + } + + let rowLength = stringWidth(rows[rows.length - 1]); + + if (index !== 0) { + if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { + // If we start with a new word but the current row length equals the length of the columns, add a new row + rows.push(''); + rowLength = 0; + } + + if (rowLength > 0 || options.trim === false) { + rows[rows.length - 1] += ' '; + rowLength++; + } + } + + // In 'hard' wrap mode, the length of a line is + // never allowed to extend past 'columns' + if (options.hard && lengths[index] > columns) { + const remainingColumns = (columns - rowLength); + const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); + const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); + if (breaksStartingNextLine < breaksStartingThisLine) { + rows.push(''); + } + + wrapWord(rows, word, columns); + continue; + } + + if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { + if (options.wordWrap === false && rowLength < columns) { + wrapWord(rows, word, columns); + continue; + } + + rows.push(''); + } + + if (rowLength + lengths[index] > columns && options.wordWrap === false) { + wrapWord(rows, word, columns); + continue; + } + + rows[rows.length - 1] += word; + } + + if (options.trim !== false) { + rows = rows.map(stringVisibleTrimSpacesRight); + } + + pre = rows.join('\n'); + + for (const [index, character] of [...pre].entries()) { + ret += character; + + if (ESCAPES.has(character)) { + const code = parseFloat(/\d[^m]*/.exec(pre.slice(index, index + 4))); + escapeCode = code === END_CODE ? null : code; + } + + const code = ansiStyles.codes.get(Number(escapeCode)); + + if (escapeCode && code) { + if (pre[index + 1] === '\n') { + ret += wrapAnsi(code); + } else if (character === '\n') { + ret += wrapAnsi(escapeCode); + } + } + } + + return ret; +}; + +// For each newline, invoke the method separately +module.exports = (string, columns, options) => { + return String(string) + .normalize() + .split('\n') + .map(line => exec(line, columns, options)) + .join('\n'); +}; + + +/***/ }), + +/***/ 871: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var camelCase = __webpack_require__(1362) +var decamelize = __webpack_require__(159) +var path = __webpack_require__(5622) +var tokenizeArgString = __webpack_require__(6003) +var util = __webpack_require__(1669) + +function parse (args, opts) { + if (!opts) opts = {} + // allow a string argument to be passed in rather + // than an argv array. + args = tokenizeArgString(args) + + // aliases might have transitive relationships, normalize this. + var aliases = combineAliases(opts.alias || {}) + var configuration = Object.assign({ + 'short-option-groups': true, + 'camel-case-expansion': true, + 'dot-notation': true, + 'parse-numbers': true, + 'boolean-negation': true, + 'negation-prefix': 'no-', + 'duplicate-arguments-array': true, + 'flatten-duplicate-arrays': true, + 'populate--': false, + 'combine-arrays': false, + 'set-placeholder-key': false, + 'halt-at-non-option': false, + 'strip-aliased': false, + 'strip-dashed': false + }, opts.configuration) + var defaults = opts.default || {} + var configObjects = opts.configObjects || [] + var envPrefix = opts.envPrefix + var notFlagsOption = configuration['populate--'] + var notFlagsArgv = notFlagsOption ? '--' : '_' + var newAliases = {} + // allow a i18n handler to be passed in, default to a fake one (util.format). + var __ = opts.__ || util.format + var error = null + var flags = { + aliases: {}, + arrays: {}, + bools: {}, + strings: {}, + numbers: {}, + counts: {}, + normalize: {}, + configs: {}, + defaulted: {}, + nargs: {}, + coercions: {}, + keys: [] + } + var negative = /^-[0-9]+(\.[0-9]+)?/ + var negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)') + + ;[].concat(opts.array).filter(Boolean).forEach(function (opt) { + var key = opt.key || opt + + // assign to flags[bools|strings|numbers] + const assignment = Object.keys(opt).map(function (key) { + return ({ + boolean: 'bools', + string: 'strings', + number: 'numbers' + })[key] + }).filter(Boolean).pop() + + // assign key to be coerced + if (assignment) { + flags[assignment][key] = true + } + + flags.arrays[key] = true + flags.keys.push(key) + }) + + ;[].concat(opts.boolean).filter(Boolean).forEach(function (key) { + flags.bools[key] = true + flags.keys.push(key) + }) + + ;[].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true + flags.keys.push(key) + }) + + ;[].concat(opts.number).filter(Boolean).forEach(function (key) { + flags.numbers[key] = true + flags.keys.push(key) + }) + + ;[].concat(opts.count).filter(Boolean).forEach(function (key) { + flags.counts[key] = true + flags.keys.push(key) + }) + + ;[].concat(opts.normalize).filter(Boolean).forEach(function (key) { + flags.normalize[key] = true + flags.keys.push(key) + }) + + Object.keys(opts.narg || {}).forEach(function (k) { + flags.nargs[k] = opts.narg[k] + flags.keys.push(k) + }) + + Object.keys(opts.coerce || {}).forEach(function (k) { + flags.coercions[k] = opts.coerce[k] + flags.keys.push(k) + }) + + if (Array.isArray(opts.config) || typeof opts.config === 'string') { + ;[].concat(opts.config).filter(Boolean).forEach(function (key) { + flags.configs[key] = true + }) + } else { + Object.keys(opts.config || {}).forEach(function (k) { + flags.configs[k] = opts.config[k] + }) + } + + // create a lookup table that takes into account all + // combinations of aliases: {f: ['foo'], foo: ['f']} + extendAliases(opts.key, aliases, opts.default, flags.arrays) + + // apply default values to all aliases. + Object.keys(defaults).forEach(function (key) { + (flags.aliases[key] || []).forEach(function (alias) { + defaults[alias] = defaults[key] + }) + }) + + var argv = { _: [] } + + Object.keys(flags.bools).forEach(function (key) { + if (Object.prototype.hasOwnProperty.call(defaults, key)) { + setArg(key, defaults[key]) + setDefaulted(key) + } + }) + + var notFlags = [] + + for (var i = 0; i < args.length; i++) { + var arg = args[i] + var broken + var key + var letters + var m + var next + var value + + // -- separated by = + if (arg.match(/^--.+=/) || ( + !configuration['short-option-groups'] && arg.match(/^-.+=/) + )) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + m = arg.match(/^--?([^=]+)=([\s\S]*)$/) + + // nargs format = '--f=monkey washing cat' + if (checkAllAliases(m[1], flags.nargs)) { + args.splice(i + 1, 0, m[2]) + i = eatNargs(i, m[1], args) + // arrays format = '--f=a b c' + } else if (checkAllAliases(m[1], flags.arrays) && args.length > i + 1) { + args.splice(i + 1, 0, m[2]) + i = eatArray(i, m[1], args) + } else { + setArg(m[1], m[2]) + } + } else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { + key = arg.match(negatedBoolean)[1] + setArg(key, false) + + // -- seperated by space. + } else if (arg.match(/^--.+/) || ( + !configuration['short-option-groups'] && arg.match(/^-[^-]+/) + )) { + key = arg.match(/^--?(.+)/)[1] + + // nargs format = '--foo a b c' + if (checkAllAliases(key, flags.nargs)) { + i = eatNargs(i, key, args) + // array format = '--foo a b c' + } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) { + i = eatArray(i, key, args) + } else { + next = flags.nargs[key] === 0 ? undefined : args[i + 1] + + if (next !== undefined && (!next.match(/^-/) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next) + i++ + } else if (/^(true|false)$/.test(next)) { + setArg(key, next) + i++ + } else { + setArg(key, defaultValue(key)) + } + } + + // dot-notation flag seperated by '='. + } else if (arg.match(/^-.\..+=/)) { + m = arg.match(/^-([^=]+)=([\s\S]*)$/) + setArg(m[1], m[2]) + + // dot-notation flag seperated by space. + } else if (arg.match(/^-.\..+/)) { + next = args[i + 1] + key = arg.match(/^-(.\..+)/)[1] + + if (next !== undefined && !next.match(/^-/) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next) + i++ + } else { + setArg(key, defaultValue(key)) + } + } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { + letters = arg.slice(1, -1).split('') + broken = false + + for (var j = 0; j < letters.length; j++) { + next = arg.slice(j + 2) + + if (letters[j + 1] && letters[j + 1] === '=') { + value = arg.slice(j + 3) + key = letters[j] + + // nargs format = '-f=monkey washing cat' + if (checkAllAliases(key, flags.nargs)) { + args.splice(i + 1, 0, value) + i = eatNargs(i, key, args) + // array format = '-f=a b c' + } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) { + args.splice(i + 1, 0, value) + i = eatArray(i, key, args) + } else { + setArg(key, value) + } + + broken = true + break + } + + if (next === '-') { + setArg(letters[j], next) + continue + } + + // current letter is an alphabetic character and next value is a number + if (/[A-Za-z]/.test(letters[j]) && + /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next) + broken = true + break + } + + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], next) + broken = true + break + } else { + setArg(letters[j], defaultValue(letters[j])) + } + } + + key = arg.slice(-1)[0] + + if (!broken && key !== '-') { + // nargs format = '-f a b c' + if (checkAllAliases(key, flags.nargs)) { + i = eatNargs(i, key, args) + // array format = '-f a b c' + } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) { + i = eatArray(i, key, args) + } else { + next = args[i + 1] + + if (next !== undefined && (!/^(-|--)[^-]/.test(next) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next) + i++ + } else if (/^(true|false)$/.test(next)) { + setArg(key, next) + i++ + } else { + setArg(key, defaultValue(key)) + } + } + } + } else if (arg === '--') { + notFlags = args.slice(i + 1) + break + } else if (configuration['halt-at-non-option']) { + notFlags = args.slice(i) + break + } else { + argv._.push(maybeCoerceNumber('_', arg)) + } + } + + // order of precedence: + // 1. command line arg + // 2. value from env var + // 3. value from config file + // 4. value from config objects + // 5. configured default value + applyEnvVars(argv, true) // special case: check env vars that point to config file + applyEnvVars(argv, false) + setConfig(argv) + setConfigObjects() + applyDefaultsAndAliases(argv, flags.aliases, defaults) + applyCoercions(argv) + if (configuration['set-placeholder-key']) setPlaceholderKeys(argv) + + // for any counts either not in args or without an explicit default, set to 0 + Object.keys(flags.counts).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) setArg(key, 0) + }) + + // '--' defaults to undefined. + if (notFlagsOption && notFlags.length) argv[notFlagsArgv] = [] + notFlags.forEach(function (key) { + argv[notFlagsArgv].push(key) + }) + + if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { + Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { + delete argv[key] + }) + } + + if (configuration['strip-aliased']) { + // XXX Switch to [].concat(...Object.values(aliases)) once node.js 6 is dropped + ;[].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { + if (configuration['camel-case-expansion']) { + delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')] + } + + delete argv[alias] + }) + } + + // how many arguments should we consume, based + // on the nargs option? + function eatNargs (i, key, args) { + var ii + const toEat = checkAllAliases(key, flags.nargs) + + // nargs will not consume flag arguments, e.g., -abc, --foo, + // and terminates when one is observed. + var available = 0 + for (ii = i + 1; ii < args.length; ii++) { + if (!args[ii].match(/^-[^0-9]/)) available++ + else break + } + + if (available < toEat) error = Error(__('Not enough arguments following: %s', key)) + + const consumed = Math.min(available, toEat) + for (ii = i + 1; ii < (consumed + i + 1); ii++) { + setArg(key, args[ii]) + } + + return (i + consumed) + } + + // if an option is an array, eat all non-hyphenated arguments + // following it... YUM! + // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] + function eatArray (i, key, args) { + var start = i + 1 + var argsToSet = [] + var multipleArrayFlag = i > 0 + for (var ii = i + 1; ii < args.length; ii++) { + if (/^-/.test(args[ii]) && !negative.test(args[ii])) { + if (ii === start) { + setArg(key, defaultForType('array')) + } + multipleArrayFlag = true + break + } + i = ii + argsToSet.push(args[ii]) + } + if (multipleArrayFlag) { + setArg(key, argsToSet.map(function (arg) { + return processValue(key, arg) + })) + } else { + argsToSet.forEach(function (arg) { + setArg(key, arg) + }) + } + + return i + } + + function setArg (key, val) { + unsetDefaulted(key) + + if (/-/.test(key) && configuration['camel-case-expansion']) { + var alias = key.split('.').map(function (prop) { + return camelCase(prop) + }).join('.') + addNewAlias(key, alias) + } + + var value = processValue(key, val) + + var splitKey = key.split('.') + setKey(argv, splitKey, value) + + // handle populating aliases of the full key + if (flags.aliases[key] && flags.aliases[key].forEach) { + flags.aliases[key].forEach(function (x) { + x = x.split('.') + setKey(argv, x, value) + }) + } + + // handle populating aliases of the first element of the dot-notation key + if (splitKey.length > 1 && configuration['dot-notation']) { + ;(flags.aliases[splitKey[0]] || []).forEach(function (x) { + x = x.split('.') + + // expand alias with nested objects in key + var a = [].concat(splitKey) + a.shift() // nuke the old key. + x = x.concat(a) + + setKey(argv, x, value) + }) + } + + // Set normalize getter and setter when key is in 'normalize' but isn't an array + if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { + var keys = [key].concat(flags.aliases[key] || []) + keys.forEach(function (key) { + argv.__defineSetter__(key, function (v) { + val = path.normalize(v) + }) + + argv.__defineGetter__(key, function () { + return typeof val === 'string' ? path.normalize(val) : val + }) + }) + } + } + + function addNewAlias (key, alias) { + if (!(flags.aliases[key] && flags.aliases[key].length)) { + flags.aliases[key] = [alias] + newAliases[alias] = true + } + if (!(flags.aliases[alias] && flags.aliases[alias].length)) { + addNewAlias(alias, key) + } + } + + function processValue (key, val) { + // strings may be quoted, clean this up as we assign values. + if (typeof val === 'string' && + (val[0] === "'" || val[0] === '"') && + val[val.length - 1] === val[0] + ) { + val = val.substring(1, val.length - 1) + } + + // handle parsing boolean arguments --foo=true --bar false. + if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { + if (typeof val === 'string') val = val === 'true' + } + + var value = maybeCoerceNumber(key, val) + + // increment a count given as arg (either no value or value parsed as boolean) + if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { + value = increment + } + + // Set normalized value when key is in 'normalize' and in 'arrays' + if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { + if (Array.isArray(val)) value = val.map(path.normalize) + else value = path.normalize(val) + } + return value + } + + function maybeCoerceNumber (key, value) { + if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.coercions)) { + const shouldCoerceNumber = isNumber(value) && configuration['parse-numbers'] && ( + Number.isSafeInteger(Math.floor(value)) + ) + if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) value = Number(value) + } + return value + } + + // set args from config.json file, this should be + // applied last so that defaults can be applied. + function setConfig (argv) { + var configLookup = {} + + // expand defaults/aliases, in-case any happen to reference + // the config.json file. + applyDefaultsAndAliases(configLookup, flags.aliases, defaults) + + Object.keys(flags.configs).forEach(function (configKey) { + var configPath = argv[configKey] || configLookup[configKey] + if (configPath) { + try { + var config = null + var resolvedConfigPath = path.resolve(process.cwd(), configPath) + + if (typeof flags.configs[configKey] === 'function') { + try { + config = flags.configs[configKey](resolvedConfigPath) + } catch (e) { + config = e + } + if (config instanceof Error) { + error = config + return + } + } else { + config = require(resolvedConfigPath) + } + + setConfigObject(config) + } catch (ex) { + if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath)) + } + } + }) + } + + // set args from config object. + // it recursively checks nested objects. + function setConfigObject (config, prev) { + Object.keys(config).forEach(function (key) { + var value = config[key] + var fullKey = prev ? prev + '.' + key : key + + // if the value is an inner object and we have dot-notation + // enabled, treat inner objects in config the same as + // heavily nested dot notations (foo.bar.apple). + if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { + // if the value is an object but not an array, check nested object + setConfigObject(value, fullKey) + } else { + // setting arguments via CLI takes precedence over + // values within the config file. + if (!hasKey(argv, fullKey.split('.')) || (flags.defaulted[fullKey]) || (flags.arrays[fullKey] && configuration['combine-arrays'])) { + setArg(fullKey, value) + } + } + }) + } + + // set all config objects passed in opts + function setConfigObjects () { + if (typeof configObjects === 'undefined') return + configObjects.forEach(function (configObject) { + setConfigObject(configObject) + }) + } + + function applyEnvVars (argv, configOnly) { + if (typeof envPrefix === 'undefined') return + + var prefix = typeof envPrefix === 'string' ? envPrefix : '' + Object.keys(process.env).forEach(function (envVar) { + if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { + // get array of nested keys and convert them to camel case + var keys = envVar.split('__').map(function (key, i) { + if (i === 0) { + key = key.substring(prefix.length) + } + return camelCase(key) + }) + + if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && (!hasKey(argv, keys) || flags.defaulted[keys.join('.')])) { + setArg(keys.join('.'), process.env[envVar]) + } + } + }) + } + + function applyCoercions (argv) { + var coerce + var applied = {} + Object.keys(argv).forEach(function (key) { + if (!applied.hasOwnProperty(key)) { // If we haven't already coerced this option via one of its aliases + coerce = checkAllAliases(key, flags.coercions) + if (typeof coerce === 'function') { + try { + var value = coerce(argv[key]) + ;([].concat(flags.aliases[key] || [], key)).forEach(ali => { + applied[ali] = argv[ali] = value + }) + } catch (err) { + error = err + } + } + } + }) + } + + function setPlaceholderKeys (argv) { + flags.keys.forEach((key) => { + // don't set placeholder keys for dot notation options 'foo.bar'. + if (~key.indexOf('.')) return + if (typeof argv[key] === 'undefined') argv[key] = undefined + }) + return argv + } + + function applyDefaultsAndAliases (obj, aliases, defaults) { + Object.keys(defaults).forEach(function (key) { + if (!hasKey(obj, key.split('.'))) { + setKey(obj, key.split('.'), defaults[key]) + + ;(aliases[key] || []).forEach(function (x) { + if (hasKey(obj, x.split('.'))) return + setKey(obj, x.split('.'), defaults[key]) + }) + } + }) + } + + function hasKey (obj, keys) { + var o = obj + + if (!configuration['dot-notation']) keys = [keys.join('.')] + + keys.slice(0, -1).forEach(function (key) { + o = (o[key] || {}) + }) + + var key = keys[keys.length - 1] + + if (typeof o !== 'object') return false + else return key in o + } + + function setKey (obj, keys, value) { + var o = obj + + if (!configuration['dot-notation']) keys = [keys.join('.')] + + keys.slice(0, -1).forEach(function (key, index) { + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + key = sanitizeKey(key) + + if (typeof o === 'object' && o[key] === undefined) { + o[key] = {} + } + + if (typeof o[key] !== 'object' || Array.isArray(o[key])) { + // ensure that o[key] is an array, and that the last item is an empty object. + if (Array.isArray(o[key])) { + o[key].push({}) + } else { + o[key] = [o[key], {}] + } + + // we want to update the empty object at the end of the o[key] array, so set o to that object + o = o[key][o[key].length - 1] + } else { + o = o[key] + } + }) + + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + const key = sanitizeKey(keys[keys.length - 1]) + + const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays) + const isValueArray = Array.isArray(value) + let duplicate = configuration['duplicate-arguments-array'] + + // nargs has higher priority than duplicate + if (!duplicate && checkAllAliases(key, flags.nargs)) { + duplicate = true + if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { + o[key] = undefined + } + } + + if (value === increment) { + o[key] = increment(o[key]) + } else if (Array.isArray(o[key])) { + if (duplicate && isTypeArray && isValueArray) { + o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]) + } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { + o[key] = value + } else { + o[key] = o[key].concat([value]) + } + } else if (o[key] === undefined && isTypeArray) { + o[key] = isValueArray ? value : [value] + } else if (duplicate && !(o[key] === undefined || checkAllAliases(key, flags.bools) || checkAllAliases(keys.join('.'), flags.bools) || checkAllAliases(key, flags.counts))) { + o[key] = [ o[key], value ] + } else { + o[key] = value + } + } + + // extend the aliases list with inferred aliases. + function extendAliases (...args) { + args.forEach(function (obj) { + Object.keys(obj || {}).forEach(function (key) { + // short-circuit if we've already added a key + // to the aliases array, for example it might + // exist in both 'opts.default' and 'opts.key'. + if (flags.aliases[key]) return + + flags.aliases[key] = [].concat(aliases[key] || []) + // For "--option-name", also set argv.optionName + flags.aliases[key].concat(key).forEach(function (x) { + if (/-/.test(x) && configuration['camel-case-expansion']) { + var c = camelCase(x) + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c) + newAliases[c] = true + } + } + }) + // For "--optionName", also set argv['option-name'] + flags.aliases[key].concat(key).forEach(function (x) { + if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { + var c = decamelize(x, '-') + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c) + newAliases[c] = true + } + } + }) + flags.aliases[key].forEach(function (x) { + flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { + return x !== y + })) + }) + }) + }) + } + + // check if a flag is set for any of a key's aliases. + function checkAllAliases (key, flag) { + var isSet = false + var toCheck = [].concat(flags.aliases[key] || [], key) + + toCheck.forEach(function (key) { + if (flag[key]) isSet = flag[key] + }) + + return isSet + } + + function setDefaulted (key) { + [].concat(flags.aliases[key] || [], key).forEach(function (k) { + flags.defaulted[k] = true + }) + } + + function unsetDefaulted (key) { + [].concat(flags.aliases[key] || [], key).forEach(function (k) { + delete flags.defaulted[k] + }) + } + + // make a best effor to pick a default value + // for an option based on name and type. + function defaultValue (key) { + if (!checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts) && + `${key}` in defaults) { + return defaults[key] + } else { + return defaultForType(guessType(key)) + } + } + + // return a default value, given the type of a flag., + // e.g., key of type 'string' will default to '', rather than 'true'. + function defaultForType (type) { + var def = { + boolean: true, + string: '', + number: undefined, + array: [] + } + + return def[type] + } + + // given a flag, enforce a default type. + function guessType (key) { + var type = 'boolean' + + if (checkAllAliases(key, flags.strings)) type = 'string' + else if (checkAllAliases(key, flags.numbers)) type = 'number' + else if (checkAllAliases(key, flags.arrays)) type = 'array' + + return type + } + + function isNumber (x) { + if (x === null || x === undefined) return false + // if loaded from config, may already be a number. + if (typeof x === 'number') return true + // hexadecimal. + if (/^0x[0-9a-f]+$/i.test(x)) return true + // don't treat 0123 as a number; as it drops the leading '0'. + if (x.length > 1 && x[0] === '0') return false + return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x) + } + + function isUndefined (num) { + return num === undefined + } + + return { + argv: argv, + error: error, + aliases: flags.aliases, + newAliases: newAliases, + configuration: configuration + } +} + +// if any aliases reference each other, we should +// merge them together. +function combineAliases (aliases) { + var aliasArrays = [] + var change = true + var combined = {} + + // turn alias lookup hash {key: ['alias1', 'alias2']} into + // a simple array ['key', 'alias1', 'alias2'] + Object.keys(aliases).forEach(function (key) { + aliasArrays.push( + [].concat(aliases[key], key) + ) + }) + + // combine arrays until zero changes are + // made in an iteration. + while (change) { + change = false + for (var i = 0; i < aliasArrays.length; i++) { + for (var ii = i + 1; ii < aliasArrays.length; ii++) { + var intersect = aliasArrays[i].filter(function (v) { + return aliasArrays[ii].indexOf(v) !== -1 + }) + + if (intersect.length) { + aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]) + aliasArrays.splice(ii, 1) + change = true + break + } + } + } + } + + // map arrays back to the hash-lookup (de-dupe while + // we're at it). + aliasArrays.forEach(function (aliasArray) { + aliasArray = aliasArray.filter(function (v, i, self) { + return self.indexOf(v) === i + }) + combined[aliasArray.pop()] = aliasArray + }) + + return combined +} + +// this function should only be called when a count is given as an arg +// it is NOT called to set a default value +// thus we can start the count at 1 instead of 0 +function increment (orig) { + return orig !== undefined ? orig + 1 : 1 +} + +function Parser (args, opts) { + var result = parse(args.slice(), opts) + + return result.argv +} + +// parse arguments and return detailed +// meta information, aliases, etc. +Parser.detailed = function (args, opts) { + return parse(args.slice(), opts) +} + +// TODO(bcoe): in the next major version of yargs, switch to +// Object.create(null) for dot notation: +function sanitizeKey (key) { + if (key === '__proto__') return '___proto___' + return key +} + +module.exports = Parser + + +/***/ }), + +/***/ 6003: +/***/ ((module) => { + +// take an un-split argv string and tokenize it. +module.exports = function (argString) { + if (Array.isArray(argString)) { + return argString.map(e => typeof e !== 'string' ? e + '' : e) + } + + argString = argString.trim() + + var i = 0 + var prevC = null + var c = null + var opening = null + var args = [] + + for (var ii = 0; ii < argString.length; ii++) { + prevC = c + c = argString.charAt(ii) + + // split on spaces unless we're in quotes. + if (c === ' ' && !opening) { + if (!(prevC === ' ')) { + i++ + } + continue + } + + // don't split the string if we're in matching + // opening or closing single and double quotes. + if (c === opening) { + opening = null + } else if ((c === "'" || c === '"') && !opening) { + opening = c + } + + if (!args[i]) args[i] = '' + args[i] += c + } + + return args +} + + +/***/ }), + +/***/ 5804: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +// classic singleton yargs API, to use yargs +// without running as a singleton do: +// require('yargs/yargs')(process.argv.slice(2)) +const yargs = __webpack_require__(2180) + +Argv(process.argv.slice(2)) + +module.exports = Argv + +function Argv (processArgs, cwd) { + const argv = yargs(processArgs, cwd, require) + singletonify(argv) + return argv +} + +/* Hack an instance of Argv with process.argv into Argv + so people can do + require('yargs')(['--beeble=1','-z','zizzle']).argv + to parse a list of args and + require('yargs').argv + to get a parsed version of process.argv. +*/ +function singletonify (inst) { + Object.keys(inst).forEach((key) => { + if (key === 'argv') { + Argv.__defineGetter__(key, inst.__lookupGetter__(key)) + } else { + Argv[key] = typeof inst[key] === 'function' ? inst[key].bind(inst) : inst[key] + } + }) +} + + +/***/ }), + +/***/ 5493: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const fs = __webpack_require__(5747) +const path = __webpack_require__(5622) +const YError = __webpack_require__(4401) + +let previouslyVisitedConfigs = [] + +function checkForCircularExtends (cfgPath) { + if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) { + throw new YError(`Circular extended configurations: '${cfgPath}'.`) + } +} + +function getPathToDefaultConfig (cwd, pathToExtend) { + return path.resolve(cwd, pathToExtend) +} + +function applyExtends (config, cwd) { + let defaultConfig = {} + + if (config.hasOwnProperty('extends')) { + if (typeof config.extends !== 'string') return defaultConfig + const isPath = /\.json|\..*rc$/.test(config.extends) + let pathToDefault = null + if (!isPath) { + try { + pathToDefault = require.resolve(config.extends) + } catch (err) { + // most likely this simply isn't a module. + } + } else { + pathToDefault = getPathToDefaultConfig(cwd, config.extends) + } + // maybe the module uses key for some other reason, + // err on side of caution. + if (!pathToDefault && !isPath) return config + + checkForCircularExtends(pathToDefault) + + previouslyVisitedConfigs.push(pathToDefault) + + defaultConfig = isPath ? JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) : require(config.extends) + delete config.extends + defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault)) + } + + previouslyVisitedConfigs = [] + + return Object.assign({}, defaultConfig, config) +} + +module.exports = applyExtends + + +/***/ }), + +/***/ 1206: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// hoisted due to circular dependency on command. +module.exports = argsert +const command = __webpack_require__(3810)() +const YError = __webpack_require__(4401) + +const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'] +function argsert (expected, callerArguments, length) { + // TODO [$5f5fbe42fcabad09c1c241bc]: should this eventually raise an exception. + try { + // preface the argument description with "cmd", so + // that we can run it through yargs' command parser. + let position = 0 + let parsed = { demanded: [], optional: [] } + if (typeof expected === 'object') { + length = callerArguments + callerArguments = expected + } else { + parsed = command.parseCommand(`cmd ${expected}`) + } + const args = [].slice.call(callerArguments) + + while (args.length && args[args.length - 1] === undefined) args.pop() + length = length || args.length + + if (length < parsed.demanded.length) { + throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`) + } + + const totalCommands = parsed.demanded.length + parsed.optional.length + if (length > totalCommands) { + throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`) + } + + parsed.demanded.forEach((demanded) => { + const arg = args.shift() + const observedType = guessType(arg) + const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*') + if (matchingTypes.length === 0) argumentTypeError(observedType, demanded.cmd, position, false) + position += 1 + }) + + parsed.optional.forEach((optional) => { + if (args.length === 0) return + const arg = args.shift() + const observedType = guessType(arg) + const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*') + if (matchingTypes.length === 0) argumentTypeError(observedType, optional.cmd, position, true) + position += 1 + }) + } catch (err) { + console.warn(err.stack) + } +} + +function guessType (arg) { + if (Array.isArray(arg)) { + return 'array' + } else if (arg === null) { + return 'null' + } + return typeof arg +} + +function argumentTypeError (observedType, allowedTypes, position, optional) { + throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`) +} + + +/***/ }), + +/***/ 3810: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const inspect = __webpack_require__(1669).inspect +const isPromise = __webpack_require__(2694) +const { applyMiddleware, commandMiddlewareFactory } = __webpack_require__(9064) +const path = __webpack_require__(5622) +const Parser = __webpack_require__(871) + +const DEFAULT_MARKER = /(^\*)|(^\$0)/ + +// handles parsing positional arguments, +// and populating argv with said positional +// arguments. +module.exports = function command (yargs, usage, validation, globalMiddleware) { + const self = {} + let handlers = {} + let aliasMap = {} + let defaultCommand + globalMiddleware = globalMiddleware || [] + + self.addHandler = function addHandler (cmd, description, builder, handler, commandMiddleware) { + let aliases = [] + const middlewares = commandMiddlewareFactory(commandMiddleware) + handler = handler || (() => {}) + + if (Array.isArray(cmd)) { + aliases = cmd.slice(1) + cmd = cmd[0] + } else if (typeof cmd === 'object') { + let command = (Array.isArray(cmd.command) || typeof cmd.command === 'string') ? cmd.command : moduleName(cmd) + if (cmd.aliases) command = [].concat(command).concat(cmd.aliases) + self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares) + return + } + + // allow a module to be provided instead of separate builder and handler + if (typeof builder === 'object' && builder.builder && typeof builder.handler === 'function') { + self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares) + return + } + + // parse positionals out of cmd string + const parsedCommand = self.parseCommand(cmd) + + // remove positional args from aliases only + aliases = aliases.map(alias => self.parseCommand(alias).cmd) + + // check for default and filter out '*'' + let isDefault = false + const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c) => { + if (DEFAULT_MARKER.test(c)) { + isDefault = true + return false + } + return true + }) + + // standardize on $0 for default command. + if (parsedAliases.length === 0 && isDefault) parsedAliases.push('$0') + + // shift cmd and aliases after filtering out '*' + if (isDefault) { + parsedCommand.cmd = parsedAliases[0] + aliases = parsedAliases.slice(1) + cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd) + } + + // populate aliasMap + aliases.forEach((alias) => { + aliasMap[alias] = parsedCommand.cmd + }) + + if (description !== false) { + usage.command(cmd, description, isDefault, aliases) + } + + handlers[parsedCommand.cmd] = { + original: cmd, + description: description, + handler, + builder: builder || {}, + middlewares: middlewares || [], + demanded: parsedCommand.demanded, + optional: parsedCommand.optional + } + + if (isDefault) defaultCommand = handlers[parsedCommand.cmd] + } + + self.addDirectory = function addDirectory (dir, context, req, callerFile, opts) { + opts = opts || {} + // disable recursion to support nested directories of subcommands + if (typeof opts.recurse !== 'boolean') opts.recurse = false + // exclude 'json', 'coffee' from require-directory defaults + if (!Array.isArray(opts.extensions)) opts.extensions = ['js'] + // allow consumer to define their own visitor function + const parentVisit = typeof opts.visit === 'function' ? opts.visit : o => o + // call addHandler via visitor function + opts.visit = function visit (obj, joined, filename) { + const visited = parentVisit(obj, joined, filename) + // allow consumer to skip modules with their own visitor + if (visited) { + // check for cyclic reference + // each command file path should only be seen once per execution + if (~context.files.indexOf(joined)) return visited + // keep track of visited files in context.files + context.files.push(joined) + self.addHandler(visited) + } + return visited + } + __webpack_require__(9200)({ require: req, filename: callerFile }, dir, opts) + } + + // lookup module object from require()d command and derive name + // if module was not require()d and no name given, throw error + function moduleName (obj) { + const mod = __webpack_require__(3664)(obj) + if (!mod) throw new Error(`No command name given for module: ${inspect(obj)}`) + return commandFromFilename(mod.filename) + } + + // derive command name from filename + function commandFromFilename (filename) { + return path.basename(filename, path.extname(filename)) + } + + function extractDesc (obj) { + for (let keys = ['describe', 'description', 'desc'], i = 0, l = keys.length, test; i < l; i++) { + test = obj[keys[i]] + if (typeof test === 'string' || typeof test === 'boolean') return test + } + return false + } + + self.parseCommand = function parseCommand (cmd) { + const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ') + const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/) + const bregex = /\.*[\][<>]/g + const parsedCommand = { + cmd: (splitCommand.shift()).replace(bregex, ''), + demanded: [], + optional: [] + } + splitCommand.forEach((cmd, i) => { + let variadic = false + cmd = cmd.replace(/\s/g, '') + if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) variadic = true + if (/^\[/.test(cmd)) { + parsedCommand.optional.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic + }) + } else { + parsedCommand.demanded.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic + }) + } + }) + return parsedCommand + } + + self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap)) + + self.getCommandHandlers = () => handlers + + self.hasDefaultCommand = () => !!defaultCommand + + self.runCommand = function runCommand (command, yargs, parsed, commandIndex) { + let aliases = parsed.aliases + const commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand + const currentContext = yargs.getContext() + let numFiles = currentContext.files.length + const parentCommands = currentContext.commands.slice() + + // what does yargs look like after the buidler is run? + let innerArgv = parsed.argv + let innerYargs = null + let positionalMap = {} + if (command) { + currentContext.commands.push(command) + currentContext.fullCommands.push(commandHandler.original) + } + if (typeof commandHandler.builder === 'function') { + // a function can be provided, which builds + // up a yargs chain and possibly returns it. + innerYargs = commandHandler.builder(yargs.reset(parsed.aliases)) + // if the builder function did not yet parse argv with reset yargs + // and did not explicitly set a usage() string, then apply the + // original command string as usage() for consistent behavior with + // options object below. + if (yargs.parsed === false) { + if (shouldUpdateUsage(yargs)) { + yargs.getUsageInstance().usage( + usageFromParentCommandsCommandHandler(parentCommands, commandHandler), + commandHandler.description + ) + } + innerArgv = innerYargs ? innerYargs._parseArgs(null, null, true, commandIndex) : yargs._parseArgs(null, null, true, commandIndex) + } else { + innerArgv = yargs.parsed.argv + } + + if (innerYargs && yargs.parsed === false) aliases = innerYargs.parsed.aliases + else aliases = yargs.parsed.aliases + } else if (typeof commandHandler.builder === 'object') { + // as a short hand, an object can instead be provided, specifying + // the options that a command takes. + innerYargs = yargs.reset(parsed.aliases) + if (shouldUpdateUsage(innerYargs)) { + innerYargs.getUsageInstance().usage( + usageFromParentCommandsCommandHandler(parentCommands, commandHandler), + commandHandler.description + ) + } + Object.keys(commandHandler.builder).forEach((key) => { + innerYargs.option(key, commandHandler.builder[key]) + }) + innerArgv = innerYargs._parseArgs(null, null, true, commandIndex) + aliases = innerYargs.parsed.aliases + } + + if (!yargs._hasOutput()) { + positionalMap = populatePositionals(commandHandler, innerArgv, currentContext, yargs) + } + + const middlewares = globalMiddleware.slice(0).concat(commandHandler.middlewares || []) + applyMiddleware(innerArgv, yargs, middlewares, true) + + // we apply validation post-hoc, so that custom + // checks get passed populated positional arguments. + if (!yargs._hasOutput()) yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error) + + if (commandHandler.handler && !yargs._hasOutput()) { + yargs._setHasOutput() + + innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false) + + const handlerResult = isPromise(innerArgv) + ? innerArgv.then(argv => commandHandler.handler(argv)) + : commandHandler.handler(innerArgv) + + if (isPromise(handlerResult)) { + handlerResult.catch(error => + yargs.getUsageInstance().fail(null, error) + ) + } + } + + if (command) { + currentContext.commands.pop() + currentContext.fullCommands.pop() + } + numFiles = currentContext.files.length - numFiles + if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles) + + return innerArgv + } + + function shouldUpdateUsage (yargs) { + return !yargs.getUsageInstance().getUsageDisabled() && + yargs.getUsageInstance().getUsage().length === 0 + } + + function usageFromParentCommandsCommandHandler (parentCommands, commandHandler) { + const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() : commandHandler.original + const pc = parentCommands.filter((c) => { return !DEFAULT_MARKER.test(c) }) + pc.push(c) + return `$0 ${pc.join(' ')}` + } + + self.runDefaultBuilderOn = function (yargs) { + if (shouldUpdateUsage(yargs)) { + // build the root-level command string from the default string. + const commandString = DEFAULT_MARKER.test(defaultCommand.original) + ? defaultCommand.original : defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ') + yargs.getUsageInstance().usage( + commandString, + defaultCommand.description + ) + } + const builder = defaultCommand.builder + if (typeof builder === 'function') { + builder(yargs) + } else { + Object.keys(builder).forEach((key) => { + yargs.option(key, builder[key]) + }) + } + } + + // transcribe all positional arguments "command [apple]" + // onto argv. + function populatePositionals (commandHandler, argv, context, yargs) { + argv._ = argv._.slice(context.commands.length) // nuke the current commands + const demanded = commandHandler.demanded.slice(0) + const optional = commandHandler.optional.slice(0) + const positionalMap = {} + + validation.positionalCount(demanded.length, argv._.length) + + while (demanded.length) { + const demand = demanded.shift() + populatePositional(demand, argv, positionalMap) + } + + while (optional.length) { + const maybe = optional.shift() + populatePositional(maybe, argv, positionalMap) + } + + argv._ = context.commands.concat(argv._) + + postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original)) + + return positionalMap + } + + function populatePositional (positional, argv, positionalMap, parseOptions) { + const cmd = positional.cmd[0] + if (positional.variadic) { + positionalMap[cmd] = argv._.splice(0).map(String) + } else { + if (argv._.length) positionalMap[cmd] = [String(argv._.shift())] + } + } + + // we run yargs-parser against the positional arguments + // applying the same parsing logic used for flags. + function postProcessPositionals (argv, positionalMap, parseOptions) { + // combine the parsing hints we've inferred from the command + // string with explicitly configured parsing hints. + const options = Object.assign({}, yargs.getOptions()) + options.default = Object.assign(parseOptions.default, options.default) + options.alias = Object.assign(parseOptions.alias, options.alias) + options.array = options.array.concat(parseOptions.array) + delete options.config // don't load config when processing positionals. + + const unparsed = [] + Object.keys(positionalMap).forEach((key) => { + positionalMap[key].map((value) => { + unparsed.push(`--${key}`) + unparsed.push(value) + }) + }) + + // short-circuit parse. + if (!unparsed.length) return + + const parsed = Parser.detailed(unparsed, options) + + if (parsed.error) { + yargs.getUsageInstance().fail(parsed.error.message, parsed.error) + } else { + // only copy over positional keys (don't overwrite + // flag arguments that were already parsed). + const positionalKeys = Object.keys(positionalMap) + Object.keys(positionalMap).forEach((key) => { + [].push.apply(positionalKeys, parsed.aliases[key]) + }) + + Object.keys(parsed.argv).forEach((key) => { + if (positionalKeys.indexOf(key) !== -1) { + // any new aliases need to be placed in positionalMap, which + // is used for validation. + if (!positionalMap[key]) positionalMap[key] = parsed.argv[key] + argv[key] = parsed.argv[key] + } + }) + } + } + + self.cmdToParseOptions = function (cmdString) { + const parseOptions = { + array: [], + default: {}, + alias: {}, + demand: {} + } + + const parsed = self.parseCommand(cmdString) + parsed.demanded.forEach((d) => { + const cmds = d.cmd.slice(0) + const cmd = cmds.shift() + if (d.variadic) { + parseOptions.array.push(cmd) + parseOptions.default[cmd] = [] + } + cmds.forEach((c) => { + parseOptions.alias[cmd] = c + }) + parseOptions.demand[cmd] = true + }) + + parsed.optional.forEach((o) => { + const cmds = o.cmd.slice(0) + const cmd = cmds.shift() + if (o.variadic) { + parseOptions.array.push(cmd) + parseOptions.default[cmd] = [] + } + cmds.forEach((c) => { + parseOptions.alias[cmd] = c + }) + }) + + return parseOptions + } + + self.reset = () => { + handlers = {} + aliasMap = {} + defaultCommand = undefined + return self + } + + // used by yargs.parse() to freeze + // the state of commands such that + // we can apply .parse() multiple times + // with the same yargs instance. + let frozen + self.freeze = () => { + frozen = {} + frozen.handlers = handlers + frozen.aliasMap = aliasMap + frozen.defaultCommand = defaultCommand + } + self.unfreeze = () => { + handlers = frozen.handlers + aliasMap = frozen.aliasMap + defaultCommand = frozen.defaultCommand + frozen = undefined + } + + return self +} + + +/***/ }), + +/***/ 3559: +/***/ ((__unused_webpack_module, exports) => { + +exports.completionShTemplate = +`###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc +# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX. +# +_yargs_completions() +{ + local cur_word args type_list + + cur_word="\${COMP_WORDS[COMP_CWORD]}" + args=("\${COMP_WORDS[@]}") + + # ask yargs to generate completions. + type_list=$({{app_path}} --get-yargs-completions "\${args[@]}") + + COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) ) + + # if no match was found, fall back to filename completion + if [ \${#COMPREPLY[@]} -eq 0 ]; then + COMPREPLY=() + fi + + return 0 +} +complete -o default -F _yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +` + +exports.completionZshTemplate = `###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc +# or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX. +# +_{{app_name}}_yargs_completions() +{ + local reply + local si=$IFS + IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}")) + IFS=$si + _describe 'values' reply +} +compdef _{{app_name}}_yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +` + + +/***/ }), + +/***/ 418: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const path = __webpack_require__(5622) + +// add bash completions to your +// yargs-powered applications. +module.exports = function completion (yargs, usage, command) { + const self = { + completionKey: 'get-yargs-completions' + } + + const zshShell = process.env.SHELL && process.env.SHELL.indexOf('zsh') !== -1 + // get a list of completion commands. + // 'args' is the array of strings from the line to be completed + self.getCompletion = function getCompletion (args, done) { + const completions = [] + const current = args.length ? args[args.length - 1] : '' + const argv = yargs.parse(args, true) + const aliases = yargs.parsed.aliases + const parentCommands = yargs.getContext().commands + + // a custom completion function can be provided + // to completion(). + if (completionFunction) { + if (completionFunction.length < 3) { + const result = completionFunction(current, argv) + + // promise based completion function. + if (typeof result.then === 'function') { + return result.then((list) => { + process.nextTick(() => { done(list) }) + }).catch((err) => { + process.nextTick(() => { throw err }) + }) + } + + // synchronous completion function. + return done(result) + } else { + // asynchronous completion function + return completionFunction(current, argv, (completions) => { + done(completions) + }) + } + } + + const handlers = command.getCommandHandlers() + for (let i = 0, ii = args.length; i < ii; ++i) { + if (handlers[args[i]] && handlers[args[i]].builder) { + const builder = handlers[args[i]].builder + if (typeof builder === 'function') { + const y = yargs.reset() + builder(y) + return y.argv + } + } + } + + if (!current.match(/^-/) && parentCommands[parentCommands.length - 1] !== current) { + usage.getCommands().forEach((usageCommand) => { + const commandName = command.parseCommand(usageCommand[0]).cmd + if (args.indexOf(commandName) === -1) { + if (!zshShell) { + completions.push(commandName) + } else { + const desc = usageCommand[1] || '' + completions.push(commandName.replace(/:/g, '\\:') + ':' + desc) + } + } + }) + } + + if (current.match(/^-/) || (current === '' && completions.length === 0)) { + const descs = usage.getDescriptions() + Object.keys(yargs.getOptions().key).forEach((key) => { + // If the key and its aliases aren't in 'args', add the key to 'completions' + const keyAndAliases = [key].concat(aliases[key] || []) + const notInArgs = keyAndAliases.every(val => args.indexOf(`--${val}`) === -1) + if (notInArgs) { + if (!zshShell) { + completions.push(`--${key}`) + } else { + const desc = descs[key] || '' + completions.push(`--${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`) + } + } + }) + } + + done(completions) + } + + // generate the completion script to add to your .bashrc. + self.generateCompletionScript = function generateCompletionScript ($0, cmd) { + const templates = __webpack_require__(3559) + let script = zshShell ? templates.completionZshTemplate : templates.completionShTemplate + const name = path.basename($0) + + // add ./to applications not yet installed as bin. + if ($0.match(/\.js$/)) $0 = `./${$0}` + + script = script.replace(/{{app_name}}/g, name) + script = script.replace(/{{completion_command}}/g, cmd) + return script.replace(/{{app_path}}/g, $0) + } + + // register a function to perform your own custom + // completions., this function can be either + // synchrnous or asynchronous. + let completionFunction = null + self.registerFunction = (fn) => { + completionFunction = fn + } + + return self +} + + +/***/ }), + +/***/ 958: +/***/ ((module) => { + +"use strict"; +/* +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. +*/ + + +module.exports = (text, separator) => { + separator = typeof separator === 'undefined' ? '_' : separator + + return text + .replace(/([a-z\d])([A-Z])/g, `$1${separator}$2`) + .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, `$1${separator}$2`) + .toLowerCase() +} + + +/***/ }), + +/***/ 2694: +/***/ ((module) => { + +module.exports = function isPromise (maybePromise) { + return maybePromise instanceof Promise +} + + +/***/ }), + +/***/ 8108: +/***/ ((module) => { + +"use strict"; +/* +Copyright (c) 2011 Andrei Mackenzie + +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. +*/ + +// levenshtein distance algorithm, pulled from Andrei Mackenzie's MIT licensed. +// gist, which can be found here: https://gist.github.com/andrei-m/982927 + +// Compute the edit distance between the two given strings +module.exports = function levenshtein (a, b) { + if (a.length === 0) return b.length + if (b.length === 0) return a.length + + const matrix = [] + + // increment along the first column of each row + let i + for (i = 0; i <= b.length; i++) { + matrix[i] = [i] + } + + // increment each column in the first row + let j + for (j = 0; j <= a.length; j++) { + matrix[0][j] = j + } + + // Fill in the rest of the matrix + for (i = 1; i <= b.length; i++) { + for (j = 1; j <= a.length; j++) { + if (b.charAt(i - 1) === a.charAt(j - 1)) { + matrix[i][j] = matrix[i - 1][j - 1] + } else { + matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution + Math.min(matrix[i][j - 1] + 1, // insertion + matrix[i - 1][j] + 1)) // deletion + } + } + } + + return matrix[b.length][a.length] +} + + +/***/ }), + +/***/ 9064: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// hoisted due to circular dependency on command. +module.exports = { + applyMiddleware, + commandMiddlewareFactory, + globalMiddlewareFactory +} +const isPromise = __webpack_require__(2694) +const argsert = __webpack_require__(1206) + +function globalMiddlewareFactory (globalMiddleware, context) { + return function (callback, applyBeforeValidation = false) { + argsert(' [boolean]', [callback, applyBeforeValidation], arguments.length) + if (Array.isArray(callback)) { + for (let i = 0; i < callback.length; i++) { + if (typeof callback[i] !== 'function') { + throw Error('middleware must be a function') + } + callback[i].applyBeforeValidation = applyBeforeValidation + } + Array.prototype.push.apply(globalMiddleware, callback) + } else if (typeof callback === 'function') { + callback.applyBeforeValidation = applyBeforeValidation + globalMiddleware.push(callback) + } + return context + } +} + +function commandMiddlewareFactory (commandMiddleware) { + if (!commandMiddleware) return [] + return commandMiddleware.map(middleware => { + middleware.applyBeforeValidation = false + return middleware + }) +} + +function applyMiddleware (argv, yargs, middlewares, beforeValidation) { + const beforeValidationError = new Error('middleware cannot return a promise when applyBeforeValidation is true') + return middlewares + .reduce((accumulation, middleware) => { + if (middleware.applyBeforeValidation !== beforeValidation && + !isPromise(accumulation)) { + return accumulation + } + + if (isPromise(accumulation)) { + return accumulation + .then(initialObj => + Promise.all([initialObj, middleware(initialObj, yargs)]) + ) + .then(([initialObj, middlewareObj]) => + Object.assign(initialObj, middlewareObj) + ) + } else { + const result = middleware(argv, yargs) + if (beforeValidation && isPromise(result)) throw beforeValidationError + + return isPromise(result) + ? result.then(middlewareObj => Object.assign(accumulation, middlewareObj)) + : Object.assign(accumulation, result) + } + }, argv) +} + + +/***/ }), + +/***/ 2511: +/***/ ((module) => { + +"use strict"; + +module.exports = function objFilter (original, filter) { + const obj = {} + filter = filter || ((k, v) => true) + Object.keys(original || {}).forEach((key) => { + if (filter(key, original[key])) { + obj[key] = original[key] + } + }) + return obj +} + + +/***/ }), + +/***/ 7803: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +// this file handles outputting usage instructions, +// failures, etc. keeps logging in one place. +const decamelize = __webpack_require__(958) +const stringWidth = __webpack_require__(2577) +const objFilter = __webpack_require__(2511) +const path = __webpack_require__(5622) +const setBlocking = __webpack_require__(9344) +const YError = __webpack_require__(4401) + +module.exports = function usage (yargs, y18n) { + const __ = y18n.__ + const self = {} + + // methods for ouputting/building failure message. + const fails = [] + self.failFn = function failFn (f) { + fails.push(f) + } + + let failMessage = null + let showHelpOnFail = true + self.showHelpOnFail = function showHelpOnFailFn (enabled, message) { + if (typeof enabled === 'string') { + message = enabled + enabled = true + } else if (typeof enabled === 'undefined') { + enabled = true + } + failMessage = message + showHelpOnFail = enabled + return self + } + + let failureOutput = false + self.fail = function fail (msg, err) { + const logger = yargs._getLoggerInstance() + + if (fails.length) { + for (let i = fails.length - 1; i >= 0; --i) { + fails[i](msg, err, self) + } + } else { + if (yargs.getExitProcess()) setBlocking(true) + + // don't output failure message more than once + if (!failureOutput) { + failureOutput = true + if (showHelpOnFail) { + yargs.showHelp('error') + logger.error() + } + if (msg || err) logger.error(msg || err) + if (failMessage) { + if (msg || err) logger.error('') + logger.error(failMessage) + } + } + + err = err || new YError(msg) + if (yargs.getExitProcess()) { + return yargs.exit(1) + } else if (yargs._hasParseCallback()) { + return yargs.exit(1, err) + } else { + throw err + } + } + } + + // methods for ouputting/building help (usage) message. + let usages = [] + let usageDisabled = false + self.usage = (msg, description) => { + if (msg === null) { + usageDisabled = true + usages = [] + return + } + usageDisabled = false + usages.push([msg, description || '']) + return self + } + self.getUsage = () => { + return usages + } + self.getUsageDisabled = () => { + return usageDisabled + } + + self.getPositionalGroupName = () => { + return __('Positionals:') + } + + let examples = [] + self.example = (cmd, description) => { + examples.push([cmd, description || '']) + } + + let commands = [] + self.command = function command (cmd, description, isDefault, aliases) { + // the last default wins, so cancel out any previously set default + if (isDefault) { + commands = commands.map((cmdArray) => { + cmdArray[2] = false + return cmdArray + }) + } + commands.push([cmd, description || '', isDefault, aliases]) + } + self.getCommands = () => commands + + let descriptions = {} + self.describe = function describe (key, desc) { + if (typeof key === 'object') { + Object.keys(key).forEach((k) => { + self.describe(k, key[k]) + }) + } else { + descriptions[key] = desc + } + } + self.getDescriptions = () => descriptions + + let epilog + self.epilog = (msg) => { + epilog = msg + } + + let wrapSet = false + let wrap + self.wrap = (cols) => { + wrapSet = true + wrap = cols + } + + function getWrap () { + if (!wrapSet) { + wrap = windowWidth() + wrapSet = true + } + + return wrap + } + + const deferY18nLookupPrefix = '__yargsString__:' + self.deferY18nLookup = str => deferY18nLookupPrefix + str + + const defaultGroup = 'Options:' + self.help = function help () { + normalizeAliases() + + // handle old demanded API + const base$0 = path.basename(yargs.$0) + const demandedOptions = yargs.getDemandedOptions() + const demandedCommands = yargs.getDemandedCommands() + const groups = yargs.getGroups() + const options = yargs.getOptions() + + let keys = [] + keys = keys.concat(Object.keys(descriptions)) + keys = keys.concat(Object.keys(demandedOptions)) + keys = keys.concat(Object.keys(demandedCommands)) + keys = keys.concat(Object.keys(options.default)) + keys = keys.filter(filterHiddenOptions) + keys = Object.keys(keys.reduce((acc, key) => { + if (key !== '_') acc[key] = true + return acc + }, {})) + + const theWrap = getWrap() + const ui = __webpack_require__(7897)({ + width: theWrap, + wrap: !!theWrap + }) + + // the usage string. + if (!usageDisabled) { + if (usages.length) { + // user-defined usage. + usages.forEach((usage) => { + ui.div(`${usage[0].replace(/\$0/g, base$0)}`) + if (usage[1]) { + ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] }) + } + }) + ui.div() + } else if (commands.length) { + let u = null + // demonstrate how commands are used. + if (demandedCommands._) { + u = `${base$0} <${__('command')}>\n` + } else { + u = `${base$0} [${__('command')}]\n` + } + ui.div(`${u}`) + } + } + + // your application's commands, i.e., non-option + // arguments populated in '_'. + if (commands.length) { + ui.div(__('Commands:')) + + const context = yargs.getContext() + const parentCommands = context.commands.length ? `${context.commands.join(' ')} ` : '' + + if (yargs.getParserConfiguration()['sort-commands'] === true) { + commands = commands.sort((a, b) => a[0].localeCompare(b[0])) + } + + commands.forEach((command) => { + const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}` // drop $0 from default commands. + ui.span( + { + text: commandString, + padding: [0, 2, 0, 2], + width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4 + }, + { text: command[1] } + ) + const hints = [] + if (command[2]) hints.push(`[${__('default:').slice(0, -1)}]`) // TODO hacking around i18n here + if (command[3] && command[3].length) { + hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`) + } + if (hints.length) { + ui.div({ text: hints.join(' '), padding: [0, 0, 0, 2], align: 'right' }) + } else { + ui.div() + } + }) + + ui.div() + } + + // perform some cleanup on the keys array, making it + // only include top-level keys not their aliases. + const aliasKeys = (Object.keys(options.alias) || []) + .concat(Object.keys(yargs.parsed.newAliases) || []) + + keys = keys.filter(key => !yargs.parsed.newAliases[key] && aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1)) + + // populate 'Options:' group with any keys that have not + // explicitly had a group set. + if (!groups[defaultGroup]) groups[defaultGroup] = [] + addUngroupedKeys(keys, options.alias, groups) + + // display 'Options:' table along with any custom tables: + Object.keys(groups).forEach((groupName) => { + if (!groups[groupName].length) return + + // if we've grouped the key 'f', but 'f' aliases 'foobar', + // normalizedKeys should contain only 'foobar'. + const normalizedKeys = groups[groupName].filter(filterHiddenOptions).map((key) => { + if (~aliasKeys.indexOf(key)) return key + for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) { + if (~(options.alias[aliasKey] || []).indexOf(key)) return aliasKey + } + return key + }) + + if (normalizedKeys.length < 1) return + + ui.div(__(groupName)) + + // actually generate the switches string --foo, -f, --bar. + const switches = normalizedKeys.reduce((acc, key) => { + acc[key] = [ key ].concat(options.alias[key] || []) + .map(sw => { + // for the special positional group don't + // add '--' or '-' prefix. + if (groupName === self.getPositionalGroupName()) return sw + else return (sw.length > 1 ? '--' : '-') + sw + }) + .join(', ') + + return acc + }, {}) + + normalizedKeys.forEach((key) => { + const kswitch = switches[key] + let desc = descriptions[key] || '' + let type = null + + if (~desc.lastIndexOf(deferY18nLookupPrefix)) desc = __(desc.substring(deferY18nLookupPrefix.length)) + + if (~options.boolean.indexOf(key)) type = `[${__('boolean')}]` + if (~options.count.indexOf(key)) type = `[${__('count')}]` + if (~options.string.indexOf(key)) type = `[${__('string')}]` + if (~options.normalize.indexOf(key)) type = `[${__('string')}]` + if (~options.array.indexOf(key)) type = `[${__('array')}]` + if (~options.number.indexOf(key)) type = `[${__('number')}]` + + const extra = [ + type, + (key in demandedOptions) ? `[${__('required')}]` : null, + options.choices && options.choices[key] ? `[${__('choices:')} ${ + self.stringifiedValues(options.choices[key])}]` : null, + defaultString(options.default[key], options.defaultDescription[key]) + ].filter(Boolean).join(' ') + + ui.span( + { text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches, theWrap) + 4 }, + desc + ) + + if (extra) ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' }) + else ui.div() + }) + + ui.div() + }) + + // describe some common use-cases for your application. + if (examples.length) { + ui.div(__('Examples:')) + + examples.forEach((example) => { + example[0] = example[0].replace(/\$0/g, base$0) + }) + + examples.forEach((example) => { + if (example[1] === '') { + ui.div( + { + text: example[0], + padding: [0, 2, 0, 2] + } + ) + } else { + ui.div( + { + text: example[0], + padding: [0, 2, 0, 2], + width: maxWidth(examples, theWrap) + 4 + }, { + text: example[1] + } + ) + } + }) + + ui.div() + } + + // the usage string. + if (epilog) { + const e = epilog.replace(/\$0/g, base$0) + ui.div(`${e}\n`) + } + + // Remove the trailing white spaces + return ui.toString().replace(/\s*$/, '') + } + + // return the maximum width of a string + // in the left-hand column of a table. + function maxWidth (table, theWrap, modifier) { + let width = 0 + + // table might be of the form [leftColumn], + // or {key: leftColumn} + if (!Array.isArray(table)) { + table = Object.keys(table).map(key => [table[key]]) + } + + table.forEach((v) => { + width = Math.max( + stringWidth(modifier ? `${modifier} ${v[0]}` : v[0]), + width + ) + }) + + // if we've enabled 'wrap' we should limit + // the max-width of the left-column. + if (theWrap) width = Math.min(width, parseInt(theWrap * 0.5, 10)) + + return width + } + + // make sure any options set for aliases, + // are copied to the keys being aliased. + function normalizeAliases () { + // handle old demanded API + const demandedOptions = yargs.getDemandedOptions() + const options = yargs.getOptions() + + ;(Object.keys(options.alias) || []).forEach((key) => { + options.alias[key].forEach((alias) => { + // copy descriptions. + if (descriptions[alias]) self.describe(key, descriptions[alias]) + // copy demanded. + if (alias in demandedOptions) yargs.demandOption(key, demandedOptions[alias]) + // type messages. + if (~options.boolean.indexOf(alias)) yargs.boolean(key) + if (~options.count.indexOf(alias)) yargs.count(key) + if (~options.string.indexOf(alias)) yargs.string(key) + if (~options.normalize.indexOf(alias)) yargs.normalize(key) + if (~options.array.indexOf(alias)) yargs.array(key) + if (~options.number.indexOf(alias)) yargs.number(key) + }) + }) + } + + // given a set of keys, place any keys that are + // ungrouped under the 'Options:' grouping. + function addUngroupedKeys (keys, aliases, groups) { + let groupedKeys = [] + let toCheck = null + Object.keys(groups).forEach((group) => { + groupedKeys = groupedKeys.concat(groups[group]) + }) + + keys.forEach((key) => { + toCheck = [key].concat(aliases[key]) + if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) { + groups[defaultGroup].push(key) + } + }) + return groupedKeys + } + + function filterHiddenOptions (key) { + return yargs.getOptions().hiddenOptions.indexOf(key) < 0 || yargs.parsed.argv[yargs.getOptions().showHiddenOpt] + } + + self.showHelp = (level) => { + const logger = yargs._getLoggerInstance() + if (!level) level = 'error' + const emit = typeof level === 'function' ? level : logger[level] + emit(self.help()) + } + + self.functionDescription = (fn) => { + const description = fn.name ? decamelize(fn.name, '-') : __('generated-value') + return ['(', description, ')'].join('') + } + + self.stringifiedValues = function stringifiedValues (values, separator) { + let string = '' + const sep = separator || ', ' + const array = [].concat(values) + + if (!values || !array.length) return string + + array.forEach((value) => { + if (string.length) string += sep + string += JSON.stringify(value) + }) + + return string + } + + // format the default-value-string displayed in + // the right-hand column. + function defaultString (value, defaultDescription) { + let string = `[${__('default:')} ` + + if (value === undefined && !defaultDescription) return null + + if (defaultDescription) { + string += defaultDescription + } else { + switch (typeof value) { + case 'string': + string += `"${value}"` + break + case 'object': + string += JSON.stringify(value) + break + default: + string += value + } + } + + return `${string}]` + } + + // guess the width of the console window, max-width 80. + function windowWidth () { + const maxWidth = 80 + if (typeof process === 'object' && process.stdout && process.stdout.columns) { + return Math.min(maxWidth, process.stdout.columns) + } else { + return maxWidth + } + } + + // logic for displaying application version. + let version = null + self.version = (ver) => { + version = ver + } + + self.showVersion = () => { + const logger = yargs._getLoggerInstance() + logger.log(version) + } + + self.reset = function reset (localLookup) { + // do not reset wrap here + // do not reset fails here + failMessage = null + failureOutput = false + usages = [] + usageDisabled = false + epilog = undefined + examples = [] + commands = [] + descriptions = objFilter(descriptions, (k, v) => !localLookup[k]) + return self + } + + let frozen + self.freeze = function freeze () { + frozen = {} + frozen.failMessage = failMessage + frozen.failureOutput = failureOutput + frozen.usages = usages + frozen.usageDisabled = usageDisabled + frozen.epilog = epilog + frozen.examples = examples + frozen.commands = commands + frozen.descriptions = descriptions + } + self.unfreeze = function unfreeze () { + failMessage = frozen.failMessage + failureOutput = frozen.failureOutput + usages = frozen.usages + usageDisabled = frozen.usageDisabled + epilog = frozen.epilog + examples = frozen.examples + commands = frozen.commands + descriptions = frozen.descriptions + frozen = undefined + } + + return self +} + + +/***/ }), + +/***/ 707: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const argsert = __webpack_require__(1206) +const objFilter = __webpack_require__(2511) +const specialKeys = ['$0', '--', '_'] + +// validation-type-stuff, missing params, +// bad implications, custom checks. +module.exports = function validation (yargs, usage, y18n) { + const __ = y18n.__ + const __n = y18n.__n + const self = {} + + // validate appropriate # of non-option + // arguments were provided, i.e., '_'. + self.nonOptionCount = function nonOptionCount (argv) { + const demandedCommands = yargs.getDemandedCommands() + // don't count currently executing commands + const _s = argv._.length - yargs.getContext().commands.length + + if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) { + if (_s < demandedCommands._.min) { + if (demandedCommands._.minMsg !== undefined) { + usage.fail( + // replace $0 with observed, $1 with expected. + demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\$0/g, _s).replace(/\$1/, demandedCommands._.min) : null + ) + } else { + usage.fail( + __('Not enough non-option arguments: got %s, need at least %s', _s, demandedCommands._.min) + ) + } + } else if (_s > demandedCommands._.max) { + if (demandedCommands._.maxMsg !== undefined) { + usage.fail( + // replace $0 with observed, $1 with expected. + demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\$0/g, _s).replace(/\$1/, demandedCommands._.max) : null + ) + } else { + usage.fail( + __('Too many non-option arguments: got %s, maximum of %s', _s, demandedCommands._.max) + ) + } + } + } + } + + // validate the appropriate # of + // positional arguments were provided: + self.positionalCount = function positionalCount (required, observed) { + if (observed < required) { + usage.fail( + __('Not enough non-option arguments: got %s, need at least %s', observed, required) + ) + } + } + + // make sure all the required arguments are present. + self.requiredArguments = function requiredArguments (argv) { + const demandedOptions = yargs.getDemandedOptions() + let missing = null + + Object.keys(demandedOptions).forEach((key) => { + if (!argv.hasOwnProperty(key) || typeof argv[key] === 'undefined') { + missing = missing || {} + missing[key] = demandedOptions[key] + } + }) + + if (missing) { + const customMsgs = [] + Object.keys(missing).forEach((key) => { + const msg = missing[key] + if (msg && customMsgs.indexOf(msg) < 0) { + customMsgs.push(msg) + } + }) + + const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '' + + usage.fail(__n( + 'Missing required argument: %s', + 'Missing required arguments: %s', + Object.keys(missing).length, + Object.keys(missing).join(', ') + customMsg + )) + } + } + + // check for unknown arguments (strict-mode). + self.unknownArguments = function unknownArguments (argv, aliases, positionalMap) { + const commandKeys = yargs.getCommandInstance().getCommands() + const unknown = [] + const currentContext = yargs.getContext() + + Object.keys(argv).forEach((key) => { + if (specialKeys.indexOf(key) === -1 && + !positionalMap.hasOwnProperty(key) && + !yargs._getParseContext().hasOwnProperty(key) && + !aliases.hasOwnProperty(key) + ) { + unknown.push(key) + } + }) + + if (commandKeys.length > 0) { + argv._.slice(currentContext.commands.length).forEach((key) => { + if (commandKeys.indexOf(key) === -1) { + unknown.push(key) + } + }) + } + + if (unknown.length > 0) { + usage.fail(__n( + 'Unknown argument: %s', + 'Unknown arguments: %s', + unknown.length, + unknown.join(', ') + )) + } + } + + // validate arguments limited to enumerated choices + self.limitedChoices = function limitedChoices (argv) { + const options = yargs.getOptions() + const invalid = {} + + if (!Object.keys(options.choices).length) return + + Object.keys(argv).forEach((key) => { + if (specialKeys.indexOf(key) === -1 && + options.choices.hasOwnProperty(key)) { + [].concat(argv[key]).forEach((value) => { + // TODO case-insensitive configurability + if (options.choices[key].indexOf(value) === -1 && + value !== undefined) { + invalid[key] = (invalid[key] || []).concat(value) + } + }) + } + }) + + const invalidKeys = Object.keys(invalid) + + if (!invalidKeys.length) return + + let msg = __('Invalid values:') + invalidKeys.forEach((key) => { + msg += `\n ${__( + 'Argument: %s, Given: %s, Choices: %s', + key, + usage.stringifiedValues(invalid[key]), + usage.stringifiedValues(options.choices[key]) + )}` + }) + usage.fail(msg) + } + + // custom checks, added using the `check` option on yargs. + let checks = [] + self.check = function check (f, global) { + checks.push({ + func: f, + global + }) + } + + self.customChecks = function customChecks (argv, aliases) { + for (let i = 0, f; (f = checks[i]) !== undefined; i++) { + const func = f.func + let result = null + try { + result = func(argv, aliases) + } catch (err) { + usage.fail(err.message ? err.message : err, err) + continue + } + + if (!result) { + usage.fail(__('Argument check failed: %s', func.toString())) + } else if (typeof result === 'string' || result instanceof Error) { + usage.fail(result.toString(), result) + } + } + } + + // check implications, argument foo implies => argument bar. + let implied = {} + self.implies = function implies (key, value) { + argsert(' [array|number|string]', [key, value], arguments.length) + + if (typeof key === 'object') { + Object.keys(key).forEach((k) => { + self.implies(k, key[k]) + }) + } else { + yargs.global(key) + if (!implied[key]) { + implied[key] = [] + } + if (Array.isArray(value)) { + value.forEach((i) => self.implies(key, i)) + } else { + implied[key].push(value) + } + } + } + self.getImplied = function getImplied () { + return implied + } + + self.implications = function implications (argv) { + const implyFail = [] + + Object.keys(implied).forEach((key) => { + const origKey = key + ;(implied[key] || []).forEach((value) => { + let num + let key = origKey + const origValue = value + + // convert string '1' to number 1 + num = Number(key) + key = isNaN(num) ? key : num + + if (typeof key === 'number') { + // check length of argv._ + key = argv._.length >= key + } else if (key.match(/^--no-.+/)) { + // check if key doesn't exist + key = key.match(/^--no-(.+)/)[1] + key = !argv[key] + } else { + // check if key exists + key = argv[key] + } + + num = Number(value) + value = isNaN(num) ? value : num + + if (typeof value === 'number') { + value = argv._.length >= value + } else if (value.match(/^--no-.+/)) { + value = value.match(/^--no-(.+)/)[1] + value = !argv[value] + } else { + value = argv[value] + } + if (key && !value) { + implyFail.push(` ${origKey} -> ${origValue}`) + } + }) + }) + + if (implyFail.length) { + let msg = `${__('Implications failed:')}\n` + + implyFail.forEach((value) => { + msg += (value) + }) + + usage.fail(msg) + } + } + + let conflicting = {} + self.conflicts = function conflicts (key, value) { + argsert(' [array|string]', [key, value], arguments.length) + + if (typeof key === 'object') { + Object.keys(key).forEach((k) => { + self.conflicts(k, key[k]) + }) + } else { + yargs.global(key) + if (!conflicting[key]) { + conflicting[key] = [] + } + if (Array.isArray(value)) { + value.forEach((i) => self.conflicts(key, i)) + } else { + conflicting[key].push(value) + } + } + } + self.getConflicting = () => conflicting + + self.conflicting = function conflictingFn (argv) { + Object.keys(argv).forEach((key) => { + if (conflicting[key]) { + conflicting[key].forEach((value) => { + // we default keys to 'undefined' that have been configured, we should not + // apply conflicting check unless they are a value other than 'undefined'. + if (value && argv[key] !== undefined && argv[value] !== undefined) { + usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)) + } + }) + } + }) + } + + self.recommendCommands = function recommendCommands (cmd, potentialCommands) { + const distance = __webpack_require__(8108) + const threshold = 3 // if it takes more than three edits, let's move on. + potentialCommands = potentialCommands.sort((a, b) => b.length - a.length) + + let recommended = null + let bestDistance = Infinity + for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) { + const d = distance(cmd, candidate) + if (d <= threshold && d < bestDistance) { + bestDistance = d + recommended = candidate + } + } + if (recommended) usage.fail(__('Did you mean %s?', recommended)) + } + + self.reset = function reset (localLookup) { + implied = objFilter(implied, (k, v) => !localLookup[k]) + conflicting = objFilter(conflicting, (k, v) => !localLookup[k]) + checks = checks.filter(c => c.global) + return self + } + + let frozen + self.freeze = function freeze () { + frozen = {} + frozen.implied = implied + frozen.checks = checks + frozen.conflicting = conflicting + } + self.unfreeze = function unfreeze () { + implied = frozen.implied + checks = frozen.checks + conflicting = frozen.conflicting + frozen = undefined + } + + return self +} + + +/***/ }), + +/***/ 4401: +/***/ ((module) => { + +"use strict"; + +function YError (msg) { + this.name = 'YError' + this.message = msg || 'yargs error' + Error.captureStackTrace(this, YError) +} + +YError.prototype = Object.create(Error.prototype) +YError.prototype.constructor = YError + +module.exports = YError + + +/***/ }), + +/***/ 2180: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; + +const argsert = __webpack_require__(1206) +const fs = __webpack_require__(5747) +const Command = __webpack_require__(3810) +const Completion = __webpack_require__(418) +const Parser = __webpack_require__(871) +const path = __webpack_require__(5622) +const Usage = __webpack_require__(7803) +const Validation = __webpack_require__(707) +const Y18n = __webpack_require__(8138) +const objFilter = __webpack_require__(2511) +const setBlocking = __webpack_require__(9344) +const applyExtends = __webpack_require__(5493) +const { globalMiddlewareFactory } = __webpack_require__(9064) +const YError = __webpack_require__(4401) + +exports = module.exports = Yargs +function Yargs (processArgs, cwd, parentRequire) { + processArgs = processArgs || [] // handle calling yargs(). + + const self = {} + let command = null + let completion = null + let groups = {} + let globalMiddleware = [] + let output = '' + let preservedGroups = {} + let usage = null + let validation = null + + const y18n = Y18n({ + directory: __webpack_require__.ab + "locales", + updateFiles: false + }) + + self.middleware = globalMiddlewareFactory(globalMiddleware, self) + + if (!cwd) cwd = process.cwd() + + self.scriptName = function scriptName (scriptName) { + self.$0 = scriptName + return self + } + + // ignore the node bin, specify this in your + // bin file with #!/usr/bin/env node + if (/\b(node|iojs|electron)(\.exe)?$/.test(process.argv[0])) { + self.$0 = process.argv.slice(1, 2) + } else { + self.$0 = process.argv.slice(0, 1) + } + + self.$0 = self.$0 + .map((x, i) => { + const b = rebase(cwd, x) + return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x + }) + .join(' ').trim() + + if (process.env._ !== undefined && process.argv[1] === process.env._) { + self.$0 = process.env._.replace( + `${path.dirname(process.execPath)}/`, '' + ) + } + + // use context object to keep track of resets, subcommand execution, etc + // submodules should modify and check the state of context as necessary + const context = { resets: -1, commands: [], fullCommands: [], files: [] } + self.getContext = () => context + + // puts yargs back into an initial state. any keys + // that have been set to "global" will not be reset + // by this action. + let options + self.resetOptions = self.reset = function resetOptions (aliases) { + context.resets++ + aliases = aliases || {} + options = options || {} + // put yargs back into an initial state, this + // logic is used to build a nested command + // hierarchy. + const tmpOptions = {} + tmpOptions.local = options.local ? options.local : [] + tmpOptions.configObjects = options.configObjects ? options.configObjects : [] + + // if a key has been explicitly set as local, + // we should reset it before passing options to command. + const localLookup = {} + tmpOptions.local.forEach((l) => { + localLookup[l] = true + ;(aliases[l] || []).forEach((a) => { + localLookup[a] = true + }) + }) + + // preserve all groups not set to local. + preservedGroups = Object.keys(groups).reduce((acc, groupName) => { + const keys = groups[groupName].filter(key => !(key in localLookup)) + if (keys.length > 0) { + acc[groupName] = keys + } + return acc + }, {}) + // groups can now be reset + groups = {} + + const arrayOptions = [ + 'array', 'boolean', 'string', 'skipValidation', + 'count', 'normalize', 'number', + 'hiddenOptions' + ] + + const objectOptions = [ + 'narg', 'key', 'alias', 'default', 'defaultDescription', + 'config', 'choices', 'demandedOptions', 'demandedCommands', 'coerce' + ] + + arrayOptions.forEach((k) => { + tmpOptions[k] = (options[k] || []).filter(k => !localLookup[k]) + }) + + objectOptions.forEach((k) => { + tmpOptions[k] = objFilter(options[k], (k, v) => !localLookup[k]) + }) + + tmpOptions.envPrefix = options.envPrefix + options = tmpOptions + + // if this is the first time being executed, create + // instances of all our helpers -- otherwise just reset. + usage = usage ? usage.reset(localLookup) : Usage(self, y18n) + validation = validation ? validation.reset(localLookup) : Validation(self, usage, y18n) + command = command ? command.reset() : Command(self, usage, validation, globalMiddleware) + if (!completion) completion = Completion(self, usage, command) + + completionCommand = null + output = '' + exitError = null + hasOutput = false + self.parsed = false + + return self + } + self.resetOptions() + + // temporary hack: allow "freezing" of reset-able state for parse(msg, cb) + let frozen + function freeze () { + frozen = {} + frozen.options = options + frozen.configObjects = options.configObjects.slice(0) + frozen.exitProcess = exitProcess + frozen.groups = groups + usage.freeze() + validation.freeze() + command.freeze() + frozen.strict = strict + frozen.completionCommand = completionCommand + frozen.output = output + frozen.exitError = exitError + frozen.hasOutput = hasOutput + frozen.parsed = self.parsed + } + function unfreeze () { + options = frozen.options + options.configObjects = frozen.configObjects + exitProcess = frozen.exitProcess + groups = frozen.groups + output = frozen.output + exitError = frozen.exitError + hasOutput = frozen.hasOutput + self.parsed = frozen.parsed + usage.unfreeze() + validation.unfreeze() + command.unfreeze() + strict = frozen.strict + completionCommand = frozen.completionCommand + parseFn = null + parseContext = null + frozen = undefined + } + + self.boolean = function (keys) { + argsert('', [keys], arguments.length) + populateParserHintArray('boolean', keys) + return self + } + + self.array = function (keys) { + argsert('', [keys], arguments.length) + populateParserHintArray('array', keys) + return self + } + + self.number = function (keys) { + argsert('', [keys], arguments.length) + populateParserHintArray('number', keys) + return self + } + + self.normalize = function (keys) { + argsert('', [keys], arguments.length) + populateParserHintArray('normalize', keys) + return self + } + + self.count = function (keys) { + argsert('', [keys], arguments.length) + populateParserHintArray('count', keys) + return self + } + + self.string = function (keys) { + argsert('', [keys], arguments.length) + populateParserHintArray('string', keys) + return self + } + + self.requiresArg = function (keys) { + argsert('', [keys], arguments.length) + populateParserHintObject(self.nargs, false, 'narg', keys, 1) + return self + } + + self.skipValidation = function (keys) { + argsert('', [keys], arguments.length) + populateParserHintArray('skipValidation', keys) + return self + } + + function populateParserHintArray (type, keys, value) { + keys = [].concat(keys) + keys.forEach((key) => { + key = sanitizeKey(key) + options[type].push(key) + }) + } + + self.nargs = function (key, value) { + argsert(' [number]', [key, value], arguments.length) + populateParserHintObject(self.nargs, false, 'narg', key, value) + return self + } + + self.choices = function (key, value) { + argsert(' [string|array]', [key, value], arguments.length) + populateParserHintObject(self.choices, true, 'choices', key, value) + return self + } + + self.alias = function (key, value) { + argsert(' [string|array]', [key, value], arguments.length) + populateParserHintObject(self.alias, true, 'alias', key, value) + return self + } + + // TODO [$5f5fbe42fcabad09c1c241bd]: actually deprecate self.defaults. + self.default = self.defaults = function (key, value, defaultDescription) { + argsert(' [*] [string]', [key, value, defaultDescription], arguments.length) + if (defaultDescription) options.defaultDescription[key] = defaultDescription + if (typeof value === 'function') { + if (!options.defaultDescription[key]) options.defaultDescription[key] = usage.functionDescription(value) + value = value.call() + } + populateParserHintObject(self.default, false, 'default', key, value) + return self + } + + self.describe = function (key, desc) { + argsert(' [string]', [key, desc], arguments.length) + populateParserHintObject(self.describe, false, 'key', key, true) + usage.describe(key, desc) + return self + } + + self.demandOption = function (keys, msg) { + argsert(' [string]', [keys, msg], arguments.length) + populateParserHintObject(self.demandOption, false, 'demandedOptions', keys, msg) + return self + } + + self.coerce = function (keys, value) { + argsert(' [function]', [keys, value], arguments.length) + populateParserHintObject(self.coerce, false, 'coerce', keys, value) + return self + } + + function populateParserHintObject (builder, isArray, type, key, value) { + if (Array.isArray(key)) { + const temp = Object.create(null) + // an array of keys with one value ['x', 'y', 'z'], function parse () {} + key.forEach((k) => { + temp[k] = value + }) + builder(temp) + } else if (typeof key === 'object') { + // an object of key value pairs: {'x': parse () {}, 'y': parse() {}} + Object.keys(key).forEach((k) => { + builder(k, key[k]) + }) + } else { + key = sanitizeKey(key) + // a single key value pair 'x', parse() {} + if (isArray) { + options[type][key] = (options[type][key] || []).concat(value) + } else { + options[type][key] = value + } + } + } + + // TODO(bcoe): in future major versions move more objects towards + // Object.create(null): + function sanitizeKey (key) { + if (key === '__proto__') return '___proto___' + return key + } + + function deleteFromParserHintObject (optionKey) { + // delete from all parsing hints: + // boolean, array, key, alias, etc. + Object.keys(options).forEach((hintKey) => { + const hint = options[hintKey] + if (Array.isArray(hint)) { + if (~hint.indexOf(optionKey)) hint.splice(hint.indexOf(optionKey), 1) + } else if (typeof hint === 'object') { + delete hint[optionKey] + } + }) + // now delete the description from usage.js. + delete usage.getDescriptions()[optionKey] + } + + self.config = function config (key, msg, parseFn) { + argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length) + // allow a config object to be provided directly. + if (typeof key === 'object') { + key = applyExtends(key, cwd) + options.configObjects = (options.configObjects || []).concat(key) + return self + } + + // allow for a custom parsing function. + if (typeof msg === 'function') { + parseFn = msg + msg = null + } + + key = key || 'config' + self.describe(key, msg || usage.deferY18nLookup('Path to JSON config file')) + ;(Array.isArray(key) ? key : [key]).forEach((k) => { + options.config[k] = parseFn || true + }) + + return self + } + + self.example = function (cmd, description) { + argsert(' [string]', [cmd, description], arguments.length) + usage.example(cmd, description) + return self + } + + self.command = function (cmd, description, builder, handler, middlewares) { + argsert(' [string|boolean] [function|object] [function] [array]', [cmd, description, builder, handler, middlewares], arguments.length) + command.addHandler(cmd, description, builder, handler, middlewares) + return self + } + + self.commandDir = function (dir, opts) { + argsert(' [object]', [dir, opts], arguments.length) + const req = parentRequire || require + command.addDirectory(dir, self.getContext(), req, __webpack_require__(351)(), opts) + return self + } + + // TODO [$5f5fbe42fcabad09c1c241be]: deprecate self.demand in favor of + // .demandCommand() .demandOption(). + self.demand = self.required = self.require = function demand (keys, max, msg) { + // you can optionally provide a 'max' key, + // which will raise an exception if too many '_' + // options are provided. + if (Array.isArray(max)) { + max.forEach((key) => { + self.demandOption(key, msg) + }) + max = Infinity + } else if (typeof max !== 'number') { + msg = max + max = Infinity + } + + if (typeof keys === 'number') { + self.demandCommand(keys, max, msg, msg) + } else if (Array.isArray(keys)) { + keys.forEach((key) => { + self.demandOption(key, msg) + }) + } else { + if (typeof msg === 'string') { + self.demandOption(keys, msg) + } else if (msg === true || typeof msg === 'undefined') { + self.demandOption(keys) + } + } + + return self + } + + self.demandCommand = function demandCommand (min, max, minMsg, maxMsg) { + argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length) + + if (typeof min === 'undefined') min = 1 + + if (typeof max !== 'number') { + minMsg = max + max = Infinity + } + + self.global('_', false) + + options.demandedCommands._ = { + min, + max, + minMsg, + maxMsg + } + + return self + } + + self.getDemandedOptions = () => { + argsert([], 0) + return options.demandedOptions + } + + self.getDemandedCommands = () => { + argsert([], 0) + return options.demandedCommands + } + + self.implies = function (key, value) { + argsert(' [number|string|array]', [key, value], arguments.length) + validation.implies(key, value) + return self + } + + self.conflicts = function (key1, key2) { + argsert(' [string|array]', [key1, key2], arguments.length) + validation.conflicts(key1, key2) + return self + } + + self.usage = function (msg, description, builder, handler) { + argsert(' [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length) + + if (description !== undefined) { + // .usage() can be used as an alias for defining + // a default command. + if ((msg || '').match(/^\$0( |$)/)) { + return self.command(msg, description, builder, handler) + } else { + throw new YError('.usage() description must start with $0 if being used as alias for .command()') + } + } else { + usage.usage(msg) + return self + } + } + + self.epilogue = self.epilog = function (msg) { + argsert('', [msg], arguments.length) + usage.epilog(msg) + return self + } + + self.fail = function (f) { + argsert('', [f], arguments.length) + usage.failFn(f) + return self + } + + self.check = function (f, _global) { + argsert(' [boolean]', [f, _global], arguments.length) + validation.check(f, _global !== false) + return self + } + + self.global = function global (globals, global) { + argsert(' [boolean]', [globals, global], arguments.length) + globals = [].concat(globals) + if (global !== false) { + options.local = options.local.filter(l => globals.indexOf(l) === -1) + } else { + globals.forEach((g) => { + if (options.local.indexOf(g) === -1) options.local.push(g) + }) + } + return self + } + + self.pkgConf = function pkgConf (key, rootPath) { + argsert(' [string]', [key, rootPath], arguments.length) + let conf = null + // prefer cwd to require-main-filename in this method + // since we're looking for e.g. "nyc" config in nyc consumer + // rather than "yargs" config in nyc (where nyc is the main filename) + const obj = pkgUp(rootPath || cwd) + + // If an object exists in the key, add it to options.configObjects + if (obj[key] && typeof obj[key] === 'object') { + conf = applyExtends(obj[key], rootPath || cwd) + options.configObjects = (options.configObjects || []).concat(conf) + } + + return self + } + + const pkgs = {} + function pkgUp (rootPath) { + const npath = rootPath || '*' + if (pkgs[npath]) return pkgs[npath] + const findUp = __webpack_require__(5763) + + let obj = {} + try { + let startDir = rootPath || __webpack_require__(6829)(parentRequire || require) + + // When called in an environment that lacks require.main.filename, such as a jest test runner, + // startDir is already process.cwd(), and should not be shortened. + // Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it. + if (!rootPath && path.extname(startDir)) { + startDir = path.dirname(startDir) + } + + const pkgJsonPath = findUp.sync('package.json', { + cwd: startDir + }) + obj = JSON.parse(fs.readFileSync(pkgJsonPath)) + } catch (noop) {} + + pkgs[npath] = obj || {} + return pkgs[npath] + } + + let parseFn = null + let parseContext = null + self.parse = function parse (args, shortCircuit, _parseFn) { + argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length) + if (typeof args === 'undefined') { + return self._parseArgs(processArgs) + } + + // a context object can optionally be provided, this allows + // additional information to be passed to a command handler. + if (typeof shortCircuit === 'object') { + parseContext = shortCircuit + shortCircuit = _parseFn + } + + // by providing a function as a second argument to + // parse you can capture output that would otherwise + // default to printing to stdout/stderr. + if (typeof shortCircuit === 'function') { + parseFn = shortCircuit + shortCircuit = null + } + // completion short-circuits the parsing process, + // skipping validation, etc. + if (!shortCircuit) processArgs = args + + freeze() + if (parseFn) exitProcess = false + + const parsed = self._parseArgs(args, shortCircuit) + if (parseFn) parseFn(exitError, parsed, output) + unfreeze() + + return parsed + } + + self._getParseContext = () => parseContext || {} + + self._hasParseCallback = () => !!parseFn + + self.option = self.options = function option (key, opt) { + argsert(' [object]', [key, opt], arguments.length) + if (typeof key === 'object') { + Object.keys(key).forEach((k) => { + self.options(k, key[k]) + }) + } else { + if (typeof opt !== 'object') { + opt = {} + } + + options.key[key] = true // track manually set keys. + + if (opt.alias) self.alias(key, opt.alias) + + const demand = opt.demand || opt.required || opt.require + + // deprecated, use 'demandOption' instead + if (demand) { + self.demand(key, demand) + } + + if (opt.demandOption) { + self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined) + } + + if ('conflicts' in opt) { + self.conflicts(key, opt.conflicts) + } + + if ('default' in opt) { + self.default(key, opt.default) + } + + if ('implies' in opt) { + self.implies(key, opt.implies) + } + + if ('nargs' in opt) { + self.nargs(key, opt.nargs) + } + + if (opt.config) { + self.config(key, opt.configParser) + } + + if (opt.normalize) { + self.normalize(key) + } + + if ('choices' in opt) { + self.choices(key, opt.choices) + } + + if ('coerce' in opt) { + self.coerce(key, opt.coerce) + } + + if ('group' in opt) { + self.group(key, opt.group) + } + + if (opt.boolean || opt.type === 'boolean') { + self.boolean(key) + if (opt.alias) self.boolean(opt.alias) + } + + if (opt.array || opt.type === 'array') { + self.array(key) + if (opt.alias) self.array(opt.alias) + } + + if (opt.number || opt.type === 'number') { + self.number(key) + if (opt.alias) self.number(opt.alias) + } + + if (opt.string || opt.type === 'string') { + self.string(key) + if (opt.alias) self.string(opt.alias) + } + + if (opt.count || opt.type === 'count') { + self.count(key) + } + + if (typeof opt.global === 'boolean') { + self.global(key, opt.global) + } + + if (opt.defaultDescription) { + options.defaultDescription[key] = opt.defaultDescription + } + + if (opt.skipValidation) { + self.skipValidation(key) + } + + const desc = opt.describe || opt.description || opt.desc + self.describe(key, desc) + if (opt.hidden) { + self.hide(key) + } + + if (opt.requiresArg) { + self.requiresArg(key) + } + } + + return self + } + self.getOptions = () => options + + self.positional = function (key, opts) { + argsert(' ', [key, opts], arguments.length) + if (context.resets === 0) { + throw new YError(".positional() can only be called in a command's builder function") + } + + // .positional() only supports a subset of the configuration + // options available to .option(). + const supportedOpts = ['default', 'defaultDescription', 'implies', 'normalize', + 'choices', 'conflicts', 'coerce', 'type', 'describe', + 'desc', 'description', 'alias'] + opts = objFilter(opts, (k, v) => { + let accept = supportedOpts.indexOf(k) !== -1 + // type can be one of string|number|boolean. + if (k === 'type' && ['string', 'number', 'boolean'].indexOf(v) === -1) accept = false + return accept + }) + + // copy over any settings that can be inferred from the command string. + const fullCommand = context.fullCommands[context.fullCommands.length - 1] + const parseOptions = fullCommand ? command.cmdToParseOptions(fullCommand) : { + array: [], + alias: {}, + default: {}, + demand: {} + } + Object.keys(parseOptions).forEach((pk) => { + if (Array.isArray(parseOptions[pk])) { + if (parseOptions[pk].indexOf(key) !== -1) opts[pk] = true + } else { + if (parseOptions[pk][key] && !(pk in opts)) opts[pk] = parseOptions[pk][key] + } + }) + self.group(key, usage.getPositionalGroupName()) + return self.option(key, opts) + } + + self.group = function group (opts, groupName) { + argsert(' ', [opts, groupName], arguments.length) + const existing = preservedGroups[groupName] || groups[groupName] + if (preservedGroups[groupName]) { + // we now only need to track this group name in groups. + delete preservedGroups[groupName] + } + + const seen = {} + groups[groupName] = (existing || []).concat(opts).filter((key) => { + if (seen[key]) return false + return (seen[key] = true) + }) + return self + } + // combine explicit and preserved groups. explicit groups should be first + self.getGroups = () => Object.assign({}, groups, preservedGroups) + + // as long as options.envPrefix is not undefined, + // parser will apply env vars matching prefix to argv + self.env = function (prefix) { + argsert('[string|boolean]', [prefix], arguments.length) + if (prefix === false) options.envPrefix = undefined + else options.envPrefix = prefix || '' + return self + } + + self.wrap = function (cols) { + argsert('', [cols], arguments.length) + usage.wrap(cols) + return self + } + + let strict = false + self.strict = function (enabled) { + argsert('[boolean]', [enabled], arguments.length) + strict = enabled !== false + return self + } + self.getStrict = () => strict + + let parserConfig = {} + self.parserConfiguration = function parserConfiguration (config) { + argsert('', [config], arguments.length) + parserConfig = config + return self + } + self.getParserConfiguration = () => parserConfig + + self.showHelp = function (level) { + argsert('[string|function]', [level], arguments.length) + if (!self.parsed) self._parseArgs(processArgs) // run parser, if it has not already been executed. + if (command.hasDefaultCommand()) { + context.resets++ // override the restriction on top-level positoinals. + command.runDefaultBuilderOn(self, true) + } + usage.showHelp(level) + return self + } + + let versionOpt = null + self.version = function version (opt, msg, ver) { + const defaultVersionOpt = 'version' + argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length) + + // nuke the key previously configured + // to return version #. + if (versionOpt) { + deleteFromParserHintObject(versionOpt) + usage.version(undefined) + versionOpt = null + } + + if (arguments.length === 0) { + ver = guessVersion() + opt = defaultVersionOpt + } else if (arguments.length === 1) { + if (opt === false) { // disable default 'version' key. + return self + } + ver = opt + opt = defaultVersionOpt + } else if (arguments.length === 2) { + ver = msg + msg = null + } + + versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt + msg = msg || usage.deferY18nLookup('Show version number') + + usage.version(ver || undefined) + self.boolean(versionOpt) + self.describe(versionOpt, msg) + return self + } + + function guessVersion () { + const obj = pkgUp() + + return obj.version || 'unknown' + } + + let helpOpt = null + self.addHelpOpt = self.help = function addHelpOpt (opt, msg) { + const defaultHelpOpt = 'help' + argsert('[string|boolean] [string]', [opt, msg], arguments.length) + + // nuke the key previously configured + // to return help. + if (helpOpt) { + deleteFromParserHintObject(helpOpt) + helpOpt = null + } + + if (arguments.length === 1) { + if (opt === false) return self + } + + // use arguments, fallback to defaults for opt and msg + helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt + self.boolean(helpOpt) + self.describe(helpOpt, msg || usage.deferY18nLookup('Show help')) + return self + } + + const defaultShowHiddenOpt = 'show-hidden' + options.showHiddenOpt = defaultShowHiddenOpt + self.addShowHiddenOpt = self.showHidden = function addShowHiddenOpt (opt, msg) { + argsert('[string|boolean] [string]', [opt, msg], arguments.length) + + if (arguments.length === 1) { + if (opt === false) return self + } + + const showHiddenOpt = typeof opt === 'string' ? opt : defaultShowHiddenOpt + self.boolean(showHiddenOpt) + self.describe(showHiddenOpt, msg || usage.deferY18nLookup('Show hidden options')) + options.showHiddenOpt = showHiddenOpt + return self + } + + self.hide = function hide (key) { + argsert('', [key], arguments.length) + options.hiddenOptions.push(key) + return self + } + + self.showHelpOnFail = function showHelpOnFail (enabled, message) { + argsert('[boolean|string] [string]', [enabled, message], arguments.length) + usage.showHelpOnFail(enabled, message) + return self + } + + var exitProcess = true + self.exitProcess = function (enabled) { + argsert('[boolean]', [enabled], arguments.length) + if (typeof enabled !== 'boolean') { + enabled = true + } + exitProcess = enabled + return self + } + self.getExitProcess = () => exitProcess + + var completionCommand = null + self.completion = function (cmd, desc, fn) { + argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length) + + // a function to execute when generating + // completions can be provided as the second + // or third argument to completion. + if (typeof desc === 'function') { + fn = desc + desc = null + } + + // register the completion command. + completionCommand = cmd || 'completion' + if (!desc && desc !== false) { + desc = 'generate completion script' + } + self.command(completionCommand, desc) + + // a function can be provided + if (fn) completion.registerFunction(fn) + + return self + } + + self.showCompletionScript = function ($0) { + argsert('[string]', [$0], arguments.length) + $0 = $0 || self.$0 + _logger.log(completion.generateCompletionScript($0, completionCommand)) + return self + } + + self.getCompletion = function (args, done) { + argsert(' ', [args, done], arguments.length) + completion.getCompletion(args, done) + } + + self.locale = function (locale) { + argsert('[string]', [locale], arguments.length) + if (arguments.length === 0) { + guessLocale() + return y18n.getLocale() + } + detectLocale = false + y18n.setLocale(locale) + return self + } + + self.updateStrings = self.updateLocale = function (obj) { + argsert('', [obj], arguments.length) + detectLocale = false + y18n.updateLocale(obj) + return self + } + + let detectLocale = true + self.detectLocale = function (detect) { + argsert('', [detect], arguments.length) + detectLocale = detect + return self + } + self.getDetectLocale = () => detectLocale + + var hasOutput = false + var exitError = null + // maybe exit, always capture + // context about why we wanted to exit. + self.exit = (code, err) => { + hasOutput = true + exitError = err + if (exitProcess) process.exit(code) + } + + // we use a custom logger that buffers output, + // so that we can print to non-CLIs, e.g., chat-bots. + const _logger = { + log () { + const args = [] + for (let i = 0; i < arguments.length; i++) args.push(arguments[i]) + if (!self._hasParseCallback()) console.log.apply(console, args) + hasOutput = true + if (output.length) output += '\n' + output += args.join(' ') + }, + error () { + const args = [] + for (let i = 0; i < arguments.length; i++) args.push(arguments[i]) + if (!self._hasParseCallback()) console.error.apply(console, args) + hasOutput = true + if (output.length) output += '\n' + output += args.join(' ') + } + } + self._getLoggerInstance = () => _logger + // has yargs output an error our help + // message in the current execution context. + self._hasOutput = () => hasOutput + + self._setHasOutput = () => { + hasOutput = true + } + + let recommendCommands + self.recommendCommands = function (recommend) { + argsert('[boolean]', [recommend], arguments.length) + recommendCommands = typeof recommend === 'boolean' ? recommend : true + return self + } + + self.getUsageInstance = () => usage + + self.getValidationInstance = () => validation + + self.getCommandInstance = () => command + + self.terminalWidth = () => { + argsert([], 0) + return typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null + } + + Object.defineProperty(self, 'argv', { + get: () => self._parseArgs(processArgs), + enumerable: true + }) + + self._parseArgs = function parseArgs (args, shortCircuit, _skipValidation, commandIndex) { + let skipValidation = !!_skipValidation + args = args || processArgs + + options.__ = y18n.__ + options.configuration = self.getParserConfiguration() + + // Deprecated + let pkgConfig = pkgUp()['yargs'] + if (pkgConfig) { + console.warn('Configuring yargs through package.json is deprecated and will be removed in the next major release, please use the JS API instead.') + options.configuration = Object.assign({}, pkgConfig, options.configuration) + } + + const parsed = Parser.detailed(args, options) + let argv = parsed.argv + if (parseContext) argv = Object.assign({}, argv, parseContext) + const aliases = parsed.aliases + + argv.$0 = self.$0 + self.parsed = parsed + + try { + guessLocale() // guess locale lazily, so that it can be turned off in chain. + + // while building up the argv object, there + // are two passes through the parser. If completion + // is being performed short-circuit on the first pass. + if (shortCircuit) { + return argv + } + + // if there's a handler associated with a + // command defer processing to it. + if (helpOpt) { + // consider any multi-char helpOpt alias as a valid help command + // unless all helpOpt aliases are single-char + // note that parsed.aliases is a normalized bidirectional map :) + const helpCmds = [helpOpt] + .concat(aliases[helpOpt] || []) + .filter(k => k.length > 1) + // check if help should trigger and strip it from _. + if (~helpCmds.indexOf(argv._[argv._.length - 1])) { + argv._.pop() + argv[helpOpt] = true + } + } + + const handlerKeys = command.getCommands() + const requestCompletions = completion.completionKey in argv + const skipRecommendation = argv[helpOpt] || requestCompletions + const skipDefaultCommand = skipRecommendation && (handlerKeys.length > 1 || handlerKeys[0] !== '$0') + + if (argv._.length) { + if (handlerKeys.length) { + let firstUnknownCommand + for (let i = (commandIndex || 0), cmd; argv._[i] !== undefined; i++) { + cmd = String(argv._[i]) + if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) { + // commands are executed using a recursive algorithm that executes + // the deepest command first; we keep track of the position in the + // argv._ array that is currently being executed. + return command.runCommand(cmd, self, parsed, i + 1) + } else if (!firstUnknownCommand && cmd !== completionCommand) { + firstUnknownCommand = cmd + break + } + } + + // run the default command, if defined + if (command.hasDefaultCommand() && !skipDefaultCommand) { + return command.runCommand(null, self, parsed) + } + + // recommend a command if recommendCommands() has + // been enabled, and no commands were found to execute + if (recommendCommands && firstUnknownCommand && !skipRecommendation) { + validation.recommendCommands(firstUnknownCommand, handlerKeys) + } + } + + // generate a completion script for adding to ~/.bashrc. + if (completionCommand && ~argv._.indexOf(completionCommand) && !requestCompletions) { + if (exitProcess) setBlocking(true) + self.showCompletionScript() + self.exit(0) + } + } else if (command.hasDefaultCommand() && !skipDefaultCommand) { + return command.runCommand(null, self, parsed) + } + + // we must run completions first, a user might + // want to complete the --help or --version option. + if (requestCompletions) { + if (exitProcess) setBlocking(true) + + // we allow for asynchronous completions, + // e.g., loading in a list of commands from an API. + const completionArgs = args.slice(args.indexOf(`--${completion.completionKey}`) + 1) + completion.getCompletion(completionArgs, (completions) => { + ;(completions || []).forEach((completion) => { + _logger.log(completion) + }) + + self.exit(0) + }) + return argv + } + + // Handle 'help' and 'version' options + // if we haven't already output help! + if (!hasOutput) { + Object.keys(argv).forEach((key) => { + if (key === helpOpt && argv[key]) { + if (exitProcess) setBlocking(true) + + skipValidation = true + self.showHelp('log') + self.exit(0) + } else if (key === versionOpt && argv[key]) { + if (exitProcess) setBlocking(true) + + skipValidation = true + usage.showVersion() + self.exit(0) + } + }) + } + + // Check if any of the options to skip validation were provided + if (!skipValidation && options.skipValidation.length > 0) { + skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true) + } + + // If the help or version options where used and exitProcess is false, + // or if explicitly skipped, we won't run validations. + if (!skipValidation) { + if (parsed.error) throw new YError(parsed.error.message) + + // if we're executed via bash completion, don't + // bother with validation. + if (!requestCompletions) { + self._runValidation(argv, aliases, {}, parsed.error) + } + } + } catch (err) { + if (err instanceof YError) usage.fail(err.message, err) + else throw err + } + + return argv + } + + self._runValidation = function runValidation (argv, aliases, positionalMap, parseErrors) { + if (parseErrors) throw new YError(parseErrors.message || parseErrors) + validation.nonOptionCount(argv) + validation.requiredArguments(argv) + if (strict) validation.unknownArguments(argv, aliases, positionalMap) + validation.customChecks(argv, aliases) + validation.limitedChoices(argv) + validation.implications(argv) + validation.conflicting(argv) + } + + function guessLocale () { + if (!detectLocale) return + + try { + const { env } = process + const locale = env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE || 'en_US' + self.locale(locale.replace(/[.:].*/, '')) + } catch (err) { + // if we explode looking up locale just noop + // we'll keep using the default language 'en'. + } + } + + // an app should almost always have --version and --help, + // if you *really* want to disable this use .help(false)/.version(false). + self.help() + self.version() + + return self +} + +// rebase an absolute path to a relative one with respect to a base directory +// exported for tests +exports.rebase = rebase +function rebase (base, dir) { + return path.relative(base, dir) +} + + +/***/ }), + +/***/ 4294: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(6651); + + +/***/ }), + +/***/ 6651: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var net = __webpack_require__(1631); +var tls = __webpack_require__(4016); +var http = __webpack_require__(8605); +var https = __webpack_require__(7211); +var events = __webpack_require__(8614); +var assert = __webpack_require__(9059); +var util = __webpack_require__(1669); + + +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; + + +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; +} + +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} + +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} + +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} + + +function TunnelingAgent(options) { + var self = this; + self.options = options || {}; + self.proxyOptions = self.options.proxy || {}; + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; + self.requests = []; + self.sockets = []; + + self.on('free', function onFree(socket, host, port, localAddress) { + var options = toOptions(host, port, localAddress); + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i]; + if (pending.host === options.host && pending.port === options.port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1); + pending.request.onSocket(socket); + return; + } + } + socket.destroy(); + self.removeSocket(socket); + }); +} +util.inherits(TunnelingAgent, events.EventEmitter); + +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); + + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; + } + + // If we are under maxSockets create a new one. + self.createSocket(options, function(socket) { + socket.on('free', onFree); + socket.on('close', onCloseOrRemove); + socket.on('agentRemove', onCloseOrRemove); + req.onSocket(socket); + + function onFree() { + self.emit('free', socket, options); + } + + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); + } + }); +}; + +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); + + var connectOptions = mergeOptions({}, self.proxyOptions, { + method: 'CONNECT', + path: options.host + ':' + options.port, + agent: false, + headers: { + host: options.host + ':' + options.port + } + }); + if (options.localAddress) { + connectOptions.localAddress = options.localAddress; + } + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); + } + + debug('making CONNECT request'); + var connectReq = self.request(connectOptions); + connectReq.useChunkedEncodingByDefault = false; // for v0.6 + connectReq.once('response', onResponse); // for v0.6 + connectReq.once('upgrade', onUpgrade); // for v0.6 + connectReq.once('connect', onConnect); // for v0.7 or later + connectReq.once('error', onError); + connectReq.end(); + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } + + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); + + if (res.statusCode !== 200) { + debug('tunneling socket could not be established, statusCode=%d', + res.statusCode); + socket.destroy(); + var error = new Error('tunneling socket could not be established, ' + + 'statusCode=' + res.statusCode); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + if (head.length > 0) { + debug('got illegal response body from proxy'); + socket.destroy(); + var error = new Error('got illegal response body from proxy'); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); + } + + function onError(cause) { + connectReq.removeAllListeners(); + + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + } +}; + +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; + } + this.sockets.splice(pos, 1); + + var pending = this.requests.shift(); + if (pending) { + // 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(pending, function(socket) { + pending.request.onSocket(socket); + }); + } +}; + +function createSecureSocket(options, cb) { + var self = this; + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + var hostHeader = options.request.getHeader('host'); + var tlsOptions = mergeOptions({}, self.options, { + socket: socket, + servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host + }); + + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); +} + + +function toOptions(host, port, localAddress) { + if (typeof host === 'string') { // since v0.10 + return { + host: host, + port: port, + localAddress: localAddress + }; + } + return host; // for v0.11 or later +} + +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i]; + if (typeof overrides === 'object') { + var keys = Object.keys(overrides); + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j]; + if (overrides[k] !== undefined) { + target[k] = overrides[k]; + } + } + } + } + return target; +} + + +var debug; +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0]; + } else { + args.unshift('TUNNEL:'); + } + console.error.apply(console, args); + } +} else { + debug = function() {}; +} +exports.debug = debug; // for test + + +/***/ }), + +/***/ 5030: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } + + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + + return ""; +} + +exports.getUserAgent = getUserAgent; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 5278: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = __webpack_require__(1669).deprecate; + + +/***/ }), + +/***/ 3664: +/***/ ((module) => { + +"use strict"; + + +module.exports = function whichModule (exported) { + for (var i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) { + mod = require.cache[files[i]] + if (mod.exports === exported) return mod + } + return null +} + + +/***/ }), + +/***/ 2940: +/***/ ((module) => { + +// 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) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + 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 + } +} + + +/***/ }), + +/***/ 8138: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var fs = __webpack_require__(5747) +var path = __webpack_require__(5622) +var util = __webpack_require__(1669) + +function Y18N (opts) { + // configurable options. + opts = opts || {} + this.directory = opts.directory || './locales' + this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true + this.locale = opts.locale || 'en' + this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true + + // internal stuff. + this.cache = {} + this.writeQueue = [] +} + +Y18N.prototype.__ = function () { + if (typeof arguments[0] !== 'string') { + return this._taggedLiteral.apply(this, arguments) + } + var args = Array.prototype.slice.call(arguments) + var str = args.shift() + var cb = function () {} // start with noop. + + if (typeof args[args.length - 1] === 'function') cb = args.pop() + cb = cb || function () {} // noop. + + if (!this.cache[this.locale]) this._readLocaleFile() + + // we've observed a new string, update the language file. + if (!this.cache[this.locale][str] && this.updateFiles) { + this.cache[this.locale][str] = str + + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite([this.directory, this.locale, cb]) + } else { + cb() + } + + return util.format.apply(util, [this.cache[this.locale][str] || str].concat(args)) +} + +Y18N.prototype._taggedLiteral = function (parts) { + var args = arguments + var str = '' + parts.forEach(function (part, i) { + var arg = args[i + 1] + str += part + if (typeof arg !== 'undefined') { + str += '%s' + } + }) + return this.__.apply(null, [str].concat([].slice.call(arguments, 1))) +} + +Y18N.prototype._enqueueWrite = function (work) { + this.writeQueue.push(work) + if (this.writeQueue.length === 1) this._processWriteQueue() +} + +Y18N.prototype._processWriteQueue = function () { + var _this = this + var work = this.writeQueue[0] + + // destructure the enqueued work. + var directory = work[0] + var locale = work[1] + var cb = work[2] + + var languageFile = this._resolveLocaleFile(directory, locale) + var serializedLocale = JSON.stringify(this.cache[locale], null, 2) + + fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) { + _this.writeQueue.shift() + if (_this.writeQueue.length > 0) _this._processWriteQueue() + cb(err) + }) +} + +Y18N.prototype._readLocaleFile = function () { + var localeLookup = {} + var languageFile = this._resolveLocaleFile(this.directory, this.locale) + + try { + localeLookup = JSON.parse(fs.readFileSync(languageFile, 'utf-8')) + } catch (err) { + if (err instanceof SyntaxError) { + err.message = 'syntax error in ' + languageFile + } + + if (err.code === 'ENOENT') localeLookup = {} + else throw err + } + + this.cache[this.locale] = localeLookup +} + +Y18N.prototype._resolveLocaleFile = function (directory, locale) { + var file = path.resolve(directory, './', locale + '.json') + if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) { + // attempt fallback to language only + var languageFile = path.resolve(directory, './', locale.split('_')[0] + '.json') + if (this._fileExistsSync(languageFile)) file = languageFile + } + return file +} + +// this only exists because fs.existsSync() "will be deprecated" +// see https://nodejs.org/api/fs.html#fs_fs_existssync_path +Y18N.prototype._fileExistsSync = function (file) { + try { + return fs.statSync(file).isFile() + } catch (err) { + return false + } +} + +Y18N.prototype.__n = function () { + var args = Array.prototype.slice.call(arguments) + var singular = args.shift() + var plural = args.shift() + var quantity = args.shift() + + var cb = function () {} // start with noop. + if (typeof args[args.length - 1] === 'function') cb = args.pop() + + if (!this.cache[this.locale]) this._readLocaleFile() + + var str = quantity === 1 ? singular : plural + if (this.cache[this.locale][singular]) { + str = this.cache[this.locale][singular][quantity === 1 ? 'one' : 'other'] + } + + // we've observed a new string, update the language file. + if (!this.cache[this.locale][singular] && this.updateFiles) { + this.cache[this.locale][singular] = { + one: singular, + other: plural + } + + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite([this.directory, this.locale, cb]) + } else { + cb() + } + + // if a %d placeholder is provided, add quantity + // to the arguments expanded by util.format. + var values = [str] + if (~str.indexOf('%d')) values.push(quantity) + + return util.format.apply(util, values.concat(args)) +} + +Y18N.prototype.setLocale = function (locale) { + this.locale = locale +} + +Y18N.prototype.getLocale = function () { + return this.locale +} + +Y18N.prototype.updateLocale = function (obj) { + if (!this.cache[this.locale]) this._readLocaleFile() + + for (var key in obj) { + this.cache[this.locale][key] = obj[key] + } +} + +module.exports = function (opts) { + var y18n = new Y18N(opts) + + // bind all functions to y18n, so that + // they can be used in isolation. + for (var key in y18n) { + if (typeof y18n[key] === 'function') { + y18n[key] = y18n[key].bind(y18n) + } + } + + return y18n +} + + +/***/ }), + +/***/ 2877: +/***/ ((module) => { + +module.exports = eval("require")("encoding"); + + +/***/ }), + +/***/ 5764: +/***/ ((module) => { + +module.exports = eval("require")("mongodb-client-encryption"); + + +/***/ }), + +/***/ 3225: +/***/ ((module) => { + +"use strict"; +module.exports = {"i8":"3.6.2"}; + +/***/ }), + +/***/ 8686: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"name\":\"pino\",\"version\":\"5.17.0\",\"description\":\"super fast, all natural json logger\",\"main\":\"pino.js\",\"browser\":\"./browser.js\",\"files\":[\"pino.js\",\"bin.js\",\"browser.js\",\"pretty.js\",\"usage.txt\",\"test\",\"docs\",\"example.js\",\"lib\"],\"scripts\":{\"docs\":\"docsify serve\",\"browser-test\":\"airtap --local 8080 test/browser*test.js\",\"test\":\"standard | snazzy && cross-env NODE_OPTIONS=\\\"--no-warnings -r qodaa\\\" tap --no-esm -j 4 --no-cov test/*test.js\",\"ci\":\"standard | snazzy && cross-env TAP_TIMEOUT=480000 NODE_OPTIONS=\\\"--no-warnings -r qodaa\\\" tap --no-esm -j 4 --100 test/*test.js\",\"cov-ci\":\"cross-env TAP_TIMEOUT=480000 NODE_OPTIONS=\\\"--no-warnings -r qodaa\\\" tap --no-esm -j 4 --100 --coverage-report=lcov test/*test.js\",\"cov-ui\":\"cross-env NODE_OPTIONS=\\\"--no-warnings -r qodaa\\\" tap --no-esm -j 4 --coverage-report=html test/*test.js\",\"bench\":\"node benchmarks/utils/runbench all\",\"bench-basic\":\"node benchmarks/utils/runbench basic\",\"bench-object\":\"node benchmarks/utils/runbench object\",\"bench-deep-object\":\"node benchmarks/utils/runbench deep-object\",\"bench-multi-arg\":\"node benchmarks/utils/runbench multi-arg\",\"bench-longs-tring\":\"node benchmarks/utils/runbench long-string\",\"bench-child\":\"node benchmarks/utils/runbench child\",\"bench-child-child\":\"node benchmarks/utils/runbench child-child\",\"bench-child-creation\":\"node benchmarks/utils/runbench child-creation\",\"update-bench-doc\":\"node benchmarks/utils/generate-benchmark-doc > docs/benchmarks.md\"},\"bin\":{\"pino\":\"./bin.js\"},\"precommit\":\"test\",\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/pinojs/pino.git\"},\"keywords\":[\"fast\",\"logger\",\"stream\",\"json\"],\"author\":\"Matteo Collina \",\"contributors\":[\"David Mark Clements \",\"James Sumners \",\"Thomas Watson Steen (https://twitter.com/wa7son)\"],\"license\":\"MIT\",\"bugs\":{\"url\":\"https://github.com/pinojs/pino/issues\"},\"homepage\":\"http://getpino.io\",\"devDependencies\":{\"airtap\":\"2.0.2\",\"benchmark\":\"^2.1.4\",\"bole\":\"^3.0.2\",\"bunyan\":\"^1.8.12\",\"cross-env\":\"^5.2.1\",\"docsify-cli\":\"^4.2.1\",\"execa\":\"^1.0.0\",\"fastbench\":\"^1.0.1\",\"flush-write-stream\":\"^2.0.0\",\"import-fresh\":\"^3.0.0\",\"log\":\"^5.0.0\",\"loglevel\":\"^1.6.4\",\"pino-pretty\":\"^2.6.1\",\"pre-commit\":\"^1.2.2\",\"proxyquire\":\"^2.1.3\",\"pump\":\"^3.0.0\",\"qodaa\":\"^1.0.1\",\"semver\":\"^6.3.0\",\"snazzy\":\"^8.0.0\",\"split2\":\"^3.1.1\",\"standard\":\"^14.2.0\",\"steed\":\"^1.1.3\",\"tap\":\"^12.7.0\",\"tape\":\"^4.11.0\",\"through2\":\"^3.0.1\",\"winston\":\"^3.2.1\"},\"dependencies\":{\"fast-redact\":\"^2.0.0\",\"fast-safe-stringify\":\"^2.0.7\",\"flatstr\":\"^1.0.12\",\"pino-std-serializers\":\"^2.4.2\",\"quick-format-unescaped\":\"^3.0.3\",\"sonic-boom\":\"^0.7.5\"}}"); + +/***/ }), + +/***/ 9059: +/***/ ((module) => { + +"use strict"; +module.exports = require("assert"); + +/***/ }), + +/***/ 4293: +/***/ ((module) => { + +"use strict"; +module.exports = require("buffer"); + +/***/ }), + +/***/ 3129: +/***/ ((module) => { + +"use strict"; +module.exports = require("child_process"); + +/***/ }), + +/***/ 6417: +/***/ ((module) => { + +"use strict"; +module.exports = require("crypto"); + +/***/ }), + +/***/ 881: +/***/ ((module) => { + +"use strict"; +module.exports = require("dns"); + +/***/ }), + +/***/ 8614: +/***/ ((module) => { + +"use strict"; +module.exports = require("events"); + +/***/ }), + +/***/ 5747: +/***/ ((module) => { + +"use strict"; +module.exports = require("fs"); + +/***/ }), + +/***/ 8605: +/***/ ((module) => { + +"use strict"; +module.exports = require("http"); + +/***/ }), + +/***/ 7211: +/***/ ((module) => { + +"use strict"; +module.exports = require("https"); + +/***/ }), + +/***/ 2282: +/***/ ((module) => { + +"use strict"; +module.exports = require("module"); + +/***/ }), + +/***/ 1631: +/***/ ((module) => { + +"use strict"; +module.exports = require("net"); + +/***/ }), + +/***/ 2087: +/***/ ((module) => { + +"use strict"; +module.exports = require("os"); + +/***/ }), + +/***/ 5622: +/***/ ((module) => { + +"use strict"; +module.exports = require("path"); + +/***/ }), + +/***/ 1191: +/***/ ((module) => { + +"use strict"; +module.exports = require("querystring"); + +/***/ }), + +/***/ 2413: +/***/ ((module) => { + +"use strict"; +module.exports = require("stream"); + +/***/ }), + +/***/ 4016: +/***/ ((module) => { + +"use strict"; +module.exports = require("tls"); + +/***/ }), + +/***/ 8835: +/***/ ((module) => { + +"use strict"; +module.exports = require("url"); + +/***/ }), + +/***/ 1669: +/***/ ((module) => { + +"use strict"; +module.exports = require("util"); + +/***/ }), + +/***/ 2184: +/***/ ((module) => { + +"use strict"; +module.exports = require("vm"); + +/***/ }), + +/***/ 8761: +/***/ ((module) => { + +"use strict"; +module.exports = require("zlib"); + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __webpack_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(1689); +/******/ })() +; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map new file mode 100644 index 0000000..eb14f5c --- /dev/null +++ b/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../lib/CLIEntrypoint.js","../lib/CodeRepository.js","../lib/DataStore.js","../lib/File.js","../lib/MongoDB.js","../lib/ProcessId.js","../lib/TaskInformationGenerator.js","../lib/TaskManagementSystem.js","../lib/TaskUpdater.js","../lib/TodoActionsMain.js","../lib/TodoParser.js","../node_modules/@actions/core/lib/command.js","../node_modules/@actions/core/lib/core.js","../node_modules/@actions/github/lib/context.js","../node_modules/@actions/github/lib/github.js","../node_modules/@actions/github/lib/internal/utils.js","../node_modules/@actions/github/lib/utils.js","../node_modules/@actions/http-client/index.js","../node_modules/@actions/http-client/proxy.js","../node_modules/@hapi/bourne/lib/index.js","../node_modules/@octokit/auth-token/dist-node/index.js","../node_modules/@octokit/core/dist-node/index.js","../node_modules/@octokit/endpoint/dist-node/index.js","../node_modules/@octokit/endpoint/node_modules/is-plain-object/dist/is-plain-object.js","../node_modules/@octokit/graphql/dist-node/index.js","../node_modules/@octokit/plugin-paginate-rest/dist-node/index.js","../node_modules/@octokit/plugin-request-log/dist-node/index.js","../node_modules/@octokit/plugin-rest-endpoint-methods/dist-node/index.js","../node_modules/@octokit/request-error/dist-node/index.js","../node_modules/@octokit/request/dist-node/index.js","../node_modules/@octokit/request/node_modules/is-plain-object/dist/is-plain-object.js","../node_modules/@octokit/rest/dist-node/index.js","../node_modules/atomic-sleep/index.js","../node_modules/aws4/aws4.js","../node_modules/aws4/lru.js","../node_modules/before-after-hook/index.js","../node_modules/before-after-hook/lib/add.js","../node_modules/before-after-hook/lib/register.js","../node_modules/before-after-hook/lib/remove.js","../node_modules/bl/bl.js","../node_modules/bson/index.js","../node_modules/bson/lib/bson/binary.js","../node_modules/bson/lib/bson/bson.js","../node_modules/bson/lib/bson/code.js","../node_modules/bson/lib/bson/db_ref.js","../node_modules/bson/lib/bson/decimal128.js","../node_modules/bson/lib/bson/double.js","../node_modules/bson/lib/bson/float_parser.js","../node_modules/bson/lib/bson/int_32.js","../node_modules/bson/lib/bson/long.js","../node_modules/bson/lib/bson/map.js","../node_modules/bson/lib/bson/max_key.js","../node_modules/bson/lib/bson/min_key.js","../node_modules/bson/lib/bson/objectid.js","../node_modules/bson/lib/bson/parser/calculate_size.js","../node_modules/bson/lib/bson/parser/deserializer.js","../node_modules/bson/lib/bson/parser/serializer.js","../node_modules/bson/lib/bson/parser/utils.js","../node_modules/bson/lib/bson/regexp.js","../node_modules/bson/lib/bson/symbol.js","../node_modules/bson/lib/bson/timestamp.js","../node_modules/camelcase/index.js","../node_modules/core-util-is/lib/util.js","../node_modules/dateformat/lib/dateformat.js","../node_modules/decamelize/index.js","../node_modules/denque/index.js","../node_modules/deprecation/dist-node/index.js","../node_modules/emoji-regex/index.js","../node_modules/escape-string-regexp/index.js","../node_modules/fast-redact/index.js","../node_modules/fast-redact/lib/modifiers.js","../node_modules/fast-redact/lib/parse.js","../node_modules/fast-redact/lib/redactor.js","../node_modules/fast-redact/lib/restorer.js","../node_modules/fast-redact/lib/rx.js","../node_modules/fast-redact/lib/state.js","../node_modules/fast-redact/lib/validator.js","../node_modules/fast-safe-stringify/index.js","../node_modules/flatstr/index.js","../node_modules/get-caller-file/index.js","../node_modules/has-flag/index.js","../node_modules/inherits/inherits.js","../node_modules/inherits/inherits_browser.js","../node_modules/invariant/invariant.js","../node_modules/is-fullwidth-code-point/index.js","../node_modules/isarray/index.js","../node_modules/jmespath/jmespath.js","../node_modules/memory-pager/index.js","../node_modules/mongodb/index.js","../node_modules/mongodb/lib/admin.js","../node_modules/mongodb/lib/aggregation_cursor.js","../node_modules/mongodb/lib/apm.js","../node_modules/mongodb/lib/async/async_iterator.js","../node_modules/mongodb/lib/bulk/common.js","../node_modules/mongodb/lib/bulk/ordered.js","../node_modules/mongodb/lib/bulk/unordered.js","../node_modules/mongodb/lib/change_stream.js","../node_modules/mongodb/lib/cmap/connection.js","../node_modules/mongodb/lib/cmap/connection_pool.js","../node_modules/mongodb/lib/cmap/errors.js","../node_modules/mongodb/lib/cmap/events.js","../node_modules/mongodb/lib/cmap/message_stream.js","../node_modules/mongodb/lib/cmap/stream_description.js","../node_modules/mongodb/lib/collection.js","../node_modules/mongodb/lib/command_cursor.js","../node_modules/mongodb/lib/constants.js","../node_modules/mongodb/lib/core/auth/auth_provider.js","../node_modules/mongodb/lib/core/auth/defaultAuthProviders.js","../node_modules/mongodb/lib/core/auth/gssapi.js","../node_modules/mongodb/lib/core/auth/mongo_credentials.js","../node_modules/mongodb/lib/core/auth/mongocr.js","../node_modules/mongodb/lib/core/auth/mongodb_aws.js","../node_modules/mongodb/lib/core/auth/plain.js","../node_modules/mongodb/lib/core/auth/scram.js","../node_modules/mongodb/lib/core/auth/x509.js","../node_modules/mongodb/lib/core/connection/apm.js","../node_modules/mongodb/lib/core/connection/command_result.js","../node_modules/mongodb/lib/core/connection/commands.js","../node_modules/mongodb/lib/core/connection/connect.js","../node_modules/mongodb/lib/core/connection/connection.js","../node_modules/mongodb/lib/core/connection/logger.js","../node_modules/mongodb/lib/core/connection/msg.js","../node_modules/mongodb/lib/core/connection/pool.js","../node_modules/mongodb/lib/core/connection/utils.js","../node_modules/mongodb/lib/core/cursor.js","../node_modules/mongodb/lib/core/error.js","../node_modules/mongodb/lib/core/index.js","../node_modules/mongodb/lib/core/sdam/common.js","../node_modules/mongodb/lib/core/sdam/events.js","../node_modules/mongodb/lib/core/sdam/monitor.js","../node_modules/mongodb/lib/core/sdam/server.js","../node_modules/mongodb/lib/core/sdam/server_description.js","../node_modules/mongodb/lib/core/sdam/server_selection.js","../node_modules/mongodb/lib/core/sdam/srv_polling.js","../node_modules/mongodb/lib/core/sdam/topology.js","../node_modules/mongodb/lib/core/sdam/topology_description.js","../node_modules/mongodb/lib/core/sessions.js","../node_modules/mongodb/lib/core/topologies/mongos.js","../node_modules/mongodb/lib/core/topologies/read_preference.js","../node_modules/mongodb/lib/core/topologies/replset.js","../node_modules/mongodb/lib/core/topologies/replset_state.js","../node_modules/mongodb/lib/core/topologies/server.js","../node_modules/mongodb/lib/core/topologies/shared.js","../node_modules/mongodb/lib/core/transactions.js","../node_modules/mongodb/lib/core/uri_parser.js","../node_modules/mongodb/lib/core/utils.js","../node_modules/mongodb/lib/core/wireprotocol/command.js","../node_modules/mongodb/lib/core/wireprotocol/compression.js","../node_modules/mongodb/lib/core/wireprotocol/constants.js","../node_modules/mongodb/lib/core/wireprotocol/get_more.js","../node_modules/mongodb/lib/core/wireprotocol/index.js","../node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js","../node_modules/mongodb/lib/core/wireprotocol/query.js","../node_modules/mongodb/lib/core/wireprotocol/shared.js","../node_modules/mongodb/lib/core/wireprotocol/write_command.js","../node_modules/mongodb/lib/cursor.js","../node_modules/mongodb/lib/db.js","../node_modules/mongodb/lib/dynamic_loaders.js","../node_modules/mongodb/lib/error.js","../node_modules/mongodb/lib/gridfs-stream/download.js","../node_modules/mongodb/lib/gridfs-stream/index.js","../node_modules/mongodb/lib/gridfs-stream/upload.js","../node_modules/mongodb/lib/gridfs/chunk.js","../node_modules/mongodb/lib/gridfs/grid_store.js","../node_modules/mongodb/lib/mongo_client.js","../node_modules/mongodb/lib/operations/add_user.js","../node_modules/mongodb/lib/operations/aggregate.js","../node_modules/mongodb/lib/operations/bulk_write.js","../node_modules/mongodb/lib/operations/collection_ops.js","../node_modules/mongodb/lib/operations/collections.js","../node_modules/mongodb/lib/operations/command.js","../node_modules/mongodb/lib/operations/command_v2.js","../node_modules/mongodb/lib/operations/common_functions.js","../node_modules/mongodb/lib/operations/connect.js","../node_modules/mongodb/lib/operations/count.js","../node_modules/mongodb/lib/operations/count_documents.js","../node_modules/mongodb/lib/operations/create_collection.js","../node_modules/mongodb/lib/operations/create_indexes.js","../node_modules/mongodb/lib/operations/cursor_ops.js","../node_modules/mongodb/lib/operations/db_ops.js","../node_modules/mongodb/lib/operations/delete_many.js","../node_modules/mongodb/lib/operations/delete_one.js","../node_modules/mongodb/lib/operations/distinct.js","../node_modules/mongodb/lib/operations/drop.js","../node_modules/mongodb/lib/operations/drop_index.js","../node_modules/mongodb/lib/operations/drop_indexes.js","../node_modules/mongodb/lib/operations/estimated_document_count.js","../node_modules/mongodb/lib/operations/execute_db_admin_command.js","../node_modules/mongodb/lib/operations/execute_operation.js","../node_modules/mongodb/lib/operations/find.js","../node_modules/mongodb/lib/operations/find_and_modify.js","../node_modules/mongodb/lib/operations/find_one.js","../node_modules/mongodb/lib/operations/find_one_and_delete.js","../node_modules/mongodb/lib/operations/find_one_and_replace.js","../node_modules/mongodb/lib/operations/find_one_and_update.js","../node_modules/mongodb/lib/operations/geo_haystack_search.js","../node_modules/mongodb/lib/operations/index_exists.js","../node_modules/mongodb/lib/operations/index_information.js","../node_modules/mongodb/lib/operations/indexes.js","../node_modules/mongodb/lib/operations/insert_many.js","../node_modules/mongodb/lib/operations/insert_one.js","../node_modules/mongodb/lib/operations/is_capped.js","../node_modules/mongodb/lib/operations/list_collections.js","../node_modules/mongodb/lib/operations/list_databases.js","../node_modules/mongodb/lib/operations/list_indexes.js","../node_modules/mongodb/lib/operations/map_reduce.js","../node_modules/mongodb/lib/operations/operation.js","../node_modules/mongodb/lib/operations/options_operation.js","../node_modules/mongodb/lib/operations/profiling_level.js","../node_modules/mongodb/lib/operations/re_index.js","../node_modules/mongodb/lib/operations/remove_user.js","../node_modules/mongodb/lib/operations/rename.js","../node_modules/mongodb/lib/operations/replace_one.js","../node_modules/mongodb/lib/operations/run_command.js","../node_modules/mongodb/lib/operations/set_profiling_level.js","../node_modules/mongodb/lib/operations/stats.js","../node_modules/mongodb/lib/operations/update_many.js","../node_modules/mongodb/lib/operations/update_one.js","../node_modules/mongodb/lib/operations/validate_collection.js","../node_modules/mongodb/lib/read_concern.js","../node_modules/mongodb/lib/topologies/mongos.js","../node_modules/mongodb/lib/topologies/native_topology.js","../node_modules/mongodb/lib/topologies/replset.js","../node_modules/mongodb/lib/topologies/server.js","../node_modules/mongodb/lib/topologies/topology_base.js","../node_modules/mongodb/lib/url_parser.js","../node_modules/mongodb/lib/utils.js","../node_modules/mongodb/lib/write_concern.js","../node_modules/node-fetch/lib/index.js","../node_modules/once/once.js","../node_modules/p-limit/index.js","../node_modules/p-try/index.js","../node_modules/pino-pretty/index.js","../node_modules/pino-pretty/lib/colors.js","../node_modules/pino-pretty/lib/constants.js","../node_modules/pino-pretty/lib/utils.js","../node_modules/pino-pretty/node_modules/ansi-styles/index.js","../node_modules/pino-pretty/node_modules/chalk/index.js","../node_modules/pino-pretty/node_modules/chalk/templates.js","../node_modules/pino-pretty/node_modules/color-convert/conversions.js","../node_modules/pino-pretty/node_modules/color-convert/index.js","../node_modules/pino-pretty/node_modules/color-convert/route.js","../node_modules/pino-pretty/node_modules/color-name/index.js","../node_modules/pino-pretty/node_modules/supports-color/index.js","../node_modules/pino-std-serializers/index.js","../node_modules/pino-std-serializers/lib/err.js","../node_modules/pino-std-serializers/lib/req.js","../node_modules/pino-std-serializers/lib/res.js","../node_modules/pino/lib/levels.js","../node_modules/pino/lib/meta.js","../node_modules/pino/lib/proto.js","../node_modules/pino/lib/redaction.js","../node_modules/pino/lib/symbols.js","../node_modules/pino/lib/time.js","../node_modules/pino/lib/tools.js","../node_modules/pino/pino.js","../node_modules/process-nextick-args/index.js","../node_modules/quick-format-unescaped/index.js","../node_modules/readable-stream/lib/_stream_duplex.js","../node_modules/readable-stream/lib/_stream_passthrough.js","../node_modules/readable-stream/lib/_stream_readable.js","../node_modules/readable-stream/lib/_stream_transform.js","../node_modules/readable-stream/lib/_stream_writable.js","../node_modules/readable-stream/lib/internal/streams/BufferList.js","../node_modules/readable-stream/lib/internal/streams/destroy.js","../node_modules/readable-stream/lib/internal/streams/stream.js","../node_modules/readable-stream/node_modules/safe-buffer/index.js","../node_modules/readable-stream/readable.js","../node_modules/require-directory/index.js","../node_modules/require-main-filename/index.js","../node_modules/require_optional/index.js","../node_modules/require_optional/node_modules/resolve-from/index.js","../node_modules/safe-buffer/index.js","../node_modules/saslprep/index.js","../node_modules/saslprep/lib/memory-code-points.js","../node_modules/semver/semver.js","../node_modules/set-blocking/index.js","../node_modules/sonic-boom/index.js","../node_modules/sparse-bitfield/index.js","../node_modules/string-width/index.js","../node_modules/string-width/node_modules/ansi-regex/index.js","../node_modules/string-width/node_modules/strip-ansi/index.js","../node_modules/string_decoder/lib/string_decoder.js","../node_modules/string_decoder/node_modules/safe-buffer/index.js","../node_modules/tkt/lib/CLI.js","../node_modules/tkt/lib/Invariant.js","../node_modules/tkt/lib/Logging.js","../node_modules/tkt/lib/index.js","../node_modules/tkt/node_modules/ansi-regex/index.js","../node_modules/tkt/node_modules/ansi-styles/index.js","../node_modules/tkt/node_modules/cliui/index.js","../node_modules/tkt/node_modules/color-convert/conversions.js","../node_modules/tkt/node_modules/color-convert/index.js","../node_modules/tkt/node_modules/color-convert/route.js","../node_modules/tkt/node_modules/color-name/index.js","../node_modules/tkt/node_modules/find-up/index.js","../node_modules/tkt/node_modules/locate-path/index.js","../node_modules/tkt/node_modules/p-locate/index.js","../node_modules/tkt/node_modules/path-exists/index.js","../node_modules/tkt/node_modules/strip-ansi/index.js","../node_modules/tkt/node_modules/wrap-ansi/index.js","../node_modules/tkt/node_modules/yargs-parser/index.js","../node_modules/tkt/node_modules/yargs-parser/lib/tokenize-arg-string.js","../node_modules/tkt/node_modules/yargs/index.js","../node_modules/tkt/node_modules/yargs/lib/apply-extends.js","../node_modules/tkt/node_modules/yargs/lib/argsert.js","../node_modules/tkt/node_modules/yargs/lib/command.js","../node_modules/tkt/node_modules/yargs/lib/completion-templates.js","../node_modules/tkt/node_modules/yargs/lib/completion.js","../node_modules/tkt/node_modules/yargs/lib/decamelize.js","../node_modules/tkt/node_modules/yargs/lib/is-promise.js","../node_modules/tkt/node_modules/yargs/lib/levenshtein.js","../node_modules/tkt/node_modules/yargs/lib/middleware.js","../node_modules/tkt/node_modules/yargs/lib/obj-filter.js","../node_modules/tkt/node_modules/yargs/lib/usage.js","../node_modules/tkt/node_modules/yargs/lib/validation.js","../node_modules/tkt/node_modules/yargs/lib/yerror.js","../node_modules/tkt/node_modules/yargs/yargs.js","../node_modules/tunnel/index.js","../node_modules/tunnel/lib/tunnel.js","../node_modules/universal-user-agent/dist-node/index.js","../node_modules/util-deprecate/node.js","../node_modules/which-module/index.js","../node_modules/wrappy/wrappy.js","../node_modules/y18n/index.js","../node_modules/@vercel/ncc/dist/ncc/@@notfound.js","../node:\"assert\"","../node:\"buffer\"","../node:\"child_process\"","../node:\"crypto\"","../node:\"dns\"","../node:\"events\"","../node:\"fs\"","../node:\"http\"","../node:\"https\"","../node:\"module\"","../node:\"net\"","../node:\"os\"","../node:\"path\"","../node:\"querystring\"","../node:\"stream\"","../node:\"tls\"","../node:\"url\"","../node:\"util\"","../node:\"vm\"","../node:\"zlib\"","/webpack/bootstrap","/webpack/runtime/node module decorator","/webpack/runtime/compat","/webpack/startup"],"sourcesContent":["\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tkt_1 = require(\"tkt\");\nconst TodoActionsMain_1 = require(\"./TodoActionsMain\");\nconst MongoDB = __importStar(require(\"./MongoDB\"));\ntkt_1.cli()\n .command('$0', 'Collect TODOs and create issues', {}, (args) => __awaiter(void 0, void 0, void 0, function* () {\n yield TodoActionsMain_1.runMain();\n yield MongoDB.close();\n}))\n .parse();\n","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.scanCodeRepository = exports.repoContext = void 0;\nconst core_1 = require(\"@actions/core\");\nconst github_1 = require(\"@actions/github\");\nconst fs_1 = require(\"fs\");\nconst tkt_1 = require(\"tkt\");\nconst child_process_1 = require(\"child_process\");\nconst File_1 = require(\"./File\");\nconst log = tkt_1.logger('CodeRepository');\nconst event = process.env.GITHUB_EVENT_PATH && fs_1.existsSync(process.env.GITHUB_EVENT_PATH)\n ? (log.debug('Found GitHub Action event file'),\n JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8')))\n : (log.debug('No GitHub Action event file found'), null);\nexports.repoContext = {\n repositoryNodeId: process.env.GITHUB_REPO_NODE_ID ||\n (event && event.repository && event.repository.node_id) ||\n tkt_1.invariant(false, 'GitHub Repo Node ID not found, either in GitHub Action event payload and GITHUB_REPO_NODE_ID environment variable.'),\n repositoryOwner: process.env.GITHUB_REPO_OWNER ||\n (event && event.repository && event.repository.full_name.split('/')[0]) ||\n tkt_1.invariant(false, 'GitHub Repo Owner not found, either in GitHub Action event payload and GITHUB_REPO_OWNER environment variable.'),\n repositoryName: process.env.GITHUB_REPO_NAME ||\n (event && event.repository && event.repository.full_name.split('/')[1]) ||\n tkt_1.invariant(false, 'GitHub Repo Name not found, either in GitHub Action event payload and GITHUB_REPO_NAME environment variable.'),\n defaultBranch: process.env.GITHUB_REPO_DEFAULT_BRANCH ||\n (event && event.repository && event.repository.default_branch) ||\n tkt_1.invariant(false, 'GitHub Repo Default Branch not found, either in GitHub Action event payload and GITHUB_REPO_DEFAULT_BRANCH environment variable.'),\n};\nfunction scanCodeRepository() {\n return __awaiter(this, void 0, void 0, function* () {\n log.info('Search for files with TODO tags...');\n const filesWithTodoMarker = child_process_1.execSync('git grep -Il TODO', {\n encoding: 'utf8',\n })\n .split('\\n')\n .filter(name => name);\n const files = [];\n log.info('Parsing TODO tags...');\n for (const filePath of filesWithTodoMarker) {\n const file = new File_1.File(filePath);\n files.push(file);\n }\n return {\n files,\n saveChanges(commitMessage, commitBody) {\n return __awaiter(this, void 0, void 0, function* () {\n const changedFiles = files.filter(file => file.contents.changed);\n log.info('Files changed: %s', changedFiles.length);\n if (changedFiles.length === 0) {\n return;\n }\n for (const file of changedFiles) {\n file.save();\n }\n log.info(`\"${commitMessage}\"`, `\"${commitBody}\"`);\n process.env.GIT_COMMITTER_NAME = 'todo-actions';\n process.env.GIT_AUTHOR_NAME = 'todo-actions';\n process.env.GIT_AUTHOR_EMAIL = 'todo-actions[bot]@users.noreply.github.com';\n child_process_1.execFileSync('git', ['add', ...changedFiles.map(file => file.fileName)]);\n child_process_1.execFileSync('git', ['commit', '-m', commitMessage, '-m', commitBody], {\n stdio: 'inherit'\n });\n if (!process.env.GITHUB_TOKEN) {\n throw `Maybe you forgot to enable the GITHUB_TOKEN secret?`;\n }\n const ref = core_1.getInput('branch') || \"$GITHUB_REF\";\n child_process_1.execSync(`git push \"https://x-access-token:${process.env.GITHUB_TOKEN}@github.com/${github_1.context.repo.owner}/${github_1.context.repo.repo}.git\" HEAD:${ref}`, {\n stdio: 'inherit'\n });\n });\n },\n };\n });\n}\nexports.scanCodeRepository = scanCodeRepository;\n","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.findAllUncompletedTasks = exports.beginTaskResolution = void 0;\nconst tkt_1 = require(\"tkt\");\nconst mongodb_1 = require(\"mongodb\");\nconst MongoDB_1 = require(\"./MongoDB\");\nconst ProcessId_1 = require(\"./ProcessId\");\nconst log = tkt_1.logger('DataStore');\nfunction beginTaskResolution(todoUniqueKey, repositoryId, todo) {\n return __awaiter(this, void 0, void 0, function* () {\n const db = yield MongoDB_1.getMongoDb();\n const _id = mongodb_1.ObjectId.createFromHexString(todoUniqueKey);\n // Ensure a task exists in the database.\n const task = yield db.tasks.findOneAndUpdate({ _id: _id }, {\n $setOnInsert: {\n _id: _id,\n repositoryId: repositoryId,\n taskReference: null,\n createdAt: new Date(),\n ownerProcessId: null,\n ownerProcessTimestamp: null,\n },\n }, { upsert: true, returnOriginal: false });\n if (!task.value) {\n throw new Error('Failed to upsert a task.');\n }\n if (task.value.taskReference) {\n log.debug('Found already-existing identifier %s for TODO %s.', task.value.taskReference, todoUniqueKey);\n return { existingTaskReference: task.value.taskReference };\n }\n return {\n acquireTaskCreationLock() {\n return __awaiter(this, void 0, void 0, function* () {\n // Acquire a lock...\n log.debug('Acquiring lock for TODO %s (currentProcessId=%s).', todoUniqueKey, ProcessId_1.currentProcessId);\n const lockedTask = yield db.tasks.findOneAndUpdate({\n _id: _id,\n $or: [\n { ownerProcessTimestamp: null },\n { ownerProcessTimestamp: { $lt: new Date(Date.now() - 60e3) } },\n ],\n }, {\n $set: {\n ownerProcessId: ProcessId_1.currentProcessId,\n ownerProcessTimestamp: new Date(),\n },\n }, { returnOriginal: false });\n if (!lockedTask.value) {\n throw new Error('Failed to acquire a lock for this task.');\n }\n return {\n finish(taskReference, state) {\n return __awaiter(this, void 0, void 0, function* () {\n // Associate\n log.debug('Created task %s for TODO %s. Saving changes.', taskReference, todoUniqueKey);\n yield db.tasks.findOneAndUpdate({ _id: _id }, { $set: { taskReference: taskReference, hash: state.hash } });\n });\n },\n };\n });\n },\n };\n });\n}\nexports.beginTaskResolution = beginTaskResolution;\nfunction findAllUncompletedTasks(repositoryId) {\n return __awaiter(this, void 0, void 0, function* () {\n const db = yield MongoDB_1.getMongoDb();\n const result = yield db.tasks\n .find({\n repositoryId: repositoryId,\n completed: { $ne: true },\n taskReference: { $ne: null },\n })\n .toArray();\n return result.map(taskData => {\n return {\n taskReference: taskData.taskReference ||\n tkt_1.invariant(false, 'Unexpected unassociated task.'),\n state: {\n hash: taskData.hash || '',\n },\n markAsCompleted() {\n return __awaiter(this, void 0, void 0, function* () {\n yield db.tasks.findOneAndUpdate({ _id: taskData._id }, { $set: { completed: true } });\n });\n },\n updateState(newState) {\n return __awaiter(this, void 0, void 0, function* () {\n yield db.tasks.findOneAndUpdate({ _id: taskData._id }, { $set: { hash: newState.hash } });\n });\n },\n };\n });\n });\n}\nexports.findAllUncompletedTasks = findAllUncompletedTasks;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FileContents = exports.MockFile = exports.File = void 0;\nclass File {\n constructor(fileName) {\n this.fileName = fileName;\n this.contents = new FileContents(require('fs').readFileSync(fileName, 'utf8'));\n }\n save() {\n if (this.contents.changed) {\n require('fs').writeFileSync(this.fileName, this.contents.toString(), 'utf8');\n this.contents.changed = false;\n }\n }\n}\nexports.File = File;\n/**\n * A mock file.\n */\nclass MockFile {\n constructor(fileName, contents) {\n this.fileName = fileName;\n this.contents = new FileContents(contents);\n }\n save() {\n this.contents.changed = false;\n }\n}\nexports.MockFile = MockFile;\nclass FileContents {\n constructor(contents) {\n this.lines = contents.split('\\n');\n this.changed = false;\n }\n changeLine(lineIndex, newLineContents) {\n this.lines[lineIndex] = newLineContents;\n this.changed = true;\n }\n toString() {\n return this.lines.join('\\n');\n }\n}\nexports.FileContents = FileContents;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.close = exports.getMongoDb = void 0;\nconst tkt_1 = require(\"tkt\");\nlet mongoPromise;\nconst log = tkt_1.logger('mongo');\nfunction getMongoDb() {\n return __awaiter(this, void 0, void 0, function* () {\n if (mongoPromise)\n return mongoPromise;\n return (mongoPromise = (() => __awaiter(this, void 0, void 0, function* () {\n const { MongoClient } = yield Promise.resolve().then(() => __importStar(require('mongodb')));\n log.info('Connecting...');\n const client = new MongoClient(process.env.TODO_ACTIONS_MONGO_URL ||\n tkt_1.invariant(false, 'Missing environment variable: TODO_ACTIONS_MONGO_URL'));\n yield client.connect();\n log.info('Connected!');\n const db = client.db();\n const tasks = db.collection('tasks');\n tasks.createIndex({ repositoryId: 1 });\n return {\n client,\n tasks: tasks,\n };\n }))());\n });\n}\nexports.getMongoDb = getMongoDb;\nfunction close() {\n return __awaiter(this, void 0, void 0, function* () {\n if (!mongoPromise)\n return;\n const mongo = yield mongoPromise;\n mongo.client.close();\n });\n}\nexports.close = close;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.currentProcessId = void 0;\nconst bson_1 = require(\"bson\");\nexports.currentProcessId = new bson_1.ObjectId().toHexString();\n","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateTaskInformationFromTodo = void 0;\nconst core_1 = require(\"@actions/core\");\nconst crypto_1 = require(\"crypto\");\nconst CodeRepository_1 = require(\"./CodeRepository\");\nconst tkt_1 = require(\"tkt\");\nconst graphql_1 = require(\"@octokit/graphql\");\nconst owner = CodeRepository_1.repoContext.repositoryOwner;\nconst repo = CodeRepository_1.repoContext.repositoryName;\nconst branch = core_1.getInput('branch') || CodeRepository_1.repoContext.defaultBranch;\nconst log = tkt_1.logger('TaskInformationGenerator');\nlet cache = 'meh';\nfunction fetchCommit() {\n return __awaiter(this, void 0, void 0, function* () {\n if (cache !== 'meh') {\n return cache;\n }\n // Some random check to filter out tests\n if (!('GITHUB_TOKEN' in process.env)) {\n log.info(`Skipping local testing env`);\n return '';\n }\n cache = '';\n log.info('Fetching commit');\n try {\n const { repository: { ref: { target: { history: { nodes: [{ oid }] } } } } } = yield graphql_1.graphql(`{\n repository(name: \"${repo}\", owner: \"${owner}\") {\n ref(qualifiedName: \"${branch}\") {\n target {\n ... on Commit {\n history(first: 1) {\n nodes {\n oid\n }\n }\n }\n }\n }\n }\n }`, {\n headers: {\n authorization: `token ${process.env.GITHUB_TOKEN ||\n tkt_1.invariant(false, 'Required GITHUB_TOKEN variable.')}`,\n },\n });\n cache = oid;\n }\n catch (err) {\n console.error(err);\n }\n return cache;\n });\n}\nfunction generateTaskInformationFromTodo(todo) {\n return __awaiter(this, void 0, void 0, function* () {\n const title = todo.title;\n const file = todo.file.fileName;\n // TODO [#31]: Also link to end line in addition to just the starting line.\n // This requires changing `IFile` interface and `File` class to also keep track of where the TODO comment ends.\n const line = todo.startLine;\n const commit = yield fetchCommit();\n const url = `https://github.com/${owner}/${repo}/blob/${commit || branch}/${file}#L${line}`;\n const link = `[${file}:${line}](${url})`;\n const body = [\n todo.body,\n '',\n '---',\n `_` +\n `This issue has been automatically created by [todo-actions](https://github.com/apps/todo-actions) based on a TODO comment found in ${link}. ` +\n `It will automatically be closed when the TODO comment is removed from ${branch}.` +\n `_`,\n ].join('\\n');\n return {\n state: {\n hash: crypto_1.createHash('md5')\n .update(title)\n .update(body)\n .digest('hex'),\n },\n title,\n body,\n };\n });\n}\nexports.generateTaskInformationFromTodo = generateTaskInformationFromTodo;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.updateTask = exports.completeTask = exports.createTask = void 0;\nconst tkt_1 = require(\"tkt\");\nconst rest_1 = require(\"@octokit/rest\");\nconst graphql_1 = require(\"@octokit/graphql\");\nconst CodeRepository = __importStar(require(\"./CodeRepository\"));\nconst log = tkt_1.logger('TaskManagementSystem');\nfunction createTask(information) {\n return __awaiter(this, void 0, void 0, function* () {\n const { createIssue } = yield graphql_1.graphql(`\n mutation CreateIssue($input: CreateIssueInput!) {\n createIssue(input: $input) {\n issue {\n number\n }\n }\n }\n `, {\n input: {\n repositoryId: CodeRepository.repoContext.repositoryNodeId,\n title: information.title,\n body: information.body,\n },\n headers: {\n authorization: `token ${process.env.GITHUB_TOKEN || tkt_1.invariant(false, 'Required GITHUB_TOKEN variable.')}`,\n },\n });\n log.debug('Create issue result:', createIssue);\n return createIssue.issue.number\n ? `#${createIssue.issue.number}`\n : tkt_1.invariant(false, 'Failed to get issue number out of createIssue API call.');\n });\n}\nexports.createTask = createTask;\nfunction completeTask(taskReference) {\n return __awaiter(this, void 0, void 0, function* () {\n const octokit = new rest_1.Octokit({\n auth: `token ${process.env.GITHUB_TOKEN ||\n tkt_1.invariant(false, 'Required GITHUB_TOKEN variable.')}`,\n });\n const result = yield octokit.issues.update({\n owner: CodeRepository.repoContext.repositoryOwner,\n repo: CodeRepository.repoContext.repositoryName,\n issue_number: +taskReference.substr(1),\n state: 'closed',\n });\n log.debug('Issue close result:', result.data);\n });\n}\nexports.completeTask = completeTask;\nfunction updateTask(taskReference, information) {\n return __awaiter(this, void 0, void 0, function* () {\n const octokit = new rest_1.Octokit({\n auth: `token ${process.env.GITHUB_TOKEN ||\n tkt_1.invariant(false, 'Required GITHUB_TOKEN variable.')}`,\n });\n const result = yield octokit.issues.update({\n owner: CodeRepository.repoContext.repositoryOwner,\n repo: CodeRepository.repoContext.repositoryName,\n issue_number: +taskReference.substr(1),\n title: information.title,\n body: information.body,\n });\n log.debug('Issue update result:', result.data);\n });\n}\nexports.updateTask = updateTask;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.resolveTask = exports.reconcileTasks = exports.ensureAllTodosAreAssociated = void 0;\nconst tkt_1 = require(\"tkt\");\nconst CodeRepository = __importStar(require(\"./CodeRepository\"));\nconst TaskManagementSystem = __importStar(require(\"./TaskManagementSystem\"));\nconst DataStore = __importStar(require(\"./DataStore\"));\nconst TaskInformationGenerator = __importStar(require(\"./TaskInformationGenerator\"));\nconst log = tkt_1.logger('TaskUpdater');\nfunction ensureAllTodosAreAssociated(todos) {\n return __awaiter(this, void 0, void 0, function* () {\n const references = [];\n for (const todo of todos) {\n const reference = todo.reference || tkt_1.invariant(false, 'Unexpected unidentified TODO marker');\n const unassociated = reference.startsWith('$');\n if (unassociated) {\n // TODO [#37]: Isolate error when creating tasks\n // Failure to create a task should not prevent the action from progressing forward.\n // We can simply skip processing this comment for now.\n // Since this script is designed to be idempotent, it can be retried later.\n const todoUniqueKey = reference.substr(1);\n log.debug('Found unresolved TODO %s, resolving task...', todoUniqueKey);\n const taskReference = yield resolveTask(todoUniqueKey, todo);\n log.debug('Resolved TODO %s => task %s', todoUniqueKey, taskReference);\n todo.reference = taskReference;\n references.push(taskReference);\n }\n }\n return references;\n });\n}\nexports.ensureAllTodosAreAssociated = ensureAllTodosAreAssociated;\nfunction reconcileTasks(todos) {\n return __awaiter(this, void 0, void 0, function* () {\n const uncompletedTasks = yield DataStore.findAllUncompletedTasks(CodeRepository.repoContext.repositoryNodeId);\n log.info('Number of registered uncompleted tasks: %s', uncompletedTasks.length);\n for (const todo of todos) {\n const reference = todo.reference || tkt_1.invariant(false, 'Unexpected unidentified TODO marker');\n tkt_1.invariant(!reference.startsWith('$'), 'Expected all TODO comments to be associated by now.');\n const task = uncompletedTasks.find(t => t.taskReference === reference);\n if (!task) {\n log.warn('Cannot find a matching task for TODO comment with reference \"%s\"', reference);\n continue;\n }\n // TODO [#38]: Isolate error when updating tasks\n // Failure to update a task should not prevent the action from progressing forward.\n // We can simply skip processing this task for now.\n // Since this script is designed to be idempotent, it can be retried later.\n const { title, body, state, } = yield TaskInformationGenerator.generateTaskInformationFromTodo(todo);\n if (task.state.hash !== state.hash) {\n log.info('Hash for \"%s\" changed: \"%s\" => \"%s\" -- must update task.', reference, task.state.hash, state.hash);\n yield TaskManagementSystem.updateTask(reference, { title, body });\n yield task.updateState(state);\n }\n else {\n log.info('Hash for \"%s\" remains unchanged: \"%s\".', reference, task.state.hash);\n }\n }\n for (const task of uncompletedTasks) {\n if (todos.find(todo => todo.reference === task.taskReference))\n continue;\n log.info('TODO for task \"%s\" is gone -- completing task!', task.taskReference);\n // TODO [#39]: Isolate error when completing tasks\n // Failure to complete a task should not prevent the action from progressing forward.\n // We can simply skip processing this task for now.\n // Since this script is designed to be idempotent, it can be retried later.\n yield TaskManagementSystem.completeTask(task.taskReference);\n yield task.markAsCompleted();\n }\n });\n}\nexports.reconcileTasks = reconcileTasks;\nfunction resolveTask(todoUniqueKey, todo) {\n return __awaiter(this, void 0, void 0, function* () {\n const resolution = yield DataStore.beginTaskResolution(todoUniqueKey, CodeRepository.repoContext.repositoryNodeId, todo);\n if ('existingTaskReference' in resolution) {\n return resolution.existingTaskReference;\n }\n const taskCreationLock = yield resolution.acquireTaskCreationLock();\n log.debug('Lock acquired. Now creating task for TODO %s.', todoUniqueKey);\n const { title, body, state, } = yield TaskInformationGenerator.generateTaskInformationFromTodo(todo);\n const taskReference = yield TaskManagementSystem.createTask({ title, body });\n taskCreationLock.finish(taskReference, state);\n return taskReference;\n });\n}\nexports.resolveTask = resolveTask;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.runMain = void 0;\nconst core_1 = require(\"@actions/core\");\nconst tkt_1 = require(\"tkt\");\nconst tkt_2 = require(\"tkt\");\nconst bson_1 = require(\"bson\");\nconst TodoParser = __importStar(require(\"./TodoParser\"));\nconst TaskUpdater = __importStar(require(\"./TaskUpdater\"));\nconst CodeRepository = __importStar(require(\"./CodeRepository\"));\nconst log = tkt_2.logger('main');\nfunction runMain() {\n return __awaiter(this, void 0, void 0, function* () {\n log.info('Search for files with TODO tags...');\n const { files, saveChanges } = yield CodeRepository.scanCodeRepository();\n const todoComments = [];\n for (const file of files) {\n // TODO [#22]: Implement ignoring paths\n if (file.fileName === 'README.md')\n continue;\n const todos = TodoParser.parseTodos(file);\n log.info('%s: %s found', file.fileName, todos.length);\n todoComments.push(...todos);\n }\n log.info('Total TODOs found: %s', todoComments.length);\n const todosWithoutReference = todoComments.filter(todo => !todo.reference);\n log.info('TODOs without references: %s', todosWithoutReference.length);\n if (todosWithoutReference.length > 0) {\n for (const todo of todosWithoutReference) {\n todo.reference = `$${new bson_1.ObjectId().toHexString()}`;\n }\n yield saveChanges(core_1.getInput('collect_commit_msg'), core_1.getInput('collect_commit_body'));\n }\n // Every TODO must have a reference by now.\n for (const todo of todoComments) {\n tkt_1.invariant(todo.reference, 'TODO \"%s\" at %s must have a reference by now!', todo.title, todo.file.fileName);\n }\n // Update all the tasks according to the TODO state.\n const associated = yield TaskUpdater.ensureAllTodosAreAssociated(todoComments);\n yield saveChanges(core_1.getInput('reference_commit_msg').replace(/%s/, associated.join(', ')), core_1.getInput('reference_commit_body').replace(/%s/, associated.join(', ')));\n // Reconcile all tasks\n yield TaskUpdater.reconcileTasks(todoComments);\n });\n}\nexports.runMain = runMain;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.parseTodos = void 0;\nfunction parseTodos(file) {\n const out = [];\n let currentTodo;\n for (const [lineIndex, line] of file.contents.lines.entries()) {\n const match = line.match(/^(\\W+\\s)TODO(?: \\[([^\\]\\s]+)\\])?:(.*)/);\n if (match) {\n const todo = new Todo(file, lineIndex, match[1], match[2], match[3]);\n currentTodo = todo;\n out.push(todo);\n }\n else if (currentTodo) {\n const beforePrefix = line.substr(0, currentTodo.prefix.length);\n const afterPrefix = line.substr(currentTodo.prefix.length);\n if (beforePrefix.trimRight() === currentTodo.prefix.trimRight() &&\n (!afterPrefix || beforePrefix.match(/\\s$/))) {\n currentTodo.handleLine(afterPrefix);\n }\n else {\n currentTodo = undefined;\n }\n }\n }\n return out;\n}\nexports.parseTodos = parseTodos;\nclass Todo {\n constructor(file, line, prefix, reference, suffix) {\n this.file = file;\n this.line = line;\n this.prefix = prefix;\n this.currentReference = reference;\n this.suffix = suffix;\n this.title = suffix.trim();\n this.body = '';\n }\n get reference() {\n return this.currentReference;\n }\n set reference(newRef) {\n this.currentReference = newRef;\n this.file.contents.changeLine(this.line, `${this.prefix}TODO${newRef ? ` [${newRef}]` : ''}:${this.suffix}`);\n }\n get startLine() {\n return this.line + 1;\n }\n handleLine(line) {\n if (!this.title) {\n this.title = line;\n }\n else if (this.body || line) {\n this.body += (this.body ? '\\n' : '') + line;\n }\n }\n}\n","\"use strict\";\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os = __importStar(require(\"os\"));\n/**\n * Commands\n *\n * Command Format:\n * ::name key=value,key=value::message\n *\n * Examples:\n * ::warning::This is the message\n * ::set-env name=MY_VAR::some value\n */\nfunction issueCommand(command, properties, message) {\n const cmd = new Command(command, properties, message);\n process.stdout.write(cmd.toString() + os.EOL);\n}\nexports.issueCommand = issueCommand;\nfunction issue(name, message = '') {\n issueCommand(name, {}, message);\n}\nexports.issue = issue;\nconst CMD_STRING = '::';\nclass Command {\n constructor(command, properties, message) {\n if (!command) {\n command = 'missing.command';\n }\n this.command = command;\n this.properties = properties;\n this.message = message;\n }\n toString() {\n let cmdStr = CMD_STRING + this.command;\n if (this.properties && Object.keys(this.properties).length > 0) {\n cmdStr += ' ';\n let first = true;\n for (const key in this.properties) {\n if (this.properties.hasOwnProperty(key)) {\n const val = this.properties[key];\n if (val) {\n if (first) {\n first = false;\n }\n else {\n cmdStr += ',';\n }\n cmdStr += `${key}=${escapeProperty(val)}`;\n }\n }\n }\n }\n cmdStr += `${CMD_STRING}${escapeData(this.message)}`;\n return cmdStr;\n }\n}\n/**\n * Sanitizes an input into a string so it can be passed into issueCommand safely\n * @param input input to sanitize into a string\n */\nfunction toCommandValue(input) {\n if (input === null || input === undefined) {\n return '';\n }\n else if (typeof input === 'string' || input instanceof String) {\n return input;\n }\n return JSON.stringify(input);\n}\nexports.toCommandValue = toCommandValue;\nfunction escapeData(s) {\n return toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A');\n}\nfunction escapeProperty(s) {\n return toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C');\n}\n//# sourceMappingURL=command.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst command_1 = require(\"./command\");\nconst os = __importStar(require(\"os\"));\nconst path = __importStar(require(\"path\"));\n/**\n * The code to exit an action\n */\nvar ExitCode;\n(function (ExitCode) {\n /**\n * A code indicating that the action was successful\n */\n ExitCode[ExitCode[\"Success\"] = 0] = \"Success\";\n /**\n * A code indicating that the action was a failure\n */\n ExitCode[ExitCode[\"Failure\"] = 1] = \"Failure\";\n})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));\n//-----------------------------------------------------------------------\n// Variables\n//-----------------------------------------------------------------------\n/**\n * Sets env variable for this action and future actions in the job\n * @param name the name of the variable to set\n * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction exportVariable(name, val) {\n const convertedVal = command_1.toCommandValue(val);\n process.env[name] = convertedVal;\n command_1.issueCommand('set-env', { name }, convertedVal);\n}\nexports.exportVariable = exportVariable;\n/**\n * Registers a secret which will get masked from logs\n * @param secret value of the secret\n */\nfunction setSecret(secret) {\n command_1.issueCommand('add-mask', {}, secret);\n}\nexports.setSecret = setSecret;\n/**\n * Prepends inputPath to the PATH (for this action and future actions)\n * @param inputPath\n */\nfunction addPath(inputPath) {\n command_1.issueCommand('add-path', {}, inputPath);\n process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;\n}\nexports.addPath = addPath;\n/**\n * Gets the value of an input. The value is also trimmed.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string\n */\nfunction getInput(name, options) {\n const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';\n if (options && options.required && !val) {\n throw new Error(`Input required and not supplied: ${name}`);\n }\n return val.trim();\n}\nexports.getInput = getInput;\n/**\n * Sets the value of an output.\n *\n * @param name name of the output to set\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setOutput(name, value) {\n command_1.issueCommand('set-output', { name }, value);\n}\nexports.setOutput = setOutput;\n/**\n * Enables or disables the echoing of commands into stdout for the rest of the step.\n * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.\n *\n */\nfunction setCommandEcho(enabled) {\n command_1.issue('echo', enabled ? 'on' : 'off');\n}\nexports.setCommandEcho = setCommandEcho;\n//-----------------------------------------------------------------------\n// Results\n//-----------------------------------------------------------------------\n/**\n * Sets the action status to failed.\n * When the action exits it will be with an exit code of 1\n * @param message add error issue message\n */\nfunction setFailed(message) {\n process.exitCode = ExitCode.Failure;\n error(message);\n}\nexports.setFailed = setFailed;\n//-----------------------------------------------------------------------\n// Logging Commands\n//-----------------------------------------------------------------------\n/**\n * Gets whether Actions Step Debug is on or not\n */\nfunction isDebug() {\n return process.env['RUNNER_DEBUG'] === '1';\n}\nexports.isDebug = isDebug;\n/**\n * Writes debug message to user log\n * @param message debug message\n */\nfunction debug(message) {\n command_1.issueCommand('debug', {}, message);\n}\nexports.debug = debug;\n/**\n * Adds an error issue\n * @param message error issue message. Errors will be converted to string via toString()\n */\nfunction error(message) {\n command_1.issue('error', message instanceof Error ? message.toString() : message);\n}\nexports.error = error;\n/**\n * Adds an warning issue\n * @param message warning issue message. Errors will be converted to string via toString()\n */\nfunction warning(message) {\n command_1.issue('warning', message instanceof Error ? message.toString() : message);\n}\nexports.warning = warning;\n/**\n * Writes info to log with console.log.\n * @param message info message\n */\nfunction info(message) {\n process.stdout.write(message + os.EOL);\n}\nexports.info = info;\n/**\n * Begin an output group.\n *\n * Output until the next `groupEnd` will be foldable in this group\n *\n * @param name The name of the output group\n */\nfunction startGroup(name) {\n command_1.issue('group', name);\n}\nexports.startGroup = startGroup;\n/**\n * End an output group.\n */\nfunction endGroup() {\n command_1.issue('endgroup');\n}\nexports.endGroup = endGroup;\n/**\n * Wrap an asynchronous function call in a group.\n *\n * Returns the same type as the function itself.\n *\n * @param name The name of the group\n * @param fn The function to wrap in the group\n */\nfunction group(name, fn) {\n return __awaiter(this, void 0, void 0, function* () {\n startGroup(name);\n let result;\n try {\n result = yield fn();\n }\n finally {\n endGroup();\n }\n return result;\n });\n}\nexports.group = group;\n//-----------------------------------------------------------------------\n// Wrapper action state\n//-----------------------------------------------------------------------\n/**\n * Saves state for current action, the state can only be retrieved by this action's post job execution.\n *\n * @param name name of the state to store\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction saveState(name, value) {\n command_1.issueCommand('save-state', { name }, value);\n}\nexports.saveState = saveState;\n/**\n * Gets the value of an state set by this action's main execution.\n *\n * @param name name of the state to get\n * @returns string\n */\nfunction getState(name) {\n return process.env[`STATE_${name}`] || '';\n}\nexports.getState = getState;\n//# sourceMappingURL=core.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Context = void 0;\nconst fs_1 = require(\"fs\");\nconst os_1 = require(\"os\");\nclass Context {\n /**\n * Hydrate the context from the environment\n */\n constructor() {\n this.payload = {};\n if (process.env.GITHUB_EVENT_PATH) {\n if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) {\n this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' }));\n }\n else {\n const path = process.env.GITHUB_EVENT_PATH;\n process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`);\n }\n }\n this.eventName = process.env.GITHUB_EVENT_NAME;\n this.sha = process.env.GITHUB_SHA;\n this.ref = process.env.GITHUB_REF;\n this.workflow = process.env.GITHUB_WORKFLOW;\n this.action = process.env.GITHUB_ACTION;\n this.actor = process.env.GITHUB_ACTOR;\n this.job = process.env.GITHUB_JOB;\n this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10);\n this.runId = parseInt(process.env.GITHUB_RUN_ID, 10);\n }\n get issue() {\n const payload = this.payload;\n return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number });\n }\n get repo() {\n if (process.env.GITHUB_REPOSITORY) {\n const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/');\n return { owner, repo };\n }\n if (this.payload.repository) {\n return {\n owner: this.payload.repository.owner.login,\n repo: this.payload.repository.name\n };\n }\n throw new Error(\"context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'\");\n }\n}\nexports.Context = Context;\n//# sourceMappingURL=context.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getOctokit = exports.context = void 0;\nconst Context = __importStar(require(\"./context\"));\nconst utils_1 = require(\"./utils\");\nexports.context = new Context.Context();\n/**\n * Returns a hydrated octokit ready to use for GitHub Actions\n *\n * @param token the repo PAT or GITHUB_TOKEN\n * @param options other options to set\n */\nfunction getOctokit(token, options) {\n return new utils_1.GitHub(utils_1.getOctokitOptions(token, options));\n}\nexports.getOctokit = getOctokit;\n//# sourceMappingURL=github.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0;\nconst httpClient = __importStar(require(\"@actions/http-client\"));\nfunction getAuthString(token, options) {\n if (!token && !options.auth) {\n throw new Error('Parameter token or opts.auth is required');\n }\n else if (token && options.auth) {\n throw new Error('Parameters token and opts.auth may not both be specified');\n }\n return typeof options.auth === 'string' ? options.auth : `token ${token}`;\n}\nexports.getAuthString = getAuthString;\nfunction getProxyAgent(destinationUrl) {\n const hc = new httpClient.HttpClient();\n return hc.getAgent(destinationUrl);\n}\nexports.getProxyAgent = getProxyAgent;\nfunction getApiBaseUrl() {\n return process.env['GITHUB_API_URL'] || 'https://api.github.com';\n}\nexports.getApiBaseUrl = getApiBaseUrl;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getOctokitOptions = exports.GitHub = exports.context = void 0;\nconst Context = __importStar(require(\"./context\"));\nconst Utils = __importStar(require(\"./internal/utils\"));\n// octokit + plugins\nconst core_1 = require(\"@octokit/core\");\nconst plugin_rest_endpoint_methods_1 = require(\"@octokit/plugin-rest-endpoint-methods\");\nconst plugin_paginate_rest_1 = require(\"@octokit/plugin-paginate-rest\");\nexports.context = new Context.Context();\nconst baseUrl = Utils.getApiBaseUrl();\nconst defaults = {\n baseUrl,\n request: {\n agent: Utils.getProxyAgent(baseUrl)\n }\n};\nexports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(defaults);\n/**\n * Convience function to correctly format Octokit Options to pass into the constructor.\n *\n * @param token the repo PAT or GITHUB_TOKEN\n * @param options other options to set\n */\nfunction getOctokitOptions(token, options) {\n const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller\n // Auth\n const auth = Utils.getAuthString(token, opts);\n if (auth) {\n opts.auth = auth;\n }\n return opts;\n}\nexports.getOctokitOptions = getOctokitOptions;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst url = require(\"url\");\nconst http = require(\"http\");\nconst https = require(\"https\");\nconst pm = require(\"./proxy\");\nlet tunnel;\nvar HttpCodes;\n(function (HttpCodes) {\n HttpCodes[HttpCodes[\"OK\"] = 200] = \"OK\";\n HttpCodes[HttpCodes[\"MultipleChoices\"] = 300] = \"MultipleChoices\";\n HttpCodes[HttpCodes[\"MovedPermanently\"] = 301] = \"MovedPermanently\";\n HttpCodes[HttpCodes[\"ResourceMoved\"] = 302] = \"ResourceMoved\";\n HttpCodes[HttpCodes[\"SeeOther\"] = 303] = \"SeeOther\";\n HttpCodes[HttpCodes[\"NotModified\"] = 304] = \"NotModified\";\n HttpCodes[HttpCodes[\"UseProxy\"] = 305] = \"UseProxy\";\n HttpCodes[HttpCodes[\"SwitchProxy\"] = 306] = \"SwitchProxy\";\n HttpCodes[HttpCodes[\"TemporaryRedirect\"] = 307] = \"TemporaryRedirect\";\n HttpCodes[HttpCodes[\"PermanentRedirect\"] = 308] = \"PermanentRedirect\";\n HttpCodes[HttpCodes[\"BadRequest\"] = 400] = \"BadRequest\";\n HttpCodes[HttpCodes[\"Unauthorized\"] = 401] = \"Unauthorized\";\n HttpCodes[HttpCodes[\"PaymentRequired\"] = 402] = \"PaymentRequired\";\n HttpCodes[HttpCodes[\"Forbidden\"] = 403] = \"Forbidden\";\n HttpCodes[HttpCodes[\"NotFound\"] = 404] = \"NotFound\";\n HttpCodes[HttpCodes[\"MethodNotAllowed\"] = 405] = \"MethodNotAllowed\";\n HttpCodes[HttpCodes[\"NotAcceptable\"] = 406] = \"NotAcceptable\";\n HttpCodes[HttpCodes[\"ProxyAuthenticationRequired\"] = 407] = \"ProxyAuthenticationRequired\";\n HttpCodes[HttpCodes[\"RequestTimeout\"] = 408] = \"RequestTimeout\";\n HttpCodes[HttpCodes[\"Conflict\"] = 409] = \"Conflict\";\n HttpCodes[HttpCodes[\"Gone\"] = 410] = \"Gone\";\n HttpCodes[HttpCodes[\"TooManyRequests\"] = 429] = \"TooManyRequests\";\n HttpCodes[HttpCodes[\"InternalServerError\"] = 500] = \"InternalServerError\";\n HttpCodes[HttpCodes[\"NotImplemented\"] = 501] = \"NotImplemented\";\n HttpCodes[HttpCodes[\"BadGateway\"] = 502] = \"BadGateway\";\n HttpCodes[HttpCodes[\"ServiceUnavailable\"] = 503] = \"ServiceUnavailable\";\n HttpCodes[HttpCodes[\"GatewayTimeout\"] = 504] = \"GatewayTimeout\";\n})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));\nvar Headers;\n(function (Headers) {\n Headers[\"Accept\"] = \"accept\";\n Headers[\"ContentType\"] = \"content-type\";\n})(Headers = exports.Headers || (exports.Headers = {}));\nvar MediaTypes;\n(function (MediaTypes) {\n MediaTypes[\"ApplicationJson\"] = \"application/json\";\n})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));\n/**\n * Returns the proxy URL, depending upon the supplied url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\nfunction getProxyUrl(serverUrl) {\n let proxyUrl = pm.getProxyUrl(url.parse(serverUrl));\n return proxyUrl ? proxyUrl.href : '';\n}\nexports.getProxyUrl = getProxyUrl;\nconst HttpRedirectCodes = [\n HttpCodes.MovedPermanently,\n HttpCodes.ResourceMoved,\n HttpCodes.SeeOther,\n HttpCodes.TemporaryRedirect,\n HttpCodes.PermanentRedirect\n];\nconst HttpResponseRetryCodes = [\n HttpCodes.BadGateway,\n HttpCodes.ServiceUnavailable,\n HttpCodes.GatewayTimeout\n];\nconst RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];\nconst ExponentialBackoffCeiling = 10;\nconst ExponentialBackoffTimeSlice = 5;\nclass HttpClientResponse {\n constructor(message) {\n this.message = message;\n }\n readBody() {\n return new Promise(async (resolve, reject) => {\n let output = Buffer.alloc(0);\n this.message.on('data', (chunk) => {\n output = Buffer.concat([output, chunk]);\n });\n this.message.on('end', () => {\n resolve(output.toString());\n });\n });\n }\n}\nexports.HttpClientResponse = HttpClientResponse;\nfunction isHttps(requestUrl) {\n let parsedUrl = url.parse(requestUrl);\n return parsedUrl.protocol === 'https:';\n}\nexports.isHttps = isHttps;\nclass HttpClient {\n constructor(userAgent, handlers, requestOptions) {\n this._ignoreSslError = false;\n this._allowRedirects = true;\n this._allowRedirectDowngrade = false;\n this._maxRedirects = 50;\n this._allowRetries = false;\n this._maxRetries = 1;\n this._keepAlive = false;\n this._disposed = false;\n this.userAgent = userAgent;\n this.handlers = handlers || [];\n this.requestOptions = requestOptions;\n if (requestOptions) {\n if (requestOptions.ignoreSslError != null) {\n this._ignoreSslError = requestOptions.ignoreSslError;\n }\n this._socketTimeout = requestOptions.socketTimeout;\n if (requestOptions.allowRedirects != null) {\n this._allowRedirects = requestOptions.allowRedirects;\n }\n if (requestOptions.allowRedirectDowngrade != null) {\n this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;\n }\n if (requestOptions.maxRedirects != null) {\n this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);\n }\n if (requestOptions.keepAlive != null) {\n this._keepAlive = requestOptions.keepAlive;\n }\n if (requestOptions.allowRetries != null) {\n this._allowRetries = requestOptions.allowRetries;\n }\n if (requestOptions.maxRetries != null) {\n this._maxRetries = requestOptions.maxRetries;\n }\n }\n }\n options(requestUrl, additionalHeaders) {\n return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});\n }\n get(requestUrl, additionalHeaders) {\n return this.request('GET', requestUrl, null, additionalHeaders || {});\n }\n del(requestUrl, additionalHeaders) {\n return this.request('DELETE', requestUrl, null, additionalHeaders || {});\n }\n post(requestUrl, data, additionalHeaders) {\n return this.request('POST', requestUrl, data, additionalHeaders || {});\n }\n patch(requestUrl, data, additionalHeaders) {\n return this.request('PATCH', requestUrl, data, additionalHeaders || {});\n }\n put(requestUrl, data, additionalHeaders) {\n return this.request('PUT', requestUrl, data, additionalHeaders || {});\n }\n head(requestUrl, additionalHeaders) {\n return this.request('HEAD', requestUrl, null, additionalHeaders || {});\n }\n sendStream(verb, requestUrl, stream, additionalHeaders) {\n return this.request(verb, requestUrl, stream, additionalHeaders);\n }\n /**\n * Gets a typed object from an endpoint\n * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise\n */\n async getJson(requestUrl, additionalHeaders = {}) {\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n let res = await this.get(requestUrl, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n }\n async postJson(requestUrl, obj, additionalHeaders = {}) {\n let data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n let res = await this.post(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n }\n async putJson(requestUrl, obj, additionalHeaders = {}) {\n let data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n let res = await this.put(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n }\n async patchJson(requestUrl, obj, additionalHeaders = {}) {\n let data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n let res = await this.patch(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n }\n /**\n * Makes a raw http request.\n * All other methods such as get, post, patch, and request ultimately call this.\n * Prefer get, del, post and patch\n */\n async request(verb, requestUrl, data, headers) {\n if (this._disposed) {\n throw new Error('Client has already been disposed.');\n }\n let parsedUrl = url.parse(requestUrl);\n let info = this._prepareRequest(verb, parsedUrl, headers);\n // Only perform retries on reads since writes may not be idempotent.\n let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1\n ? this._maxRetries + 1\n : 1;\n let numTries = 0;\n let response;\n while (numTries < maxTries) {\n response = await this.requestRaw(info, data);\n // Check if it's an authentication challenge\n if (response &&\n response.message &&\n response.message.statusCode === HttpCodes.Unauthorized) {\n let authenticationHandler;\n for (let i = 0; i < this.handlers.length; i++) {\n if (this.handlers[i].canHandleAuthentication(response)) {\n authenticationHandler = this.handlers[i];\n break;\n }\n }\n if (authenticationHandler) {\n return authenticationHandler.handleAuthentication(this, info, data);\n }\n else {\n // We have received an unauthorized response but have no handlers to handle it.\n // Let the response return to the caller.\n return response;\n }\n }\n let redirectsRemaining = this._maxRedirects;\n while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 &&\n this._allowRedirects &&\n redirectsRemaining > 0) {\n const redirectUrl = response.message.headers['location'];\n if (!redirectUrl) {\n // if there's no location to redirect to, we won't\n break;\n }\n let parsedRedirectUrl = url.parse(redirectUrl);\n if (parsedUrl.protocol == 'https:' &&\n parsedUrl.protocol != parsedRedirectUrl.protocol &&\n !this._allowRedirectDowngrade) {\n throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');\n }\n // we need to finish reading the response before reassigning response\n // which will leak the open socket.\n await response.readBody();\n // strip authorization header if redirected to a different hostname\n if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {\n for (let header in headers) {\n // header names are case insensitive\n if (header.toLowerCase() === 'authorization') {\n delete headers[header];\n }\n }\n }\n // let's make the request with the new redirectUrl\n info = this._prepareRequest(verb, parsedRedirectUrl, headers);\n response = await this.requestRaw(info, data);\n redirectsRemaining--;\n }\n if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) {\n // If not a retry code, return immediately instead of retrying\n return response;\n }\n numTries += 1;\n if (numTries < maxTries) {\n await response.readBody();\n await this._performExponentialBackoff(numTries);\n }\n }\n return response;\n }\n /**\n * Needs to be called if keepAlive is set to true in request options.\n */\n dispose() {\n if (this._agent) {\n this._agent.destroy();\n }\n this._disposed = true;\n }\n /**\n * Raw request.\n * @param info\n * @param data\n */\n requestRaw(info, data) {\n return new Promise((resolve, reject) => {\n let callbackForResult = function (err, res) {\n if (err) {\n reject(err);\n }\n resolve(res);\n };\n this.requestRawWithCallback(info, data, callbackForResult);\n });\n }\n /**\n * Raw request with callback.\n * @param info\n * @param data\n * @param onResult\n */\n requestRawWithCallback(info, data, onResult) {\n let socket;\n if (typeof data === 'string') {\n info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');\n }\n let callbackCalled = false;\n let handleResult = (err, res) => {\n if (!callbackCalled) {\n callbackCalled = true;\n onResult(err, res);\n }\n };\n let req = info.httpModule.request(info.options, (msg) => {\n let res = new HttpClientResponse(msg);\n handleResult(null, res);\n });\n req.on('socket', sock => {\n socket = sock;\n });\n // If we ever get disconnected, we want the socket to timeout eventually\n req.setTimeout(this._socketTimeout || 3 * 60000, () => {\n if (socket) {\n socket.end();\n }\n handleResult(new Error('Request timeout: ' + info.options.path), null);\n });\n req.on('error', function (err) {\n // err has statusCode property\n // res should have headers\n handleResult(err, null);\n });\n if (data && typeof data === 'string') {\n req.write(data, 'utf8');\n }\n if (data && typeof data !== 'string') {\n data.on('close', function () {\n req.end();\n });\n data.pipe(req);\n }\n else {\n req.end();\n }\n }\n /**\n * Gets an http agent. This function is useful when you need an http agent that handles\n * routing through a proxy server - depending upon the url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\n getAgent(serverUrl) {\n let parsedUrl = url.parse(serverUrl);\n return this._getAgent(parsedUrl);\n }\n _prepareRequest(method, requestUrl, headers) {\n const info = {};\n info.parsedUrl = requestUrl;\n const usingSsl = info.parsedUrl.protocol === 'https:';\n info.httpModule = usingSsl ? https : http;\n const defaultPort = usingSsl ? 443 : 80;\n info.options = {};\n info.options.host = info.parsedUrl.hostname;\n info.options.port = info.parsedUrl.port\n ? parseInt(info.parsedUrl.port)\n : defaultPort;\n info.options.path =\n (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');\n info.options.method = method;\n info.options.headers = this._mergeHeaders(headers);\n if (this.userAgent != null) {\n info.options.headers['user-agent'] = this.userAgent;\n }\n info.options.agent = this._getAgent(info.parsedUrl);\n // gives handlers an opportunity to participate\n if (this.handlers) {\n this.handlers.forEach(handler => {\n handler.prepareRequest(info.options);\n });\n }\n return info;\n }\n _mergeHeaders(headers) {\n const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});\n if (this.requestOptions && this.requestOptions.headers) {\n return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers));\n }\n return lowercaseKeys(headers || {});\n }\n _getExistingOrDefaultHeader(additionalHeaders, header, _default) {\n const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});\n let clientHeader;\n if (this.requestOptions && this.requestOptions.headers) {\n clientHeader = lowercaseKeys(this.requestOptions.headers)[header];\n }\n return additionalHeaders[header] || clientHeader || _default;\n }\n _getAgent(parsedUrl) {\n let agent;\n let proxyUrl = pm.getProxyUrl(parsedUrl);\n let useProxy = proxyUrl && proxyUrl.hostname;\n if (this._keepAlive && useProxy) {\n agent = this._proxyAgent;\n }\n if (this._keepAlive && !useProxy) {\n agent = this._agent;\n }\n // if agent is already assigned use that agent.\n if (!!agent) {\n return agent;\n }\n const usingSsl = parsedUrl.protocol === 'https:';\n let maxSockets = 100;\n if (!!this.requestOptions) {\n maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;\n }\n if (useProxy) {\n // If using proxy, need tunnel\n if (!tunnel) {\n tunnel = require('tunnel');\n }\n const agentOptions = {\n maxSockets: maxSockets,\n keepAlive: this._keepAlive,\n proxy: {\n proxyAuth: proxyUrl.auth,\n host: proxyUrl.hostname,\n port: proxyUrl.port\n }\n };\n let tunnelAgent;\n const overHttps = proxyUrl.protocol === 'https:';\n if (usingSsl) {\n tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;\n }\n else {\n tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;\n }\n agent = tunnelAgent(agentOptions);\n this._proxyAgent = agent;\n }\n // if reusing agent across request and tunneling agent isn't assigned create a new agent\n if (this._keepAlive && !agent) {\n const options = { keepAlive: this._keepAlive, maxSockets: maxSockets };\n agent = usingSsl ? new https.Agent(options) : new http.Agent(options);\n this._agent = agent;\n }\n // if not using private agent and tunnel agent isn't setup then use global agent\n if (!agent) {\n agent = usingSsl ? https.globalAgent : http.globalAgent;\n }\n if (usingSsl && this._ignoreSslError) {\n // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process\n // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options\n // we have to cast it to any and change it directly\n agent.options = Object.assign(agent.options || {}, {\n rejectUnauthorized: false\n });\n }\n return agent;\n }\n _performExponentialBackoff(retryNumber) {\n retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);\n const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);\n return new Promise(resolve => setTimeout(() => resolve(), ms));\n }\n static dateTimeDeserializer(key, value) {\n if (typeof value === 'string') {\n let a = new Date(value);\n if (!isNaN(a.valueOf())) {\n return a;\n }\n }\n return value;\n }\n async _processResponse(res, options) {\n return new Promise(async (resolve, reject) => {\n const statusCode = res.message.statusCode;\n const response = {\n statusCode: statusCode,\n result: null,\n headers: {}\n };\n // not found leads to null obj returned\n if (statusCode == HttpCodes.NotFound) {\n resolve(response);\n }\n let obj;\n let contents;\n // get the result from the body\n try {\n contents = await res.readBody();\n if (contents && contents.length > 0) {\n if (options && options.deserializeDates) {\n obj = JSON.parse(contents, HttpClient.dateTimeDeserializer);\n }\n else {\n obj = JSON.parse(contents);\n }\n response.result = obj;\n }\n response.headers = res.message.headers;\n }\n catch (err) {\n // Invalid resource (contents not json); leaving result obj null\n }\n // note that 3xx redirects are handled by the http layer.\n if (statusCode > 299) {\n let msg;\n // if exception/error in body, attempt to get better error\n if (obj && obj.message) {\n msg = obj.message;\n }\n else if (contents && contents.length > 0) {\n // it may be the case that the exception is in the body message as string\n msg = contents;\n }\n else {\n msg = 'Failed request: (' + statusCode + ')';\n }\n let err = new Error(msg);\n // attach statusCode and body obj (if available) to the error object\n err['statusCode'] = statusCode;\n if (response.result) {\n err['result'] = response.result;\n }\n reject(err);\n }\n else {\n resolve(response);\n }\n });\n }\n}\nexports.HttpClient = HttpClient;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst url = require(\"url\");\nfunction getProxyUrl(reqUrl) {\n let usingSsl = reqUrl.protocol === 'https:';\n let proxyUrl;\n if (checkBypass(reqUrl)) {\n return proxyUrl;\n }\n let proxyVar;\n if (usingSsl) {\n proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY'];\n }\n else {\n proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY'];\n }\n if (proxyVar) {\n proxyUrl = url.parse(proxyVar);\n }\n return proxyUrl;\n}\nexports.getProxyUrl = getProxyUrl;\nfunction checkBypass(reqUrl) {\n if (!reqUrl.hostname) {\n return false;\n }\n let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';\n if (!noProxy) {\n return false;\n }\n // Determine the request port\n let reqPort;\n if (reqUrl.port) {\n reqPort = Number(reqUrl.port);\n }\n else if (reqUrl.protocol === 'http:') {\n reqPort = 80;\n }\n else if (reqUrl.protocol === 'https:') {\n reqPort = 443;\n }\n // Format the request hostname and hostname with port\n let upperReqHosts = [reqUrl.hostname.toUpperCase()];\n if (typeof reqPort === 'number') {\n upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);\n }\n // Compare request host against noproxy\n for (let upperNoProxyItem of noProxy\n .split(',')\n .map(x => x.trim().toUpperCase())\n .filter(x => x)) {\n if (upperReqHosts.some(x => x === upperNoProxyItem)) {\n return true;\n }\n }\n return false;\n}\nexports.checkBypass = checkBypass;\n","'use strict';\r\n\r\n\r\nconst internals = {\r\n suspectRx: /\"(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])\"\\s*\\:/\r\n};\r\n\r\n\r\nexports.parse = function (text, reviver, options) {\r\n\r\n // Normalize arguments\r\n\r\n if (!options) {\r\n if (reviver &&\r\n typeof reviver === 'object') {\r\n\r\n options = reviver;\r\n reviver = undefined;\r\n }\r\n else {\r\n options = {};\r\n }\r\n }\r\n\r\n // Parse normally, allowing exceptions\r\n\r\n const obj = JSON.parse(text, reviver);\r\n\r\n // options.protoAction: 'error' (default) / 'remove' / 'ignore'\r\n\r\n if (options.protoAction === 'ignore') {\r\n return obj;\r\n }\r\n\r\n // Ignore null and non-objects\r\n\r\n if (!obj ||\r\n typeof obj !== 'object') {\r\n\r\n return obj;\r\n }\r\n\r\n // Check original string for potential exploit\r\n\r\n if (!text.match(internals.suspectRx)) {\r\n return obj;\r\n }\r\n\r\n // Scan result for proto keys\r\n\r\n exports.scan(obj, options);\r\n\r\n return obj;\r\n};\r\n\r\n\r\nexports.scan = function (obj, options) {\r\n\r\n options = options || {};\r\n\r\n let next = [obj];\r\n\r\n while (next.length) {\r\n const nodes = next;\r\n next = [];\r\n\r\n for (const node of nodes) {\r\n if (Object.prototype.hasOwnProperty.call(node, '__proto__')) { // Avoid calling node.hasOwnProperty directly\r\n if (options.protoAction !== 'remove') {\r\n throw new SyntaxError('Object contains forbidden prototype property');\r\n }\r\n\r\n delete node.__proto__;\r\n }\r\n\r\n for (const key in node) {\r\n const value = node[key];\r\n if (value &&\r\n typeof value === 'object') {\r\n\r\n next.push(node[key]);\r\n }\r\n }\r\n }\r\n }\r\n};\r\n\r\n\r\nexports.safeParse = function (text, reviver) {\r\n\r\n try {\r\n return exports.parse(text, reviver);\r\n }\r\n catch (ignoreError) {\r\n return null;\r\n }\r\n};\r\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nasync function auth(token) {\n const tokenType = token.split(/\\./).length === 3 ? \"app\" : /^v\\d+\\./.test(token) ? \"installation\" : \"oauth\";\n return {\n type: \"token\",\n token: token,\n tokenType\n };\n}\n\n/**\n * Prefix token for usage in the Authorization header\n *\n * @param token OAuth token or JSON Web Token\n */\nfunction withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n\n return `token ${token}`;\n}\n\nasync function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(route, parameters);\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n\nconst createTokenAuth = function createTokenAuth(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n\n if (typeof token !== \"string\") {\n throw new Error(\"[@octokit/auth-token] Token passed to createTokenAuth is not a string\");\n }\n\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token)\n });\n};\n\nexports.createTokenAuth = createTokenAuth;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar universalUserAgent = require('universal-user-agent');\nvar beforeAfterHook = require('before-after-hook');\nvar request = require('@octokit/request');\nvar graphql = require('@octokit/graphql');\nvar authToken = require('@octokit/auth-token');\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly) symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n}\n\nfunction _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n }\n\n return target;\n}\n\nconst VERSION = \"3.1.2\";\n\nclass Octokit {\n constructor(options = {}) {\n const hook = new beforeAfterHook.Collection();\n const requestDefaults = {\n baseUrl: request.request.endpoint.DEFAULTS.baseUrl,\n headers: {},\n request: Object.assign({}, options.request, {\n hook: hook.bind(null, \"request\")\n }),\n mediaType: {\n previews: [],\n format: \"\"\n }\n }; // prepend default user agent with `options.userAgent` if set\n\n requestDefaults.headers[\"user-agent\"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(\" \");\n\n if (options.baseUrl) {\n requestDefaults.baseUrl = options.baseUrl;\n }\n\n if (options.previews) {\n requestDefaults.mediaType.previews = options.previews;\n }\n\n if (options.timeZone) {\n requestDefaults.headers[\"time-zone\"] = options.timeZone;\n }\n\n this.request = request.request.defaults(requestDefaults);\n this.graphql = graphql.withCustomRequest(this.request).defaults(_objectSpread2(_objectSpread2({}, requestDefaults), {}, {\n baseUrl: requestDefaults.baseUrl.replace(/\\/api\\/v3$/, \"/api\")\n }));\n this.log = Object.assign({\n debug: () => {},\n info: () => {},\n warn: console.warn.bind(console),\n error: console.error.bind(console)\n }, options.log);\n this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance\n // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registred.\n // (2) If only `options.auth` is set, use the default token authentication strategy.\n // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance.\n // TODO: type `options.auth` based on `options.authStrategy`.\n\n if (!options.authStrategy) {\n if (!options.auth) {\n // (1)\n this.auth = async () => ({\n type: \"unauthenticated\"\n });\n } else {\n // (2)\n const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\\_(ツ)_/¯\n\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n } else {\n const auth = options.authStrategy(Object.assign({\n request: this.request\n }, options.auth)); // @ts-ignore ¯\\_(ツ)_/¯\n\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n } // apply plugins\n // https://stackoverflow.com/a/16345172\n\n\n const classConstructor = this.constructor;\n classConstructor.plugins.forEach(plugin => {\n Object.assign(this, plugin(this, options));\n });\n }\n\n static defaults(defaults) {\n const OctokitWithDefaults = class extends this {\n constructor(...args) {\n const options = args[0] || {};\n\n if (typeof defaults === \"function\") {\n super(defaults(options));\n return;\n }\n\n super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? {\n userAgent: `${options.userAgent} ${defaults.userAgent}`\n } : null));\n }\n\n };\n return OctokitWithDefaults;\n }\n /**\n * Attach a plugin (or many) to your Octokit instance.\n *\n * @example\n * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)\n */\n\n\n static plugin(...newPlugins) {\n var _a;\n\n const currentPlugins = this.plugins;\n const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a);\n return NewOctokit;\n }\n\n}\nOctokit.VERSION = VERSION;\nOctokit.plugins = [];\n\nexports.Octokit = Octokit;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar isPlainObject = require('is-plain-object');\nvar universalUserAgent = require('universal-user-agent');\n\nfunction lowercaseKeys(object) {\n if (!object) {\n return {};\n }\n\n return Object.keys(object).reduce((newObj, key) => {\n newObj[key.toLowerCase()] = object[key];\n return newObj;\n }, {});\n}\n\nfunction mergeDeep(defaults, options) {\n const result = Object.assign({}, defaults);\n Object.keys(options).forEach(key => {\n if (isPlainObject.isPlainObject(options[key])) {\n if (!(key in defaults)) Object.assign(result, {\n [key]: options[key]\n });else result[key] = mergeDeep(defaults[key], options[key]);\n } else {\n Object.assign(result, {\n [key]: options[key]\n });\n }\n });\n return result;\n}\n\nfunction merge(defaults, route, options) {\n if (typeof route === \"string\") {\n let [method, url] = route.split(\" \");\n options = Object.assign(url ? {\n method,\n url\n } : {\n url: method\n }, options);\n } else {\n options = Object.assign({}, route);\n } // lowercase header names before merging with defaults to avoid duplicates\n\n\n options.headers = lowercaseKeys(options.headers);\n const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten\n\n if (defaults && defaults.mediaType.previews.length) {\n mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);\n }\n\n mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, \"\"));\n return mergedOptions;\n}\n\nfunction addQueryParameters(url, parameters) {\n const separator = /\\?/.test(url) ? \"&\" : \"?\";\n const names = Object.keys(parameters);\n\n if (names.length === 0) {\n return url;\n }\n\n return url + separator + names.map(name => {\n if (name === \"q\") {\n return \"q=\" + parameters.q.split(\"+\").map(encodeURIComponent).join(\"+\");\n }\n\n return `${name}=${encodeURIComponent(parameters[name])}`;\n }).join(\"&\");\n}\n\nconst urlVariableRegex = /\\{[^}]+\\}/g;\n\nfunction removeNonChars(variableName) {\n return variableName.replace(/^\\W+|\\W+$/g, \"\").split(/,/);\n}\n\nfunction extractUrlVariableNames(url) {\n const matches = url.match(urlVariableRegex);\n\n if (!matches) {\n return [];\n }\n\n return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);\n}\n\nfunction omit(object, keysToOmit) {\n return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => {\n obj[key] = object[key];\n return obj;\n }, {});\n}\n\n// Based on https://github.com/bramstein/url-template, licensed under BSD\n// TODO: create separate package.\n//\n// Copyright (c) 2012-2014, Bram Stein\n// All rights reserved.\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. The name of the author may not be used to endorse or promote products\n// derived from this software without specific prior written permission.\n// THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n/* istanbul ignore file */\nfunction encodeReserved(str) {\n return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {\n if (!/%[0-9A-Fa-f]/.test(part)) {\n part = encodeURI(part).replace(/%5B/g, \"[\").replace(/%5D/g, \"]\");\n }\n\n return part;\n }).join(\"\");\n}\n\nfunction encodeUnreserved(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {\n return \"%\" + c.charCodeAt(0).toString(16).toUpperCase();\n });\n}\n\nfunction encodeValue(operator, value, key) {\n value = operator === \"+\" || operator === \"#\" ? encodeReserved(value) : encodeUnreserved(value);\n\n if (key) {\n return encodeUnreserved(key) + \"=\" + value;\n } else {\n return value;\n }\n}\n\nfunction isDefined(value) {\n return value !== undefined && value !== null;\n}\n\nfunction isKeyOperator(operator) {\n return operator === \";\" || operator === \"&\" || operator === \"?\";\n}\n\nfunction getValues(context, operator, key, modifier) {\n var value = context[key],\n result = [];\n\n if (isDefined(value) && value !== \"\") {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n value = value.toString();\n\n if (modifier && modifier !== \"*\") {\n value = value.substring(0, parseInt(modifier, 10));\n }\n\n result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : \"\"));\n } else {\n if (modifier === \"*\") {\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function (value) {\n result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : \"\"));\n });\n } else {\n Object.keys(value).forEach(function (k) {\n if (isDefined(value[k])) {\n result.push(encodeValue(operator, value[k], k));\n }\n });\n }\n } else {\n const tmp = [];\n\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function (value) {\n tmp.push(encodeValue(operator, value));\n });\n } else {\n Object.keys(value).forEach(function (k) {\n if (isDefined(value[k])) {\n tmp.push(encodeUnreserved(k));\n tmp.push(encodeValue(operator, value[k].toString()));\n }\n });\n }\n\n if (isKeyOperator(operator)) {\n result.push(encodeUnreserved(key) + \"=\" + tmp.join(\",\"));\n } else if (tmp.length !== 0) {\n result.push(tmp.join(\",\"));\n }\n }\n }\n } else {\n if (operator === \";\") {\n if (isDefined(value)) {\n result.push(encodeUnreserved(key));\n }\n } else if (value === \"\" && (operator === \"&\" || operator === \"?\")) {\n result.push(encodeUnreserved(key) + \"=\");\n } else if (value === \"\") {\n result.push(\"\");\n }\n }\n\n return result;\n}\n\nfunction parseUrl(template) {\n return {\n expand: expand.bind(null, template)\n };\n}\n\nfunction expand(template, context) {\n var operators = [\"+\", \"#\", \".\", \"/\", \";\", \"?\", \"&\"];\n return template.replace(/\\{([^\\{\\}]+)\\}|([^\\{\\}]+)/g, function (_, expression, literal) {\n if (expression) {\n let operator = \"\";\n const values = [];\n\n if (operators.indexOf(expression.charAt(0)) !== -1) {\n operator = expression.charAt(0);\n expression = expression.substr(1);\n }\n\n expression.split(/,/g).forEach(function (variable) {\n var tmp = /([^:\\*]*)(?::(\\d+)|(\\*))?/.exec(variable);\n values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));\n });\n\n if (operator && operator !== \"+\") {\n var separator = \",\";\n\n if (operator === \"?\") {\n separator = \"&\";\n } else if (operator !== \"#\") {\n separator = operator;\n }\n\n return (values.length !== 0 ? operator : \"\") + values.join(separator);\n } else {\n return values.join(\",\");\n }\n } else {\n return encodeReserved(literal);\n }\n });\n}\n\nfunction parse(options) {\n // https://fetch.spec.whatwg.org/#methods\n let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible\n\n let url = (options.url || \"/\").replace(/:([a-z]\\w+)/g, \"{+$1}\");\n let headers = Object.assign({}, options.headers);\n let body;\n let parameters = omit(options, [\"method\", \"baseUrl\", \"url\", \"headers\", \"request\", \"mediaType\"]); // extract variable names from URL to calculate remaining variables later\n\n const urlVariableNames = extractUrlVariableNames(url);\n url = parseUrl(url).expand(parameters);\n\n if (!/^http/.test(url)) {\n url = options.baseUrl + url;\n }\n\n const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat(\"baseUrl\");\n const remainingParameters = omit(parameters, omittedParameters);\n const isBinaryRequest = /application\\/octet-stream/i.test(headers.accept);\n\n if (!isBinaryRequest) {\n if (options.mediaType.format) {\n // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw\n headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\\/vnd(\\.\\w+)(\\.v3)?(\\.\\w+)?(\\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(\",\");\n }\n\n if (options.mediaType.previews.length) {\n const previewsFromAcceptHeader = headers.accept.match(/[\\w-]+(?=-preview)/g) || [];\n headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => {\n const format = options.mediaType.format ? `.${options.mediaType.format}` : \"+json\";\n return `application/vnd.github.${preview}-preview${format}`;\n }).join(\",\");\n }\n } // for GET/HEAD requests, set URL query parameters from remaining parameters\n // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters\n\n\n if ([\"GET\", \"HEAD\"].includes(method)) {\n url = addQueryParameters(url, remainingParameters);\n } else {\n if (\"data\" in remainingParameters) {\n body = remainingParameters.data;\n } else {\n if (Object.keys(remainingParameters).length) {\n body = remainingParameters;\n } else {\n headers[\"content-length\"] = 0;\n }\n }\n } // default content-type for JSON if body is set\n\n\n if (!headers[\"content-type\"] && typeof body !== \"undefined\") {\n headers[\"content-type\"] = \"application/json; charset=utf-8\";\n } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body.\n // fetch does not allow to set `content-length` header, but we can set body to an empty string\n\n\n if ([\"PATCH\", \"PUT\"].includes(method) && typeof body === \"undefined\") {\n body = \"\";\n } // Only return body/request keys if present\n\n\n return Object.assign({\n method,\n url,\n headers\n }, typeof body !== \"undefined\" ? {\n body\n } : null, options.request ? {\n request: options.request\n } : null);\n}\n\nfunction endpointWithDefaults(defaults, route, options) {\n return parse(merge(defaults, route, options));\n}\n\nfunction withDefaults(oldDefaults, newDefaults) {\n const DEFAULTS = merge(oldDefaults, newDefaults);\n const endpoint = endpointWithDefaults.bind(null, DEFAULTS);\n return Object.assign(endpoint, {\n DEFAULTS,\n defaults: withDefaults.bind(null, DEFAULTS),\n merge: merge.bind(null, DEFAULTS),\n parse\n });\n}\n\nconst VERSION = \"6.0.6\";\n\nconst userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url.\n// So we use RequestParameters and add method as additional required property.\n\nconst DEFAULTS = {\n method: \"GET\",\n baseUrl: \"https://api.github.com\",\n headers: {\n accept: \"application/vnd.github.v3+json\",\n \"user-agent\": userAgent\n },\n mediaType: {\n format: \"\",\n previews: []\n }\n};\n\nconst endpoint = withDefaults(null, DEFAULTS);\n\nexports.endpoint = endpoint;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n/*!\n * is-plain-object \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nfunction isObject(o) {\n return Object.prototype.toString.call(o) === '[object Object]';\n}\n\nfunction isPlainObject(o) {\n var ctor,prot;\n\n if (isObject(o) === false) return false;\n\n // If has modified constructor\n ctor = o.constructor;\n if (ctor === undefined) return true;\n\n // If has modified prototype\n prot = ctor.prototype;\n if (isObject(prot) === false) return false;\n\n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n\n // Most likely a plain Object\n return true;\n}\n\nexports.isPlainObject = isPlainObject;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar request = require('@octokit/request');\nvar universalUserAgent = require('universal-user-agent');\n\nconst VERSION = \"4.5.6\";\n\nclass GraphqlError extends Error {\n constructor(request, response) {\n const message = response.data.errors[0].message;\n super(message);\n Object.assign(this, response.data);\n Object.assign(this, {\n headers: response.headers\n });\n this.name = \"GraphqlError\";\n this.request = request; // Maintains proper stack trace (only available on V8)\n\n /* istanbul ignore next */\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n}\n\nconst NON_VARIABLE_OPTIONS = [\"method\", \"baseUrl\", \"url\", \"headers\", \"request\", \"query\", \"mediaType\"];\nconst GHES_V3_SUFFIX_REGEX = /\\/api\\/v3\\/?$/;\nfunction graphql(request, query, options) {\n if (typeof query === \"string\" && options && \"query\" in options) {\n return Promise.reject(new Error(`[@octokit/graphql] \"query\" cannot be used as variable name`));\n }\n\n const parsedOptions = typeof query === \"string\" ? Object.assign({\n query\n }, options) : query;\n const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {\n if (NON_VARIABLE_OPTIONS.includes(key)) {\n result[key] = parsedOptions[key];\n return result;\n }\n\n if (!result.variables) {\n result.variables = {};\n }\n\n result.variables[key] = parsedOptions[key];\n return result;\n }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix\n // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451\n\n const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;\n\n if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {\n requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, \"/api/graphql\");\n }\n\n return request(requestOptions).then(response => {\n if (response.data.errors) {\n const headers = {};\n\n for (const key of Object.keys(response.headers)) {\n headers[key] = response.headers[key];\n }\n\n throw new GraphqlError(requestOptions, {\n headers,\n data: response.data\n });\n }\n\n return response.data.data;\n });\n}\n\nfunction withDefaults(request$1, newDefaults) {\n const newRequest = request$1.defaults(newDefaults);\n\n const newApi = (query, options) => {\n return graphql(newRequest, query, options);\n };\n\n return Object.assign(newApi, {\n defaults: withDefaults.bind(null, newRequest),\n endpoint: request.request.endpoint\n });\n}\n\nconst graphql$1 = withDefaults(request.request, {\n headers: {\n \"user-agent\": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}`\n },\n method: \"POST\",\n url: \"/graphql\"\n});\nfunction withCustomRequest(customRequest) {\n return withDefaults(customRequest, {\n method: \"POST\",\n url: \"/graphql\"\n });\n}\n\nexports.graphql = graphql$1;\nexports.withCustomRequest = withCustomRequest;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst VERSION = \"2.3.3\";\n\n/**\n * Some “list” response that can be paginated have a different response structure\n *\n * They have a `total_count` key in the response (search also has `incomplete_results`,\n * /installation/repositories also has `repository_selection`), as well as a key with\n * the list of the items which name varies from endpoint to endpoint.\n *\n * Octokit normalizes these responses so that paginated results are always returned following\n * the same structure. One challenge is that if the list response has only one page, no Link\n * header is provided, so this header alone is not sufficient to check wether a response is\n * paginated or not.\n *\n * We check if a \"total_count\" key is present in the response data, but also make sure that\n * a \"url\" property is not, as the \"Get the combined status for a specific ref\" endpoint would\n * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref\n */\nfunction normalizePaginatedListResponse(response) {\n const responseNeedsNormalization = \"total_count\" in response.data && !(\"url\" in response.data);\n if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way\n // to retrieve the same information.\n\n const incompleteResults = response.data.incomplete_results;\n const repositorySelection = response.data.repository_selection;\n const totalCount = response.data.total_count;\n delete response.data.incomplete_results;\n delete response.data.repository_selection;\n delete response.data.total_count;\n const namespaceKey = Object.keys(response.data)[0];\n const data = response.data[namespaceKey];\n response.data = data;\n\n if (typeof incompleteResults !== \"undefined\") {\n response.data.incomplete_results = incompleteResults;\n }\n\n if (typeof repositorySelection !== \"undefined\") {\n response.data.repository_selection = repositorySelection;\n }\n\n response.data.total_count = totalCount;\n return response;\n}\n\nfunction iterator(octokit, route, parameters) {\n const options = typeof route === \"function\" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);\n const requestMethod = typeof route === \"function\" ? route : octokit.request;\n const method = options.method;\n const headers = options.headers;\n let url = options.url;\n return {\n [Symbol.asyncIterator]: () => ({\n next() {\n if (!url) {\n return Promise.resolve({\n done: true\n });\n }\n\n return requestMethod({\n method,\n url,\n headers\n }).then(normalizePaginatedListResponse).then(response => {\n // `response.headers.link` format:\n // '; rel=\"next\", ; rel=\"last\"'\n // sets `url` to undefined if \"next\" URL is not present or `link` header is not set\n url = ((response.headers.link || \"\").match(/<([^>]+)>;\\s*rel=\"next\"/) || [])[1];\n return {\n value: response\n };\n });\n }\n\n })\n };\n}\n\nfunction paginate(octokit, route, parameters, mapFn) {\n if (typeof parameters === \"function\") {\n mapFn = parameters;\n parameters = undefined;\n }\n\n return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn);\n}\n\nfunction gather(octokit, results, iterator, mapFn) {\n return iterator.next().then(result => {\n if (result.done) {\n return results;\n }\n\n let earlyExit = false;\n\n function done() {\n earlyExit = true;\n }\n\n results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data);\n\n if (earlyExit) {\n return results;\n }\n\n return gather(octokit, results, iterator, mapFn);\n });\n}\n\n/**\n * @param octokit Octokit instance\n * @param options Options passed to Octokit constructor\n */\n\nfunction paginateRest(octokit) {\n return {\n paginate: Object.assign(paginate.bind(null, octokit), {\n iterator: iterator.bind(null, octokit)\n })\n };\n}\npaginateRest.VERSION = VERSION;\n\nexports.paginateRest = paginateRest;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst VERSION = \"1.0.0\";\n\n/**\n * @param octokit Octokit instance\n * @param options Options passed to Octokit constructor\n */\n\nfunction requestLog(octokit) {\n octokit.hook.wrap(\"request\", (request, options) => {\n octokit.log.debug(\"request\", options);\n const start = Date.now();\n const requestOptions = octokit.request.endpoint.parse(options);\n const path = requestOptions.url.replace(options.baseUrl, \"\");\n return request(options).then(response => {\n octokit.log.info(`${requestOptions.method} ${path} - ${response.status} in ${Date.now() - start}ms`);\n return response;\n }).catch(error => {\n octokit.log.info(`${requestOptions.method} ${path} - ${error.status} in ${Date.now() - start}ms`);\n throw error;\n });\n });\n}\nrequestLog.VERSION = VERSION;\n\nexports.requestLog = requestLog;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst Endpoints = {\n actions: {\n addSelectedRepoToOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\"],\n cancelWorkflowRun: [\"POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel\"],\n createOrUpdateOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}\"],\n createOrUpdateRepoSecret: [\"PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n createRegistrationTokenForOrg: [\"POST /orgs/{org}/actions/runners/registration-token\"],\n createRegistrationTokenForRepo: [\"POST /repos/{owner}/{repo}/actions/runners/registration-token\"],\n createRemoveTokenForOrg: [\"POST /orgs/{org}/actions/runners/remove-token\"],\n createRemoveTokenForRepo: [\"POST /repos/{owner}/{repo}/actions/runners/remove-token\"],\n createWorkflowDispatch: [\"POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches\"],\n deleteArtifact: [\"DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\"],\n deleteOrgSecret: [\"DELETE /orgs/{org}/actions/secrets/{secret_name}\"],\n deleteRepoSecret: [\"DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n deleteSelfHostedRunnerFromOrg: [\"DELETE /orgs/{org}/actions/runners/{runner_id}\"],\n deleteSelfHostedRunnerFromRepo: [\"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}\"],\n deleteWorkflowRun: [\"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n deleteWorkflowRunLogs: [\"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs\"],\n downloadArtifact: [\"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}\"],\n downloadJobLogsForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs\"],\n downloadWorkflowRunLogs: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs\"],\n getArtifact: [\"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\"],\n getJobForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/jobs/{job_id}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/actions/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/actions/secrets/{secret_name}\"],\n getRepoPublicKey: [\"GET /repos/{owner}/{repo}/actions/secrets/public-key\"],\n getRepoSecret: [\"GET /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n getSelfHostedRunnerForOrg: [\"GET /orgs/{org}/actions/runners/{runner_id}\"],\n getSelfHostedRunnerForRepo: [\"GET /repos/{owner}/{repo}/actions/runners/{runner_id}\"],\n getWorkflow: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}\"],\n getWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n getWorkflowRunUsage: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing\"],\n getWorkflowUsage: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing\"],\n listArtifactsForRepo: [\"GET /repos/{owner}/{repo}/actions/artifacts\"],\n listJobsForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs\"],\n listOrgSecrets: [\"GET /orgs/{org}/actions/secrets\"],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/actions/secrets\"],\n listRepoWorkflows: [\"GET /repos/{owner}/{repo}/actions/workflows\"],\n listRunnerApplicationsForOrg: [\"GET /orgs/{org}/actions/runners/downloads\"],\n listRunnerApplicationsForRepo: [\"GET /repos/{owner}/{repo}/actions/runners/downloads\"],\n listSelectedReposForOrgSecret: [\"GET /orgs/{org}/actions/secrets/{secret_name}/repositories\"],\n listSelfHostedRunnersForOrg: [\"GET /orgs/{org}/actions/runners\"],\n listSelfHostedRunnersForRepo: [\"GET /repos/{owner}/{repo}/actions/runners\"],\n listWorkflowRunArtifacts: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts\"],\n listWorkflowRuns: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs\"],\n listWorkflowRunsForRepo: [\"GET /repos/{owner}/{repo}/actions/runs\"],\n reRunWorkflow: [\"POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun\"],\n removeSelectedRepoFromOrgSecret: [\"DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\"],\n setSelectedReposForOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories\"]\n },\n activity: {\n checkRepoIsStarredByAuthenticatedUser: [\"GET /user/starred/{owner}/{repo}\"],\n deleteRepoSubscription: [\"DELETE /repos/{owner}/{repo}/subscription\"],\n deleteThreadSubscription: [\"DELETE /notifications/threads/{thread_id}/subscription\"],\n getFeeds: [\"GET /feeds\"],\n getRepoSubscription: [\"GET /repos/{owner}/{repo}/subscription\"],\n getThread: [\"GET /notifications/threads/{thread_id}\"],\n getThreadSubscriptionForAuthenticatedUser: [\"GET /notifications/threads/{thread_id}/subscription\"],\n listEventsForAuthenticatedUser: [\"GET /users/{username}/events\"],\n listNotificationsForAuthenticatedUser: [\"GET /notifications\"],\n listOrgEventsForAuthenticatedUser: [\"GET /users/{username}/events/orgs/{org}\"],\n listPublicEvents: [\"GET /events\"],\n listPublicEventsForRepoNetwork: [\"GET /networks/{owner}/{repo}/events\"],\n listPublicEventsForUser: [\"GET /users/{username}/events/public\"],\n listPublicOrgEvents: [\"GET /orgs/{org}/events\"],\n listReceivedEventsForUser: [\"GET /users/{username}/received_events\"],\n listReceivedPublicEventsForUser: [\"GET /users/{username}/received_events/public\"],\n listRepoEvents: [\"GET /repos/{owner}/{repo}/events\"],\n listRepoNotificationsForAuthenticatedUser: [\"GET /repos/{owner}/{repo}/notifications\"],\n listReposStarredByAuthenticatedUser: [\"GET /user/starred\"],\n listReposStarredByUser: [\"GET /users/{username}/starred\"],\n listReposWatchedByUser: [\"GET /users/{username}/subscriptions\"],\n listStargazersForRepo: [\"GET /repos/{owner}/{repo}/stargazers\"],\n listWatchedReposForAuthenticatedUser: [\"GET /user/subscriptions\"],\n listWatchersForRepo: [\"GET /repos/{owner}/{repo}/subscribers\"],\n markNotificationsAsRead: [\"PUT /notifications\"],\n markRepoNotificationsAsRead: [\"PUT /repos/{owner}/{repo}/notifications\"],\n markThreadAsRead: [\"PATCH /notifications/threads/{thread_id}\"],\n setRepoSubscription: [\"PUT /repos/{owner}/{repo}/subscription\"],\n setThreadSubscription: [\"PUT /notifications/threads/{thread_id}/subscription\"],\n starRepoForAuthenticatedUser: [\"PUT /user/starred/{owner}/{repo}\"],\n unstarRepoForAuthenticatedUser: [\"DELETE /user/starred/{owner}/{repo}\"]\n },\n apps: {\n addRepoToInstallation: [\"PUT /user/installations/{installation_id}/repositories/{repository_id}\"],\n checkToken: [\"POST /applications/{client_id}/token\"],\n createContentAttachment: [\"POST /content_references/{content_reference_id}/attachments\", {\n mediaType: {\n previews: [\"corsair\"]\n }\n }],\n createFromManifest: [\"POST /app-manifests/{code}/conversions\"],\n createInstallationAccessToken: [\"POST /app/installations/{installation_id}/access_tokens\"],\n deleteAuthorization: [\"DELETE /applications/{client_id}/grant\"],\n deleteInstallation: [\"DELETE /app/installations/{installation_id}\"],\n deleteToken: [\"DELETE /applications/{client_id}/token\"],\n getAuthenticated: [\"GET /app\"],\n getBySlug: [\"GET /apps/{app_slug}\"],\n getInstallation: [\"GET /app/installations/{installation_id}\"],\n getOrgInstallation: [\"GET /orgs/{org}/installation\"],\n getRepoInstallation: [\"GET /repos/{owner}/{repo}/installation\"],\n getSubscriptionPlanForAccount: [\"GET /marketplace_listing/accounts/{account_id}\"],\n getSubscriptionPlanForAccountStubbed: [\"GET /marketplace_listing/stubbed/accounts/{account_id}\"],\n getUserInstallation: [\"GET /users/{username}/installation\"],\n listAccountsForPlan: [\"GET /marketplace_listing/plans/{plan_id}/accounts\"],\n listAccountsForPlanStubbed: [\"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts\"],\n listInstallationReposForAuthenticatedUser: [\"GET /user/installations/{installation_id}/repositories\"],\n listInstallations: [\"GET /app/installations\"],\n listInstallationsForAuthenticatedUser: [\"GET /user/installations\"],\n listPlans: [\"GET /marketplace_listing/plans\"],\n listPlansStubbed: [\"GET /marketplace_listing/stubbed/plans\"],\n listReposAccessibleToInstallation: [\"GET /installation/repositories\"],\n listSubscriptionsForAuthenticatedUser: [\"GET /user/marketplace_purchases\"],\n listSubscriptionsForAuthenticatedUserStubbed: [\"GET /user/marketplace_purchases/stubbed\"],\n removeRepoFromInstallation: [\"DELETE /user/installations/{installation_id}/repositories/{repository_id}\"],\n resetToken: [\"PATCH /applications/{client_id}/token\"],\n revokeInstallationAccessToken: [\"DELETE /installation/token\"],\n suspendInstallation: [\"PUT /app/installations/{installation_id}/suspended\"],\n unsuspendInstallation: [\"DELETE /app/installations/{installation_id}/suspended\"]\n },\n billing: {\n getGithubActionsBillingOrg: [\"GET /orgs/{org}/settings/billing/actions\"],\n getGithubActionsBillingUser: [\"GET /users/{username}/settings/billing/actions\"],\n getGithubPackagesBillingOrg: [\"GET /orgs/{org}/settings/billing/packages\"],\n getGithubPackagesBillingUser: [\"GET /users/{username}/settings/billing/packages\"],\n getSharedStorageBillingOrg: [\"GET /orgs/{org}/settings/billing/shared-storage\"],\n getSharedStorageBillingUser: [\"GET /users/{username}/settings/billing/shared-storage\"]\n },\n checks: {\n create: [\"POST /repos/{owner}/{repo}/check-runs\", {\n mediaType: {\n previews: [\"antiope\"]\n }\n }],\n createSuite: [\"POST /repos/{owner}/{repo}/check-suites\", {\n mediaType: {\n previews: [\"antiope\"]\n }\n }],\n get: [\"GET /repos/{owner}/{repo}/check-runs/{check_run_id}\", {\n mediaType: {\n previews: [\"antiope\"]\n }\n }],\n getSuite: [\"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}\", {\n mediaType: {\n previews: [\"antiope\"]\n }\n }],\n listAnnotations: [\"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations\", {\n mediaType: {\n previews: [\"antiope\"]\n }\n }],\n listForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-runs\", {\n mediaType: {\n previews: [\"antiope\"]\n }\n }],\n listForSuite: [\"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs\", {\n mediaType: {\n previews: [\"antiope\"]\n }\n }],\n listSuitesForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-suites\", {\n mediaType: {\n previews: [\"antiope\"]\n }\n }],\n rerequestSuite: [\"POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest\", {\n mediaType: {\n previews: [\"antiope\"]\n }\n }],\n setSuitesPreferences: [\"PATCH /repos/{owner}/{repo}/check-suites/preferences\", {\n mediaType: {\n previews: [\"antiope\"]\n }\n }],\n update: [\"PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}\", {\n mediaType: {\n previews: [\"antiope\"]\n }\n }]\n },\n codeScanning: {\n getAlert: [\"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_id}\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/code-scanning/alerts\"]\n },\n codesOfConduct: {\n getAllCodesOfConduct: [\"GET /codes_of_conduct\", {\n mediaType: {\n previews: [\"scarlet-witch\"]\n }\n }],\n getConductCode: [\"GET /codes_of_conduct/{key}\", {\n mediaType: {\n previews: [\"scarlet-witch\"]\n }\n }],\n getForRepo: [\"GET /repos/{owner}/{repo}/community/code_of_conduct\", {\n mediaType: {\n previews: [\"scarlet-witch\"]\n }\n }]\n },\n emojis: {\n get: [\"GET /emojis\"]\n },\n gists: {\n checkIsStarred: [\"GET /gists/{gist_id}/star\"],\n create: [\"POST /gists\"],\n createComment: [\"POST /gists/{gist_id}/comments\"],\n delete: [\"DELETE /gists/{gist_id}\"],\n deleteComment: [\"DELETE /gists/{gist_id}/comments/{comment_id}\"],\n fork: [\"POST /gists/{gist_id}/forks\"],\n get: [\"GET /gists/{gist_id}\"],\n getComment: [\"GET /gists/{gist_id}/comments/{comment_id}\"],\n getRevision: [\"GET /gists/{gist_id}/{sha}\"],\n list: [\"GET /gists\"],\n listComments: [\"GET /gists/{gist_id}/comments\"],\n listCommits: [\"GET /gists/{gist_id}/commits\"],\n listForUser: [\"GET /users/{username}/gists\"],\n listForks: [\"GET /gists/{gist_id}/forks\"],\n listPublic: [\"GET /gists/public\"],\n listStarred: [\"GET /gists/starred\"],\n star: [\"PUT /gists/{gist_id}/star\"],\n unstar: [\"DELETE /gists/{gist_id}/star\"],\n update: [\"PATCH /gists/{gist_id}\"],\n updateComment: [\"PATCH /gists/{gist_id}/comments/{comment_id}\"]\n },\n git: {\n createBlob: [\"POST /repos/{owner}/{repo}/git/blobs\"],\n createCommit: [\"POST /repos/{owner}/{repo}/git/commits\"],\n createRef: [\"POST /repos/{owner}/{repo}/git/refs\"],\n createTag: [\"POST /repos/{owner}/{repo}/git/tags\"],\n createTree: [\"POST /repos/{owner}/{repo}/git/trees\"],\n deleteRef: [\"DELETE /repos/{owner}/{repo}/git/refs/{ref}\"],\n getBlob: [\"GET /repos/{owner}/{repo}/git/blobs/{file_sha}\"],\n getCommit: [\"GET /repos/{owner}/{repo}/git/commits/{commit_sha}\"],\n getRef: [\"GET /repos/{owner}/{repo}/git/ref/{ref}\"],\n getTag: [\"GET /repos/{owner}/{repo}/git/tags/{tag_sha}\"],\n getTree: [\"GET /repos/{owner}/{repo}/git/trees/{tree_sha}\"],\n listMatchingRefs: [\"GET /repos/{owner}/{repo}/git/matching-refs/{ref}\"],\n updateRef: [\"PATCH /repos/{owner}/{repo}/git/refs/{ref}\"]\n },\n gitignore: {\n getAllTemplates: [\"GET /gitignore/templates\"],\n getTemplate: [\"GET /gitignore/templates/{name}\"]\n },\n interactions: {\n getRestrictionsForOrg: [\"GET /orgs/{org}/interaction-limits\", {\n mediaType: {\n previews: [\"sombra\"]\n }\n }],\n getRestrictionsForRepo: [\"GET /repos/{owner}/{repo}/interaction-limits\", {\n mediaType: {\n previews: [\"sombra\"]\n }\n }],\n removeRestrictionsForOrg: [\"DELETE /orgs/{org}/interaction-limits\", {\n mediaType: {\n previews: [\"sombra\"]\n }\n }],\n removeRestrictionsForRepo: [\"DELETE /repos/{owner}/{repo}/interaction-limits\", {\n mediaType: {\n previews: [\"sombra\"]\n }\n }],\n setRestrictionsForOrg: [\"PUT /orgs/{org}/interaction-limits\", {\n mediaType: {\n previews: [\"sombra\"]\n }\n }],\n setRestrictionsForRepo: [\"PUT /repos/{owner}/{repo}/interaction-limits\", {\n mediaType: {\n previews: [\"sombra\"]\n }\n }]\n },\n issues: {\n addAssignees: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/assignees\"],\n addLabels: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n checkUserCanBeAssigned: [\"GET /repos/{owner}/{repo}/assignees/{assignee}\"],\n create: [\"POST /repos/{owner}/{repo}/issues\"],\n createComment: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/comments\"],\n createLabel: [\"POST /repos/{owner}/{repo}/labels\"],\n createMilestone: [\"POST /repos/{owner}/{repo}/milestones\"],\n deleteComment: [\"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n deleteLabel: [\"DELETE /repos/{owner}/{repo}/labels/{name}\"],\n deleteMilestone: [\"DELETE /repos/{owner}/{repo}/milestones/{milestone_number}\"],\n get: [\"GET /repos/{owner}/{repo}/issues/{issue_number}\"],\n getComment: [\"GET /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n getEvent: [\"GET /repos/{owner}/{repo}/issues/events/{event_id}\"],\n getLabel: [\"GET /repos/{owner}/{repo}/labels/{name}\"],\n getMilestone: [\"GET /repos/{owner}/{repo}/milestones/{milestone_number}\"],\n list: [\"GET /issues\"],\n listAssignees: [\"GET /repos/{owner}/{repo}/assignees\"],\n listComments: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/comments\"],\n listCommentsForRepo: [\"GET /repos/{owner}/{repo}/issues/comments\"],\n listEvents: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/events\"],\n listEventsForRepo: [\"GET /repos/{owner}/{repo}/issues/events\"],\n listEventsForTimeline: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline\", {\n mediaType: {\n previews: [\"mockingbird\"]\n }\n }],\n listForAuthenticatedUser: [\"GET /user/issues\"],\n listForOrg: [\"GET /orgs/{org}/issues\"],\n listForRepo: [\"GET /repos/{owner}/{repo}/issues\"],\n listLabelsForMilestone: [\"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels\"],\n listLabelsForRepo: [\"GET /repos/{owner}/{repo}/labels\"],\n listLabelsOnIssue: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n listMilestones: [\"GET /repos/{owner}/{repo}/milestones\"],\n lock: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n removeAllLabels: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n removeAssignees: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees\"],\n removeLabel: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}\"],\n setLabels: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n unlock: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n update: [\"PATCH /repos/{owner}/{repo}/issues/{issue_number}\"],\n updateComment: [\"PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n updateLabel: [\"PATCH /repos/{owner}/{repo}/labels/{name}\"],\n updateMilestone: [\"PATCH /repos/{owner}/{repo}/milestones/{milestone_number}\"]\n },\n licenses: {\n get: [\"GET /licenses/{license}\"],\n getAllCommonlyUsed: [\"GET /licenses\"],\n getForRepo: [\"GET /repos/{owner}/{repo}/license\"]\n },\n markdown: {\n render: [\"POST /markdown\"],\n renderRaw: [\"POST /markdown/raw\", {\n headers: {\n \"content-type\": \"text/plain; charset=utf-8\"\n }\n }]\n },\n meta: {\n get: [\"GET /meta\"]\n },\n migrations: {\n cancelImport: [\"DELETE /repos/{owner}/{repo}/import\"],\n deleteArchiveForAuthenticatedUser: [\"DELETE /user/migrations/{migration_id}/archive\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n deleteArchiveForOrg: [\"DELETE /orgs/{org}/migrations/{migration_id}/archive\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n downloadArchiveForOrg: [\"GET /orgs/{org}/migrations/{migration_id}/archive\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n getArchiveForAuthenticatedUser: [\"GET /user/migrations/{migration_id}/archive\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n getCommitAuthors: [\"GET /repos/{owner}/{repo}/import/authors\"],\n getImportStatus: [\"GET /repos/{owner}/{repo}/import\"],\n getLargeFiles: [\"GET /repos/{owner}/{repo}/import/large_files\"],\n getStatusForAuthenticatedUser: [\"GET /user/migrations/{migration_id}\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n getStatusForOrg: [\"GET /orgs/{org}/migrations/{migration_id}\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n listForAuthenticatedUser: [\"GET /user/migrations\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n listForOrg: [\"GET /orgs/{org}/migrations\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n listReposForOrg: [\"GET /orgs/{org}/migrations/{migration_id}/repositories\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n listReposForUser: [\"GET /user/migrations/{migration_id}/repositories\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n mapCommitAuthor: [\"PATCH /repos/{owner}/{repo}/import/authors/{author_id}\"],\n setLfsPreference: [\"PATCH /repos/{owner}/{repo}/import/lfs\"],\n startForAuthenticatedUser: [\"POST /user/migrations\"],\n startForOrg: [\"POST /orgs/{org}/migrations\"],\n startImport: [\"PUT /repos/{owner}/{repo}/import\"],\n unlockRepoForAuthenticatedUser: [\"DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n unlockRepoForOrg: [\"DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock\", {\n mediaType: {\n previews: [\"wyandotte\"]\n }\n }],\n updateImport: [\"PATCH /repos/{owner}/{repo}/import\"]\n },\n orgs: {\n blockUser: [\"PUT /orgs/{org}/blocks/{username}\"],\n checkBlockedUser: [\"GET /orgs/{org}/blocks/{username}\"],\n checkMembershipForUser: [\"GET /orgs/{org}/members/{username}\"],\n checkPublicMembershipForUser: [\"GET /orgs/{org}/public_members/{username}\"],\n convertMemberToOutsideCollaborator: [\"PUT /orgs/{org}/outside_collaborators/{username}\"],\n createInvitation: [\"POST /orgs/{org}/invitations\"],\n createWebhook: [\"POST /orgs/{org}/hooks\"],\n deleteWebhook: [\"DELETE /orgs/{org}/hooks/{hook_id}\"],\n get: [\"GET /orgs/{org}\"],\n getMembershipForAuthenticatedUser: [\"GET /user/memberships/orgs/{org}\"],\n getMembershipForUser: [\"GET /orgs/{org}/memberships/{username}\"],\n getWebhook: [\"GET /orgs/{org}/hooks/{hook_id}\"],\n list: [\"GET /organizations\"],\n listAppInstallations: [\"GET /orgs/{org}/installations\"],\n listBlockedUsers: [\"GET /orgs/{org}/blocks\"],\n listForAuthenticatedUser: [\"GET /user/orgs\"],\n listForUser: [\"GET /users/{username}/orgs\"],\n listInvitationTeams: [\"GET /orgs/{org}/invitations/{invitation_id}/teams\"],\n listMembers: [\"GET /orgs/{org}/members\"],\n listMembershipsForAuthenticatedUser: [\"GET /user/memberships/orgs\"],\n listOutsideCollaborators: [\"GET /orgs/{org}/outside_collaborators\"],\n listPendingInvitations: [\"GET /orgs/{org}/invitations\"],\n listPublicMembers: [\"GET /orgs/{org}/public_members\"],\n listWebhooks: [\"GET /orgs/{org}/hooks\"],\n pingWebhook: [\"POST /orgs/{org}/hooks/{hook_id}/pings\"],\n removeMember: [\"DELETE /orgs/{org}/members/{username}\"],\n removeMembershipForUser: [\"DELETE /orgs/{org}/memberships/{username}\"],\n removeOutsideCollaborator: [\"DELETE /orgs/{org}/outside_collaborators/{username}\"],\n removePublicMembershipForAuthenticatedUser: [\"DELETE /orgs/{org}/public_members/{username}\"],\n setMembershipForUser: [\"PUT /orgs/{org}/memberships/{username}\"],\n setPublicMembershipForAuthenticatedUser: [\"PUT /orgs/{org}/public_members/{username}\"],\n unblockUser: [\"DELETE /orgs/{org}/blocks/{username}\"],\n update: [\"PATCH /orgs/{org}\"],\n updateMembershipForAuthenticatedUser: [\"PATCH /user/memberships/orgs/{org}\"],\n updateWebhook: [\"PATCH /orgs/{org}/hooks/{hook_id}\"]\n },\n projects: {\n addCollaborator: [\"PUT /projects/{project_id}/collaborators/{username}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createCard: [\"POST /projects/columns/{column_id}/cards\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createColumn: [\"POST /projects/{project_id}/columns\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createForAuthenticatedUser: [\"POST /user/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createForOrg: [\"POST /orgs/{org}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n createForRepo: [\"POST /repos/{owner}/{repo}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n delete: [\"DELETE /projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n deleteCard: [\"DELETE /projects/columns/cards/{card_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n deleteColumn: [\"DELETE /projects/columns/{column_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n get: [\"GET /projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n getCard: [\"GET /projects/columns/cards/{card_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n getColumn: [\"GET /projects/columns/{column_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n getPermissionForUser: [\"GET /projects/{project_id}/collaborators/{username}/permission\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listCards: [\"GET /projects/columns/{column_id}/cards\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listCollaborators: [\"GET /projects/{project_id}/collaborators\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listColumns: [\"GET /projects/{project_id}/columns\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listForOrg: [\"GET /orgs/{org}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listForRepo: [\"GET /repos/{owner}/{repo}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listForUser: [\"GET /users/{username}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n moveCard: [\"POST /projects/columns/cards/{card_id}/moves\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n moveColumn: [\"POST /projects/columns/{column_id}/moves\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n removeCollaborator: [\"DELETE /projects/{project_id}/collaborators/{username}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n update: [\"PATCH /projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n updateCard: [\"PATCH /projects/columns/cards/{card_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n updateColumn: [\"PATCH /projects/columns/{column_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }]\n },\n pulls: {\n checkIfMerged: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n create: [\"POST /repos/{owner}/{repo}/pulls\"],\n createReplyForReviewComment: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies\"],\n createReview: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n createReviewComment: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments\"],\n deletePendingReview: [\"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"],\n deleteReviewComment: [\"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}\"],\n dismissReview: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals\"],\n get: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}\"],\n getReview: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"],\n getReviewComment: [\"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}\"],\n list: [\"GET /repos/{owner}/{repo}/pulls\"],\n listCommentsForReview: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments\"],\n listCommits: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits\"],\n listFiles: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/files\"],\n listRequestedReviewers: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"],\n listReviewComments: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments\"],\n listReviewCommentsForRepo: [\"GET /repos/{owner}/{repo}/pulls/comments\"],\n listReviews: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n merge: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n removeRequestedReviewers: [\"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"],\n requestReviewers: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"],\n submitReview: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events\"],\n update: [\"PATCH /repos/{owner}/{repo}/pulls/{pull_number}\"],\n updateBranch: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch\", {\n mediaType: {\n previews: [\"lydian\"]\n }\n }],\n updateReview: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"],\n updateReviewComment: [\"PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}\"]\n },\n rateLimit: {\n get: [\"GET /rate_limit\"]\n },\n reactions: {\n createForCommitComment: [\"POST /repos/{owner}/{repo}/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForIssue: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForIssueComment: [\"POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForPullRequestReviewComment: [\"POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForTeamDiscussionCommentInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n createForTeamDiscussionInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForCommitComment: [\"DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForIssue: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForIssueComment: [\"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForPullRequestComment: [\"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForTeamDiscussion: [\"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteForTeamDiscussionComment: [\"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n deleteLegacy: [\"DELETE /reactions/{reaction_id}\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }, {\n deprecated: \"octokit.reactions.deleteLegacy() is deprecated, see https://developer.github.com/v3/reactions/#delete-a-reaction-legacy\"\n }],\n listForCommitComment: [\"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForIssue: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForIssueComment: [\"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForPullRequestReviewComment: [\"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForTeamDiscussionCommentInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }],\n listForTeamDiscussionInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\", {\n mediaType: {\n previews: [\"squirrel-girl\"]\n }\n }]\n },\n repos: {\n acceptInvitation: [\"PATCH /user/repository_invitations/{invitation_id}\"],\n addAppAccessRestrictions: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\", {}, {\n mapToData: \"apps\"\n }],\n addCollaborator: [\"PUT /repos/{owner}/{repo}/collaborators/{username}\"],\n addStatusCheckContexts: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\", {}, {\n mapToData: \"contexts\"\n }],\n addTeamAccessRestrictions: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\", {}, {\n mapToData: \"teams\"\n }],\n addUserAccessRestrictions: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\", {}, {\n mapToData: \"users\"\n }],\n checkCollaborator: [\"GET /repos/{owner}/{repo}/collaborators/{username}\"],\n checkVulnerabilityAlerts: [\"GET /repos/{owner}/{repo}/vulnerability-alerts\", {\n mediaType: {\n previews: [\"dorian\"]\n }\n }],\n compareCommits: [\"GET /repos/{owner}/{repo}/compare/{base}...{head}\"],\n createCommitComment: [\"POST /repos/{owner}/{repo}/commits/{commit_sha}/comments\"],\n createCommitSignatureProtection: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\", {\n mediaType: {\n previews: [\"zzzax\"]\n }\n }],\n createCommitStatus: [\"POST /repos/{owner}/{repo}/statuses/{sha}\"],\n createDeployKey: [\"POST /repos/{owner}/{repo}/keys\"],\n createDeployment: [\"POST /repos/{owner}/{repo}/deployments\"],\n createDeploymentStatus: [\"POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\"],\n createDispatchEvent: [\"POST /repos/{owner}/{repo}/dispatches\"],\n createForAuthenticatedUser: [\"POST /user/repos\"],\n createFork: [\"POST /repos/{owner}/{repo}/forks\"],\n createInOrg: [\"POST /orgs/{org}/repos\"],\n createOrUpdateFileContents: [\"PUT /repos/{owner}/{repo}/contents/{path}\"],\n createPagesSite: [\"POST /repos/{owner}/{repo}/pages\", {\n mediaType: {\n previews: [\"switcheroo\"]\n }\n }],\n createRelease: [\"POST /repos/{owner}/{repo}/releases\"],\n createUsingTemplate: [\"POST /repos/{template_owner}/{template_repo}/generate\", {\n mediaType: {\n previews: [\"baptiste\"]\n }\n }],\n createWebhook: [\"POST /repos/{owner}/{repo}/hooks\"],\n declineInvitation: [\"DELETE /user/repository_invitations/{invitation_id}\"],\n delete: [\"DELETE /repos/{owner}/{repo}\"],\n deleteAccessRestrictions: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\"],\n deleteAdminBranchProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"],\n deleteBranchProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection\"],\n deleteCommitComment: [\"DELETE /repos/{owner}/{repo}/comments/{comment_id}\"],\n deleteCommitSignatureProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\", {\n mediaType: {\n previews: [\"zzzax\"]\n }\n }],\n deleteDeployKey: [\"DELETE /repos/{owner}/{repo}/keys/{key_id}\"],\n deleteDeployment: [\"DELETE /repos/{owner}/{repo}/deployments/{deployment_id}\"],\n deleteFile: [\"DELETE /repos/{owner}/{repo}/contents/{path}\"],\n deleteInvitation: [\"DELETE /repos/{owner}/{repo}/invitations/{invitation_id}\"],\n deletePagesSite: [\"DELETE /repos/{owner}/{repo}/pages\", {\n mediaType: {\n previews: [\"switcheroo\"]\n }\n }],\n deletePullRequestReviewProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"],\n deleteRelease: [\"DELETE /repos/{owner}/{repo}/releases/{release_id}\"],\n deleteReleaseAsset: [\"DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n deleteWebhook: [\"DELETE /repos/{owner}/{repo}/hooks/{hook_id}\"],\n disableAutomatedSecurityFixes: [\"DELETE /repos/{owner}/{repo}/automated-security-fixes\", {\n mediaType: {\n previews: [\"london\"]\n }\n }],\n disableVulnerabilityAlerts: [\"DELETE /repos/{owner}/{repo}/vulnerability-alerts\", {\n mediaType: {\n previews: [\"dorian\"]\n }\n }],\n downloadArchive: [\"GET /repos/{owner}/{repo}/{archive_format}/{ref}\"],\n enableAutomatedSecurityFixes: [\"PUT /repos/{owner}/{repo}/automated-security-fixes\", {\n mediaType: {\n previews: [\"london\"]\n }\n }],\n enableVulnerabilityAlerts: [\"PUT /repos/{owner}/{repo}/vulnerability-alerts\", {\n mediaType: {\n previews: [\"dorian\"]\n }\n }],\n get: [\"GET /repos/{owner}/{repo}\"],\n getAccessRestrictions: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\"],\n getAdminBranchProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"],\n getAllStatusCheckContexts: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\"],\n getAllTopics: [\"GET /repos/{owner}/{repo}/topics\", {\n mediaType: {\n previews: [\"mercy\"]\n }\n }],\n getAppsWithAccessToProtectedBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\"],\n getBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}\"],\n getBranchProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection\"],\n getClones: [\"GET /repos/{owner}/{repo}/traffic/clones\"],\n getCodeFrequencyStats: [\"GET /repos/{owner}/{repo}/stats/code_frequency\"],\n getCollaboratorPermissionLevel: [\"GET /repos/{owner}/{repo}/collaborators/{username}/permission\"],\n getCombinedStatusForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/status\"],\n getCommit: [\"GET /repos/{owner}/{repo}/commits/{ref}\"],\n getCommitActivityStats: [\"GET /repos/{owner}/{repo}/stats/commit_activity\"],\n getCommitComment: [\"GET /repos/{owner}/{repo}/comments/{comment_id}\"],\n getCommitSignatureProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\", {\n mediaType: {\n previews: [\"zzzax\"]\n }\n }],\n getCommunityProfileMetrics: [\"GET /repos/{owner}/{repo}/community/profile\", {\n mediaType: {\n previews: [\"black-panther\"]\n }\n }],\n getContent: [\"GET /repos/{owner}/{repo}/contents/{path}\"],\n getContributorsStats: [\"GET /repos/{owner}/{repo}/stats/contributors\"],\n getDeployKey: [\"GET /repos/{owner}/{repo}/keys/{key_id}\"],\n getDeployment: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}\"],\n getDeploymentStatus: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}\"],\n getLatestPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/latest\"],\n getLatestRelease: [\"GET /repos/{owner}/{repo}/releases/latest\"],\n getPages: [\"GET /repos/{owner}/{repo}/pages\"],\n getPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/{build_id}\"],\n getParticipationStats: [\"GET /repos/{owner}/{repo}/stats/participation\"],\n getPullRequestReviewProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"],\n getPunchCardStats: [\"GET /repos/{owner}/{repo}/stats/punch_card\"],\n getReadme: [\"GET /repos/{owner}/{repo}/readme\"],\n getRelease: [\"GET /repos/{owner}/{repo}/releases/{release_id}\"],\n getReleaseAsset: [\"GET /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n getReleaseByTag: [\"GET /repos/{owner}/{repo}/releases/tags/{tag}\"],\n getStatusChecksProtection: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"],\n getTeamsWithAccessToProtectedBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\"],\n getTopPaths: [\"GET /repos/{owner}/{repo}/traffic/popular/paths\"],\n getTopReferrers: [\"GET /repos/{owner}/{repo}/traffic/popular/referrers\"],\n getUsersWithAccessToProtectedBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\"],\n getViews: [\"GET /repos/{owner}/{repo}/traffic/views\"],\n getWebhook: [\"GET /repos/{owner}/{repo}/hooks/{hook_id}\"],\n listBranches: [\"GET /repos/{owner}/{repo}/branches\"],\n listBranchesForHeadCommit: [\"GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head\", {\n mediaType: {\n previews: [\"groot\"]\n }\n }],\n listCollaborators: [\"GET /repos/{owner}/{repo}/collaborators\"],\n listCommentsForCommit: [\"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments\"],\n listCommitCommentsForRepo: [\"GET /repos/{owner}/{repo}/comments\"],\n listCommitStatusesForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/statuses\"],\n listCommits: [\"GET /repos/{owner}/{repo}/commits\"],\n listContributors: [\"GET /repos/{owner}/{repo}/contributors\"],\n listDeployKeys: [\"GET /repos/{owner}/{repo}/keys\"],\n listDeploymentStatuses: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\"],\n listDeployments: [\"GET /repos/{owner}/{repo}/deployments\"],\n listForAuthenticatedUser: [\"GET /user/repos\"],\n listForOrg: [\"GET /orgs/{org}/repos\"],\n listForUser: [\"GET /users/{username}/repos\"],\n listForks: [\"GET /repos/{owner}/{repo}/forks\"],\n listInvitations: [\"GET /repos/{owner}/{repo}/invitations\"],\n listInvitationsForAuthenticatedUser: [\"GET /user/repository_invitations\"],\n listLanguages: [\"GET /repos/{owner}/{repo}/languages\"],\n listPagesBuilds: [\"GET /repos/{owner}/{repo}/pages/builds\"],\n listPublic: [\"GET /repositories\"],\n listPullRequestsAssociatedWithCommit: [\"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls\", {\n mediaType: {\n previews: [\"groot\"]\n }\n }],\n listReleaseAssets: [\"GET /repos/{owner}/{repo}/releases/{release_id}/assets\"],\n listReleases: [\"GET /repos/{owner}/{repo}/releases\"],\n listTags: [\"GET /repos/{owner}/{repo}/tags\"],\n listTeams: [\"GET /repos/{owner}/{repo}/teams\"],\n listWebhooks: [\"GET /repos/{owner}/{repo}/hooks\"],\n merge: [\"POST /repos/{owner}/{repo}/merges\"],\n pingWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/pings\"],\n removeAppAccessRestrictions: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\", {}, {\n mapToData: \"apps\"\n }],\n removeCollaborator: [\"DELETE /repos/{owner}/{repo}/collaborators/{username}\"],\n removeStatusCheckContexts: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\", {}, {\n mapToData: \"contexts\"\n }],\n removeStatusCheckProtection: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"],\n removeTeamAccessRestrictions: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\", {}, {\n mapToData: \"teams\"\n }],\n removeUserAccessRestrictions: [\"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\", {}, {\n mapToData: \"users\"\n }],\n replaceAllTopics: [\"PUT /repos/{owner}/{repo}/topics\", {\n mediaType: {\n previews: [\"mercy\"]\n }\n }],\n requestPagesBuild: [\"POST /repos/{owner}/{repo}/pages/builds\"],\n setAdminBranchProtection: [\"POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"],\n setAppAccessRestrictions: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\", {}, {\n mapToData: \"apps\"\n }],\n setStatusCheckContexts: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\", {}, {\n mapToData: \"contexts\"\n }],\n setTeamAccessRestrictions: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\", {}, {\n mapToData: \"teams\"\n }],\n setUserAccessRestrictions: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\", {}, {\n mapToData: \"users\"\n }],\n testPushWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/tests\"],\n transfer: [\"POST /repos/{owner}/{repo}/transfer\"],\n update: [\"PATCH /repos/{owner}/{repo}\"],\n updateBranchProtection: [\"PUT /repos/{owner}/{repo}/branches/{branch}/protection\"],\n updateCommitComment: [\"PATCH /repos/{owner}/{repo}/comments/{comment_id}\"],\n updateInformationAboutPagesSite: [\"PUT /repos/{owner}/{repo}/pages\"],\n updateInvitation: [\"PATCH /repos/{owner}/{repo}/invitations/{invitation_id}\"],\n updatePullRequestReviewProtection: [\"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"],\n updateRelease: [\"PATCH /repos/{owner}/{repo}/releases/{release_id}\"],\n updateReleaseAsset: [\"PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n updateStatusCheckPotection: [\"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"],\n updateWebhook: [\"PATCH /repos/{owner}/{repo}/hooks/{hook_id}\"],\n uploadReleaseAsset: [\"POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}\", {\n baseUrl: \"https://uploads.github.com\"\n }]\n },\n search: {\n code: [\"GET /search/code\"],\n commits: [\"GET /search/commits\", {\n mediaType: {\n previews: [\"cloak\"]\n }\n }],\n issuesAndPullRequests: [\"GET /search/issues\"],\n labels: [\"GET /search/labels\"],\n repos: [\"GET /search/repositories\"],\n topics: [\"GET /search/topics\", {\n mediaType: {\n previews: [\"mercy\"]\n }\n }],\n users: [\"GET /search/users\"]\n },\n teams: {\n addOrUpdateMembershipForUserInOrg: [\"PUT /orgs/{org}/teams/{team_slug}/memberships/{username}\"],\n addOrUpdateProjectPermissionsInOrg: [\"PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n addOrUpdateRepoPermissionsInOrg: [\"PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"],\n checkPermissionsForProjectInOrg: [\"GET /orgs/{org}/teams/{team_slug}/projects/{project_id}\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n checkPermissionsForRepoInOrg: [\"GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"],\n create: [\"POST /orgs/{org}/teams\"],\n createDiscussionCommentInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\"],\n createDiscussionInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions\"],\n deleteDiscussionCommentInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"],\n deleteDiscussionInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"],\n deleteInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}\"],\n getByName: [\"GET /orgs/{org}/teams/{team_slug}\"],\n getDiscussionCommentInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"],\n getDiscussionInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"],\n getMembershipForUserInOrg: [\"GET /orgs/{org}/teams/{team_slug}/memberships/{username}\"],\n list: [\"GET /orgs/{org}/teams\"],\n listChildInOrg: [\"GET /orgs/{org}/teams/{team_slug}/teams\"],\n listDiscussionCommentsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\"],\n listDiscussionsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions\"],\n listForAuthenticatedUser: [\"GET /user/teams\"],\n listMembersInOrg: [\"GET /orgs/{org}/teams/{team_slug}/members\"],\n listPendingInvitationsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/invitations\"],\n listProjectsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/projects\", {\n mediaType: {\n previews: [\"inertia\"]\n }\n }],\n listReposInOrg: [\"GET /orgs/{org}/teams/{team_slug}/repos\"],\n removeMembershipForUserInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}\"],\n removeProjectInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}\"],\n removeRepoInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"],\n updateDiscussionCommentInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"],\n updateDiscussionInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"],\n updateInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}\"]\n },\n users: {\n addEmailForAuthenticated: [\"POST /user/emails\"],\n block: [\"PUT /user/blocks/{username}\"],\n checkBlocked: [\"GET /user/blocks/{username}\"],\n checkFollowingForUser: [\"GET /users/{username}/following/{target_user}\"],\n checkPersonIsFollowedByAuthenticated: [\"GET /user/following/{username}\"],\n createGpgKeyForAuthenticated: [\"POST /user/gpg_keys\"],\n createPublicSshKeyForAuthenticated: [\"POST /user/keys\"],\n deleteEmailForAuthenticated: [\"DELETE /user/emails\"],\n deleteGpgKeyForAuthenticated: [\"DELETE /user/gpg_keys/{gpg_key_id}\"],\n deletePublicSshKeyForAuthenticated: [\"DELETE /user/keys/{key_id}\"],\n follow: [\"PUT /user/following/{username}\"],\n getAuthenticated: [\"GET /user\"],\n getByUsername: [\"GET /users/{username}\"],\n getContextForUser: [\"GET /users/{username}/hovercard\"],\n getGpgKeyForAuthenticated: [\"GET /user/gpg_keys/{gpg_key_id}\"],\n getPublicSshKeyForAuthenticated: [\"GET /user/keys/{key_id}\"],\n list: [\"GET /users\"],\n listBlockedByAuthenticated: [\"GET /user/blocks\"],\n listEmailsForAuthenticated: [\"GET /user/emails\"],\n listFollowedByAuthenticated: [\"GET /user/following\"],\n listFollowersForAuthenticatedUser: [\"GET /user/followers\"],\n listFollowersForUser: [\"GET /users/{username}/followers\"],\n listFollowingForUser: [\"GET /users/{username}/following\"],\n listGpgKeysForAuthenticated: [\"GET /user/gpg_keys\"],\n listGpgKeysForUser: [\"GET /users/{username}/gpg_keys\"],\n listPublicEmailsForAuthenticated: [\"GET /user/public_emails\"],\n listPublicKeysForUser: [\"GET /users/{username}/keys\"],\n listPublicSshKeysForAuthenticated: [\"GET /user/keys\"],\n setPrimaryEmailVisibilityForAuthenticated: [\"PATCH /user/email/visibility\"],\n unblock: [\"DELETE /user/blocks/{username}\"],\n unfollow: [\"DELETE /user/following/{username}\"],\n updateAuthenticated: [\"PATCH /user\"]\n }\n};\n\nconst VERSION = \"4.1.4\";\n\nfunction endpointsToMethods(octokit, endpointsMap) {\n const newMethods = {};\n\n for (const [scope, endpoints] of Object.entries(endpointsMap)) {\n for (const [methodName, endpoint] of Object.entries(endpoints)) {\n const [route, defaults, decorations] = endpoint;\n const [method, url] = route.split(/ /);\n const endpointDefaults = Object.assign({\n method,\n url\n }, defaults);\n\n if (!newMethods[scope]) {\n newMethods[scope] = {};\n }\n\n const scopeMethods = newMethods[scope];\n\n if (decorations) {\n scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations);\n continue;\n }\n\n scopeMethods[methodName] = octokit.request.defaults(endpointDefaults);\n }\n }\n\n return newMethods;\n}\n\nfunction decorate(octokit, scope, methodName, defaults, decorations) {\n const requestWithDefaults = octokit.request.defaults(defaults);\n /* istanbul ignore next */\n\n function withDecorations(...args) {\n // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData`\n\n if (decorations.mapToData) {\n options = Object.assign({}, options, {\n data: options[decorations.mapToData],\n [decorations.mapToData]: undefined\n });\n return requestWithDefaults(options);\n }\n\n if (decorations.renamed) {\n const [newScope, newMethodName] = decorations.renamed;\n octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`);\n }\n\n if (decorations.deprecated) {\n octokit.log.warn(decorations.deprecated);\n }\n\n if (decorations.renamedParameters) {\n // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n const options = requestWithDefaults.endpoint.merge(...args);\n\n for (const [name, alias] of Object.entries(decorations.renamedParameters)) {\n if (name in options) {\n octokit.log.warn(`\"${name}\" parameter is deprecated for \"octokit.${scope}.${methodName}()\". Use \"${alias}\" instead`);\n\n if (!(alias in options)) {\n options[alias] = options[name];\n }\n\n delete options[name];\n }\n }\n\n return requestWithDefaults(options);\n } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n\n\n return requestWithDefaults(...args);\n }\n\n return Object.assign(withDecorations, requestWithDefaults);\n}\n\n/**\n * This plugin is a 1:1 copy of internal @octokit/rest plugins. The primary\n * goal is to rebuild @octokit/rest on top of @octokit/core. Once that is\n * done, we will remove the registerEndpoints methods and return the methods\n * directly as with the other plugins. At that point we will also remove the\n * legacy workarounds and deprecations.\n *\n * See the plan at\n * https://github.com/octokit/plugin-rest-endpoint-methods.js/pull/1\n */\n\nfunction restEndpointMethods(octokit) {\n return endpointsToMethods(octokit, Endpoints);\n}\nrestEndpointMethods.VERSION = VERSION;\n\nexports.restEndpointMethods = restEndpointMethods;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar deprecation = require('deprecation');\nvar once = _interopDefault(require('once'));\n\nconst logOnce = once(deprecation => console.warn(deprecation));\n/**\n * Error with extra properties to help with debugging\n */\n\nclass RequestError extends Error {\n constructor(message, statusCode, options) {\n super(message); // Maintains proper stack trace (only available on V8)\n\n /* istanbul ignore next */\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n this.name = \"HttpError\";\n this.status = statusCode;\n Object.defineProperty(this, \"code\", {\n get() {\n logOnce(new deprecation.Deprecation(\"[@octokit/request-error] `error.code` is deprecated, use `error.status`.\"));\n return statusCode;\n }\n\n });\n this.headers = options.headers || {}; // redact request credentials without mutating original request options\n\n const requestCopy = Object.assign({}, options.request);\n\n if (options.request.headers.authorization) {\n requestCopy.headers = Object.assign({}, options.request.headers, {\n authorization: options.request.headers.authorization.replace(/ .*$/, \" [REDACTED]\")\n });\n }\n\n requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit\n // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications\n .replace(/\\bclient_secret=\\w+/g, \"client_secret=[REDACTED]\") // OAuth tokens can be passed as URL query parameters, although it is not recommended\n // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header\n .replace(/\\baccess_token=\\w+/g, \"access_token=[REDACTED]\");\n this.request = requestCopy;\n }\n\n}\n\nexports.RequestError = RequestError;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar endpoint = require('@octokit/endpoint');\nvar universalUserAgent = require('universal-user-agent');\nvar isPlainObject = require('is-plain-object');\nvar nodeFetch = _interopDefault(require('node-fetch'));\nvar requestError = require('@octokit/request-error');\n\nconst VERSION = \"5.4.8\";\n\nfunction getBufferResponse(response) {\n return response.arrayBuffer();\n}\n\nfunction fetchWrapper(requestOptions) {\n if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {\n requestOptions.body = JSON.stringify(requestOptions.body);\n }\n\n let headers = {};\n let status;\n let url;\n const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch;\n return fetch(requestOptions.url, Object.assign({\n method: requestOptions.method,\n body: requestOptions.body,\n headers: requestOptions.headers,\n redirect: requestOptions.redirect\n }, requestOptions.request)).then(response => {\n url = response.url;\n status = response.status;\n\n for (const keyAndValue of response.headers) {\n headers[keyAndValue[0]] = keyAndValue[1];\n }\n\n if (status === 204 || status === 205) {\n return;\n } // GitHub API returns 200 for HEAD requests\n\n\n if (requestOptions.method === \"HEAD\") {\n if (status < 400) {\n return;\n }\n\n throw new requestError.RequestError(response.statusText, status, {\n headers,\n request: requestOptions\n });\n }\n\n if (status === 304) {\n throw new requestError.RequestError(\"Not modified\", status, {\n headers,\n request: requestOptions\n });\n }\n\n if (status >= 400) {\n return response.text().then(message => {\n const error = new requestError.RequestError(message, status, {\n headers,\n request: requestOptions\n });\n\n try {\n let responseBody = JSON.parse(error.message);\n Object.assign(error, responseBody);\n let errors = responseBody.errors; // Assumption `errors` would always be in Array format\n\n error.message = error.message + \": \" + errors.map(JSON.stringify).join(\", \");\n } catch (e) {// ignore, see octokit/rest.js#684\n }\n\n throw error;\n });\n }\n\n const contentType = response.headers.get(\"content-type\");\n\n if (/application\\/json/.test(contentType)) {\n return response.json();\n }\n\n if (!contentType || /^text\\/|charset=utf-8$/.test(contentType)) {\n return response.text();\n }\n\n return getBufferResponse(response);\n }).then(data => {\n return {\n status,\n url,\n headers,\n data\n };\n }).catch(error => {\n if (error instanceof requestError.RequestError) {\n throw error;\n }\n\n throw new requestError.RequestError(error.message, 500, {\n headers,\n request: requestOptions\n });\n });\n}\n\nfunction withDefaults(oldEndpoint, newDefaults) {\n const endpoint = oldEndpoint.defaults(newDefaults);\n\n const newApi = function (route, parameters) {\n const endpointOptions = endpoint.merge(route, parameters);\n\n if (!endpointOptions.request || !endpointOptions.request.hook) {\n return fetchWrapper(endpoint.parse(endpointOptions));\n }\n\n const request = (route, parameters) => {\n return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters)));\n };\n\n Object.assign(request, {\n endpoint,\n defaults: withDefaults.bind(null, endpoint)\n });\n return endpointOptions.request.hook(request, endpointOptions);\n };\n\n return Object.assign(newApi, {\n endpoint,\n defaults: withDefaults.bind(null, endpoint)\n });\n}\n\nconst request = withDefaults(endpoint.endpoint, {\n headers: {\n \"user-agent\": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}`\n }\n});\n\nexports.request = request;\n//# sourceMappingURL=index.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n/*!\n * is-plain-object \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nfunction isObject(o) {\n return Object.prototype.toString.call(o) === '[object Object]';\n}\n\nfunction isPlainObject(o) {\n var ctor,prot;\n\n if (isObject(o) === false) return false;\n\n // If has modified constructor\n ctor = o.constructor;\n if (ctor === undefined) return true;\n\n // If has modified prototype\n prot = ctor.prototype;\n if (isObject(prot) === false) return false;\n\n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n\n // Most likely a plain Object\n return true;\n}\n\nexports.isPlainObject = isPlainObject;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar core = require('@octokit/core');\nvar pluginRequestLog = require('@octokit/plugin-request-log');\nvar pluginPaginateRest = require('@octokit/plugin-paginate-rest');\nvar pluginRestEndpointMethods = require('@octokit/plugin-rest-endpoint-methods');\n\nconst VERSION = \"18.0.5\";\n\nconst Octokit = core.Octokit.plugin(pluginRequestLog.requestLog, pluginRestEndpointMethods.restEndpointMethods, pluginPaginateRest.paginateRest).defaults({\n userAgent: `octokit-rest.js/${VERSION}`\n});\n\nexports.Octokit = Octokit;\n//# sourceMappingURL=index.js.map\n","'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n const nil = new Int32Array(new SharedArrayBuffer(4))\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n\n Atomics.wait(nil, 0, 0, Number(ms))\n }\n module.exports = sleep\n} else {\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n const target = Date.now() + Number(ms)\n while (target > Date.now()){}\n }\n\n module.exports = sleep\n\n}\n","var aws4 = exports,\n url = require('url'),\n querystring = require('querystring'),\n crypto = require('crypto'),\n lru = require('./lru'),\n credentialsCache = lru(1000)\n\n// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html\n\nfunction hmac(key, string, encoding) {\n return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)\n}\n\nfunction hash(string, encoding) {\n return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)\n}\n\n// This function assumes the string has already been percent encoded\nfunction encodeRfc3986(urlEncodedString) {\n return urlEncodedString.replace(/[!'()*]/g, function(c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\nfunction encodeRfc3986Full(str) {\n return encodeRfc3986(encodeURIComponent(str))\n}\n\n// request: { path | body, [host], [method], [headers], [service], [region] }\n// credentials: { accessKeyId, secretAccessKey, [sessionToken] }\nfunction RequestSigner(request, credentials) {\n\n if (typeof request === 'string') request = url.parse(request)\n\n var headers = request.headers = (request.headers || {}),\n hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host)\n\n this.request = request\n this.credentials = credentials || this.defaultCredentials()\n\n this.service = request.service || hostParts[0] || ''\n this.region = request.region || hostParts[1] || 'us-east-1'\n\n // SES uses a different domain from the service name\n if (this.service === 'email') this.service = 'ses'\n\n if (!request.method && request.body)\n request.method = 'POST'\n\n if (!headers.Host && !headers.host) {\n headers.Host = request.hostname || request.host || this.createHost()\n\n // If a port is specified explicitly, use it as is\n if (request.port)\n headers.Host += ':' + request.port\n }\n if (!request.hostname && !request.host)\n request.hostname = headers.Host || headers.host\n\n this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'\n}\n\nRequestSigner.prototype.matchHost = function(host) {\n var match = (host || '').match(/([^\\.]+)\\.(?:([^\\.]*)\\.)?amazonaws\\.com(\\.cn)?$/)\n var hostParts = (match || []).slice(1, 3)\n\n // ES's hostParts are sometimes the other way round, if the value that is expected\n // to be region equals ‘es’ switch them back\n // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com\n if (hostParts[1] === 'es')\n hostParts = hostParts.reverse()\n\n if (hostParts[1] == 's3') {\n hostParts[0] = 's3'\n hostParts[1] = 'us-east-1'\n } else {\n for (var i = 0; i < 2; i++) {\n if (/^s3-/.test(hostParts[i])) {\n hostParts[1] = hostParts[i].slice(3)\n hostParts[0] = 's3'\n break\n }\n }\n }\n\n return hostParts\n}\n\n// http://docs.aws.amazon.com/general/latest/gr/rande.html\nRequestSigner.prototype.isSingleRegion = function() {\n // Special case for S3 and SimpleDB in us-east-1\n if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true\n\n return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']\n .indexOf(this.service) >= 0\n}\n\nRequestSigner.prototype.createHost = function() {\n var region = this.isSingleRegion() ? '' : '.' + this.region,\n subdomain = this.service === 'ses' ? 'email' : this.service\n return subdomain + region + '.amazonaws.com'\n}\n\nRequestSigner.prototype.prepareRequest = function() {\n this.parsePath()\n\n var request = this.request, headers = request.headers, query\n\n if (request.signQuery) {\n\n this.parsedPath.query = query = this.parsedPath.query || {}\n\n if (this.credentials.sessionToken)\n query['X-Amz-Security-Token'] = this.credentials.sessionToken\n\n if (this.service === 's3' && !query['X-Amz-Expires'])\n query['X-Amz-Expires'] = 86400\n\n if (query['X-Amz-Date'])\n this.datetime = query['X-Amz-Date']\n else\n query['X-Amz-Date'] = this.getDateTime()\n\n query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'\n query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()\n query['X-Amz-SignedHeaders'] = this.signedHeaders()\n\n } else {\n\n if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {\n if (request.body && !headers['Content-Type'] && !headers['content-type'])\n headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'\n\n if (request.body && !headers['Content-Length'] && !headers['content-length'])\n headers['Content-Length'] = Buffer.byteLength(request.body)\n\n if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])\n headers['X-Amz-Security-Token'] = this.credentials.sessionToken\n\n if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])\n headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')\n\n if (headers['X-Amz-Date'] || headers['x-amz-date'])\n this.datetime = headers['X-Amz-Date'] || headers['x-amz-date']\n else\n headers['X-Amz-Date'] = this.getDateTime()\n }\n\n delete headers.Authorization\n delete headers.authorization\n }\n}\n\nRequestSigner.prototype.sign = function() {\n if (!this.parsedPath) this.prepareRequest()\n\n if (this.request.signQuery) {\n this.parsedPath.query['X-Amz-Signature'] = this.signature()\n } else {\n this.request.headers.Authorization = this.authHeader()\n }\n\n this.request.path = this.formatPath()\n\n return this.request\n}\n\nRequestSigner.prototype.getDateTime = function() {\n if (!this.datetime) {\n var headers = this.request.headers,\n date = new Date(headers.Date || headers.date || new Date)\n\n this.datetime = date.toISOString().replace(/[:\\-]|\\.\\d{3}/g, '')\n\n // Remove the trailing 'Z' on the timestamp string for CodeCommit git access\n if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1)\n }\n return this.datetime\n}\n\nRequestSigner.prototype.getDate = function() {\n return this.getDateTime().substr(0, 8)\n}\n\nRequestSigner.prototype.authHeader = function() {\n return [\n 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),\n 'SignedHeaders=' + this.signedHeaders(),\n 'Signature=' + this.signature(),\n ].join(', ')\n}\n\nRequestSigner.prototype.signature = function() {\n var date = this.getDate(),\n cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),\n kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)\n if (!kCredentials) {\n kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)\n kRegion = hmac(kDate, this.region)\n kService = hmac(kRegion, this.service)\n kCredentials = hmac(kService, 'aws4_request')\n credentialsCache.set(cacheKey, kCredentials)\n }\n return hmac(kCredentials, this.stringToSign(), 'hex')\n}\n\nRequestSigner.prototype.stringToSign = function() {\n return [\n 'AWS4-HMAC-SHA256',\n this.getDateTime(),\n this.credentialString(),\n hash(this.canonicalString(), 'hex'),\n ].join('\\n')\n}\n\nRequestSigner.prototype.canonicalString = function() {\n if (!this.parsedPath) this.prepareRequest()\n\n var pathStr = this.parsedPath.path,\n query = this.parsedPath.query,\n headers = this.request.headers,\n queryStr = '',\n normalizePath = this.service !== 's3',\n decodePath = this.service === 's3' || this.request.doNotEncodePath,\n decodeSlashesInPath = this.service === 's3',\n firstValOnly = this.service === 's3',\n bodyHash\n\n if (this.service === 's3' && this.request.signQuery) {\n bodyHash = 'UNSIGNED-PAYLOAD'\n } else if (this.isCodeCommitGit) {\n bodyHash = ''\n } else {\n bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||\n hash(this.request.body || '', 'hex')\n }\n\n if (query) {\n var reducedQuery = Object.keys(query).reduce(function(obj, key) {\n if (!key) return obj\n obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] :\n (firstValOnly ? query[key][0] : query[key])\n return obj\n }, {})\n var encodedQueryPieces = []\n Object.keys(reducedQuery).sort().forEach(function(key) {\n if (!Array.isArray(reducedQuery[key])) {\n encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key]))\n } else {\n reducedQuery[key].map(encodeRfc3986Full).sort()\n .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) })\n }\n })\n queryStr = encodedQueryPieces.join('&')\n }\n if (pathStr !== '/') {\n if (normalizePath) pathStr = pathStr.replace(/\\/{2,}/g, '/')\n pathStr = pathStr.split('/').reduce(function(path, piece) {\n if (normalizePath && piece === '..') {\n path.pop()\n } else if (!normalizePath || piece !== '.') {\n if (decodePath) piece = decodeURIComponent(piece.replace(/\\+/g, ' '))\n path.push(encodeRfc3986Full(piece))\n }\n return path\n }, []).join('/')\n if (pathStr[0] !== '/') pathStr = '/' + pathStr\n if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')\n }\n\n return [\n this.request.method || 'GET',\n pathStr,\n queryStr,\n this.canonicalHeaders() + '\\n',\n this.signedHeaders(),\n bodyHash,\n ].join('\\n')\n}\n\nRequestSigner.prototype.canonicalHeaders = function() {\n var headers = this.request.headers\n function trimAll(header) {\n return header.toString().trim().replace(/\\s+/g, ' ')\n }\n return Object.keys(headers)\n .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })\n .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })\n .join('\\n')\n}\n\nRequestSigner.prototype.signedHeaders = function() {\n return Object.keys(this.request.headers)\n .map(function(key) { return key.toLowerCase() })\n .sort()\n .join(';')\n}\n\nRequestSigner.prototype.credentialString = function() {\n return [\n this.getDate(),\n this.region,\n this.service,\n 'aws4_request',\n ].join('/')\n}\n\nRequestSigner.prototype.defaultCredentials = function() {\n var env = process.env\n return {\n accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,\n secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,\n sessionToken: env.AWS_SESSION_TOKEN,\n }\n}\n\nRequestSigner.prototype.parsePath = function() {\n var path = this.request.path || '/'\n\n // S3 doesn't always encode characters > 127 correctly and\n // all services don't encode characters > 255 correctly\n // So if there are non-reserved chars (and it's not already all % encoded), just encode them all\n if (/[^0-9A-Za-z;,/?:@&=+$\\-_.!~*'()#%]/.test(path)) {\n path = encodeURI(decodeURI(path))\n }\n\n var queryIx = path.indexOf('?'),\n query = null\n\n if (queryIx >= 0) {\n query = querystring.parse(path.slice(queryIx + 1))\n path = path.slice(0, queryIx)\n }\n\n this.parsedPath = {\n path: path,\n query: query,\n }\n}\n\nRequestSigner.prototype.formatPath = function() {\n var path = this.parsedPath.path,\n query = this.parsedPath.query\n\n if (!query) return path\n\n // Services don't support empty query string keys\n if (query[''] != null) delete query['']\n\n return path + '?' + encodeRfc3986(querystring.stringify(query))\n}\n\naws4.RequestSigner = RequestSigner\n\naws4.sign = function(request, credentials) {\n return new RequestSigner(request, credentials).sign()\n}\n","module.exports = function(size) {\n return new LruCache(size)\n}\n\nfunction LruCache(size) {\n this.capacity = size | 0\n this.map = Object.create(null)\n this.list = new DoublyLinkedList()\n}\n\nLruCache.prototype.get = function(key) {\n var node = this.map[key]\n if (node == null) return undefined\n this.used(node)\n return node.val\n}\n\nLruCache.prototype.set = function(key, val) {\n var node = this.map[key]\n if (node != null) {\n node.val = val\n } else {\n if (!this.capacity) this.prune()\n if (!this.capacity) return false\n node = new DoublyLinkedNode(key, val)\n this.map[key] = node\n this.capacity--\n }\n this.used(node)\n return true\n}\n\nLruCache.prototype.used = function(node) {\n this.list.moveToFront(node)\n}\n\nLruCache.prototype.prune = function() {\n var node = this.list.pop()\n if (node != null) {\n delete this.map[node.key]\n this.capacity++\n }\n}\n\n\nfunction DoublyLinkedList() {\n this.firstNode = null\n this.lastNode = null\n}\n\nDoublyLinkedList.prototype.moveToFront = function(node) {\n if (this.firstNode == node) return\n\n this.remove(node)\n\n if (this.firstNode == null) {\n this.firstNode = node\n this.lastNode = node\n node.prev = null\n node.next = null\n } else {\n node.prev = null\n node.next = this.firstNode\n node.next.prev = node\n this.firstNode = node\n }\n}\n\nDoublyLinkedList.prototype.pop = function() {\n var lastNode = this.lastNode\n if (lastNode != null) {\n this.remove(lastNode)\n }\n return lastNode\n}\n\nDoublyLinkedList.prototype.remove = function(node) {\n if (this.firstNode == node) {\n this.firstNode = node.next\n } else if (node.prev != null) {\n node.prev.next = node.next\n }\n if (this.lastNode == node) {\n this.lastNode = node.prev\n } else if (node.next != null) {\n node.next.prev = node.prev\n }\n}\n\n\nfunction DoublyLinkedNode(key, val) {\n this.key = key\n this.val = val\n this.prev = null\n this.next = null\n}\n","var register = require('./lib/register')\nvar addHook = require('./lib/add')\nvar removeHook = require('./lib/remove')\n\n// bind with array of arguments: https://stackoverflow.com/a/21792913\nvar bind = Function.bind\nvar bindable = bind.bind(bind)\n\nfunction bindApi (hook, state, name) {\n var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state])\n hook.api = { remove: removeHookRef }\n hook.remove = removeHookRef\n\n ;['before', 'error', 'after', 'wrap'].forEach(function (kind) {\n var args = name ? [state, kind, name] : [state, kind]\n hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args)\n })\n}\n\nfunction HookSingular () {\n var singularHookName = 'h'\n var singularHookState = {\n registry: {}\n }\n var singularHook = register.bind(null, singularHookState, singularHookName)\n bindApi(singularHook, singularHookState, singularHookName)\n return singularHook\n}\n\nfunction HookCollection () {\n var state = {\n registry: {}\n }\n\n var hook = register.bind(null, state)\n bindApi(hook, state)\n\n return hook\n}\n\nvar collectionHookDeprecationMessageDisplayed = false\nfunction Hook () {\n if (!collectionHookDeprecationMessageDisplayed) {\n console.warn('[before-after-hook]: \"Hook()\" repurposing warning, use \"Hook.Collection()\". Read more: https://git.io/upgrade-before-after-hook-to-1.4')\n collectionHookDeprecationMessageDisplayed = true\n }\n return HookCollection()\n}\n\nHook.Singular = HookSingular.bind()\nHook.Collection = HookCollection.bind()\n\nmodule.exports = Hook\n// expose constructors as a named property for TypeScript\nmodule.exports.Hook = Hook\nmodule.exports.Singular = Hook.Singular\nmodule.exports.Collection = Hook.Collection\n","module.exports = addHook\n\nfunction addHook (state, kind, name, hook) {\n var orig = hook\n if (!state.registry[name]) {\n state.registry[name] = []\n }\n\n if (kind === 'before') {\n hook = function (method, options) {\n return Promise.resolve()\n .then(orig.bind(null, options))\n .then(method.bind(null, options))\n }\n }\n\n if (kind === 'after') {\n hook = function (method, options) {\n var result\n return Promise.resolve()\n .then(method.bind(null, options))\n .then(function (result_) {\n result = result_\n return orig(result, options)\n })\n .then(function () {\n return result\n })\n }\n }\n\n if (kind === 'error') {\n hook = function (method, options) {\n return Promise.resolve()\n .then(method.bind(null, options))\n .catch(function (error) {\n return orig(error, options)\n })\n }\n }\n\n state.registry[name].push({\n hook: hook,\n orig: orig\n })\n}\n","module.exports = register\n\nfunction register (state, name, method, options) {\n if (typeof method !== 'function') {\n throw new Error('method for before hook must be a function')\n }\n\n if (!options) {\n options = {}\n }\n\n if (Array.isArray(name)) {\n return name.reverse().reduce(function (callback, name) {\n return register.bind(null, state, name, callback, options)\n }, method)()\n }\n\n return Promise.resolve()\n .then(function () {\n if (!state.registry[name]) {\n return method(options)\n }\n\n return (state.registry[name]).reduce(function (method, registered) {\n return registered.hook.bind(null, method, options)\n }, method)()\n })\n}\n","module.exports = removeHook\n\nfunction removeHook (state, name, method) {\n if (!state.registry[name]) {\n return\n }\n\n var index = state.registry[name]\n .map(function (registered) { return registered.orig })\n .indexOf(method)\n\n if (index === -1) {\n return\n }\n\n state.registry[name].splice(index, 1)\n}\n","'use strict'\nvar DuplexStream = require('readable-stream').Duplex\n , util = require('util')\n , Buffer = require('safe-buffer').Buffer\n\nfunction BufferList (callback) {\n if (!(this instanceof BufferList))\n return new BufferList(callback)\n\n this._bufs = []\n this.length = 0\n\n if (typeof callback == 'function') {\n this._callback = callback\n\n var piper = function piper (err) {\n if (this._callback) {\n this._callback(err)\n this._callback = null\n }\n }.bind(this)\n\n this.on('pipe', function onPipe (src) {\n src.on('error', piper)\n })\n this.on('unpipe', function onUnpipe (src) {\n src.removeListener('error', piper)\n })\n } else {\n this.append(callback)\n }\n\n DuplexStream.call(this)\n}\n\n\nutil.inherits(BufferList, DuplexStream)\n\n\nBufferList.prototype._offset = function _offset (offset) {\n var tot = 0, i = 0, _t\n if (offset === 0) return [ 0, 0 ]\n for (; i < this._bufs.length; i++) {\n _t = tot + this._bufs[i].length\n if (offset < _t || i == this._bufs.length - 1) {\n return [ i, offset - tot ]\n }\n tot = _t\n }\n}\n\nBufferList.prototype._reverseOffset = function (blOffset) {\n var bufferId = blOffset[0]\n var offset = blOffset[1]\n for (var i = 0; i < bufferId; i++) {\n offset += this._bufs[i].length\n }\n return offset\n}\n\nBufferList.prototype.append = function append (buf) {\n var i = 0\n\n if (Buffer.isBuffer(buf)) {\n this._appendBuffer(buf)\n } else if (Array.isArray(buf)) {\n for (; i < buf.length; i++)\n this.append(buf[i])\n } else if (buf instanceof BufferList) {\n // unwrap argument into individual BufferLists\n for (; i < buf._bufs.length; i++)\n this.append(buf._bufs[i])\n } else if (buf != null) {\n // coerce number arguments to strings, since Buffer(number) does\n // uninitialized memory allocation\n if (typeof buf == 'number')\n buf = buf.toString()\n\n this._appendBuffer(Buffer.from(buf))\n }\n\n return this\n}\n\n\nBufferList.prototype._appendBuffer = function appendBuffer (buf) {\n this._bufs.push(buf)\n this.length += buf.length\n}\n\n\nBufferList.prototype._write = function _write (buf, encoding, callback) {\n this._appendBuffer(buf)\n\n if (typeof callback == 'function')\n callback()\n}\n\n\nBufferList.prototype._read = function _read (size) {\n if (!this.length)\n return this.push(null)\n\n size = Math.min(size, this.length)\n this.push(this.slice(0, size))\n this.consume(size)\n}\n\n\nBufferList.prototype.end = function end (chunk) {\n DuplexStream.prototype.end.call(this, chunk)\n\n if (this._callback) {\n this._callback(null, this.slice())\n this._callback = null\n }\n}\n\n\nBufferList.prototype.get = function get (index) {\n if (index > this.length || index < 0) {\n return undefined\n }\n var offset = this._offset(index)\n return this._bufs[offset[0]][offset[1]]\n}\n\n\nBufferList.prototype.slice = function slice (start, end) {\n if (typeof start == 'number' && start < 0)\n start += this.length\n if (typeof end == 'number' && end < 0)\n end += this.length\n return this.copy(null, 0, start, end)\n}\n\n\nBufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {\n if (typeof srcStart != 'number' || srcStart < 0)\n srcStart = 0\n if (typeof srcEnd != 'number' || srcEnd > this.length)\n srcEnd = this.length\n if (srcStart >= this.length)\n return dst || Buffer.alloc(0)\n if (srcEnd <= 0)\n return dst || Buffer.alloc(0)\n\n var copy = !!dst\n , off = this._offset(srcStart)\n , len = srcEnd - srcStart\n , bytes = len\n , bufoff = (copy && dstStart) || 0\n , start = off[1]\n , l\n , i\n\n // copy/slice everything\n if (srcStart === 0 && srcEnd == this.length) {\n if (!copy) { // slice, but full concat if multiple buffers\n return this._bufs.length === 1\n ? this._bufs[0]\n : Buffer.concat(this._bufs, this.length)\n }\n\n // copy, need to copy individual buffers\n for (i = 0; i < this._bufs.length; i++) {\n this._bufs[i].copy(dst, bufoff)\n bufoff += this._bufs[i].length\n }\n\n return dst\n }\n\n // easy, cheap case where it's a subset of one of the buffers\n if (bytes <= this._bufs[off[0]].length - start) {\n return copy\n ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)\n : this._bufs[off[0]].slice(start, start + bytes)\n }\n\n if (!copy) // a slice, we need something to copy in to\n dst = Buffer.allocUnsafe(len)\n\n for (i = off[0]; i < this._bufs.length; i++) {\n l = this._bufs[i].length - start\n\n if (bytes > l) {\n this._bufs[i].copy(dst, bufoff, start)\n bufoff += l\n } else {\n this._bufs[i].copy(dst, bufoff, start, start + bytes)\n bufoff += l\n break\n }\n\n bytes -= l\n\n if (start)\n start = 0\n }\n\n // safeguard so that we don't return uninitialized memory\n if (dst.length > bufoff) return dst.slice(0, bufoff)\n\n return dst\n}\n\nBufferList.prototype.shallowSlice = function shallowSlice (start, end) {\n start = start || 0\n end = typeof end !== 'number' ? this.length : end\n\n if (start < 0)\n start += this.length\n if (end < 0)\n end += this.length\n\n if (start === end) {\n return new BufferList()\n }\n var startOffset = this._offset(start)\n , endOffset = this._offset(end)\n , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)\n\n if (endOffset[1] == 0)\n buffers.pop()\n else\n buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1])\n\n if (startOffset[1] != 0)\n buffers[0] = buffers[0].slice(startOffset[1])\n\n return new BufferList(buffers)\n}\n\nBufferList.prototype.toString = function toString (encoding, start, end) {\n return this.slice(start, end).toString(encoding)\n}\n\nBufferList.prototype.consume = function consume (bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) return this\n\n while (this._bufs.length) {\n if (bytes >= this._bufs[0].length) {\n bytes -= this._bufs[0].length\n this.length -= this._bufs[0].length\n this._bufs.shift()\n } else {\n this._bufs[0] = this._bufs[0].slice(bytes)\n this.length -= bytes\n break\n }\n }\n return this\n}\n\n\nBufferList.prototype.duplicate = function duplicate () {\n var i = 0\n , copy = new BufferList()\n\n for (; i < this._bufs.length; i++)\n copy.append(this._bufs[i])\n\n return copy\n}\n\n\nBufferList.prototype.destroy = function destroy () {\n this._bufs.length = 0\n this.length = 0\n this.push(null)\n}\n\n\nBufferList.prototype.indexOf = function (search, offset, encoding) {\n if (encoding === undefined && typeof offset === 'string') {\n encoding = offset\n offset = undefined\n }\n if (typeof search === 'function' || Array.isArray(search)) {\n throw new TypeError('The \"value\" argument must be one of type string, Buffer, BufferList, or Uint8Array.')\n } else if (typeof search === 'number') {\n search = Buffer.from([search])\n } else if (typeof search === 'string') {\n search = Buffer.from(search, encoding)\n } else if (search instanceof BufferList) {\n search = search.slice()\n } else if (!Buffer.isBuffer(search)) {\n search = Buffer.from(search)\n }\n\n offset = Number(offset || 0)\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n var blOffset = this._offset(offset)\n var blIndex = blOffset[0] // index of which internal buffer we're working on\n var buffOffset = blOffset[1] // offset of the internal buffer we're working on\n\n // scan over each buffer\n for (blIndex; blIndex < this._bufs.length; blIndex++) {\n var buff = this._bufs[blIndex]\n while(buffOffset < buff.length) {\n var availableWindow = buff.length - buffOffset\n if (availableWindow >= search.length) {\n var nativeSearchResult = buff.indexOf(search, buffOffset)\n if (nativeSearchResult !== -1) {\n return this._reverseOffset([blIndex, nativeSearchResult])\n }\n buffOffset = buff.length - search.length + 1 // end of native search window\n } else {\n var revOffset = this._reverseOffset([blIndex, buffOffset])\n if (this._match(revOffset, search)) {\n return revOffset\n }\n buffOffset++\n }\n }\n buffOffset = 0\n }\n return -1\n}\n\nBufferList.prototype._match = function(offset, search) {\n if (this.length - offset < search.length) {\n return false\n }\n for (var searchOffset = 0; searchOffset < search.length ; searchOffset++) {\n if(this.get(offset + searchOffset) !== search[searchOffset]){\n return false\n }\n }\n return true\n}\n\n\n;(function () {\n var methods = {\n 'readDoubleBE' : 8\n , 'readDoubleLE' : 8\n , 'readFloatBE' : 4\n , 'readFloatLE' : 4\n , 'readInt32BE' : 4\n , 'readInt32LE' : 4\n , 'readUInt32BE' : 4\n , 'readUInt32LE' : 4\n , 'readInt16BE' : 2\n , 'readInt16LE' : 2\n , 'readUInt16BE' : 2\n , 'readUInt16LE' : 2\n , 'readInt8' : 1\n , 'readUInt8' : 1\n , 'readIntBE' : null\n , 'readIntLE' : null\n , 'readUIntBE' : null\n , 'readUIntLE' : null\n }\n\n for (var m in methods) {\n (function (m) {\n if (methods[m] === null) {\n BufferList.prototype[m] = function (offset, byteLength) {\n return this.slice(offset, offset + byteLength)[m](0, byteLength)\n }\n }\n else {\n BufferList.prototype[m] = function (offset) {\n return this.slice(offset, offset + methods[m])[m](0)\n }\n }\n }(m))\n }\n}())\n\n\nmodule.exports = BufferList\n","var BSON = require('./lib/bson/bson'),\n Binary = require('./lib/bson/binary'),\n Code = require('./lib/bson/code'),\n DBRef = require('./lib/bson/db_ref'),\n Decimal128 = require('./lib/bson/decimal128'),\n Double = require('./lib/bson/double'),\n Int32 = require('./lib/bson/int_32'),\n Long = require('./lib/bson/long'),\n Map = require('./lib/bson/map'),\n MaxKey = require('./lib/bson/max_key'),\n MinKey = require('./lib/bson/min_key'),\n ObjectId = require('./lib/bson/objectid'),\n BSONRegExp = require('./lib/bson/regexp'),\n Symbol = require('./lib/bson/symbol'),\n Timestamp = require('./lib/bson/timestamp');\n\n// BSON MAX VALUES\nBSON.BSON_INT32_MAX = 0x7fffffff;\nBSON.BSON_INT32_MIN = -0x80000000;\n\nBSON.BSON_INT64_MAX = Math.pow(2, 63) - 1;\nBSON.BSON_INT64_MIN = -Math.pow(2, 63);\n\n// JS MAX PRECISE VALUES\nBSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.\nBSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.\n\n// Add BSON types to function creation\nBSON.Binary = Binary;\nBSON.Code = Code;\nBSON.DBRef = DBRef;\nBSON.Decimal128 = Decimal128;\nBSON.Double = Double;\nBSON.Int32 = Int32;\nBSON.Long = Long;\nBSON.Map = Map;\nBSON.MaxKey = MaxKey;\nBSON.MinKey = MinKey;\nBSON.ObjectId = ObjectId;\nBSON.ObjectID = ObjectId;\nBSON.BSONRegExp = BSONRegExp;\nBSON.Symbol = Symbol;\nBSON.Timestamp = Timestamp;\n\n// Return the BSON\nmodule.exports = BSON;\n","/**\n * Module dependencies.\n * @ignore\n */\n\n// Test if we're in Node via presence of \"global\" not absence of \"window\"\n// to support hybrid environments like Electron\nif (typeof global !== 'undefined') {\n var Buffer = require('buffer').Buffer; // TODO just use global Buffer\n}\n\nvar utils = require('./parser/utils');\n\n/**\n * A class representation of the BSON Binary type.\n *\n * Sub types\n * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type.\n * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type.\n * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type.\n * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type.\n * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type.\n * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type.\n *\n * @class\n * @param {Buffer} buffer a buffer object containing the binary data.\n * @param {Number} [subType] the option binary type.\n * @return {Binary}\n */\nfunction Binary(buffer, subType) {\n if (!(this instanceof Binary)) return new Binary(buffer, subType);\n\n if (\n buffer != null &&\n !(typeof buffer === 'string') &&\n !Buffer.isBuffer(buffer) &&\n !(buffer instanceof Uint8Array) &&\n !Array.isArray(buffer)\n ) {\n throw new Error('only String, Buffer, Uint8Array or Array accepted');\n }\n\n this._bsontype = 'Binary';\n\n if (buffer instanceof Number) {\n this.sub_type = buffer;\n this.position = 0;\n } else {\n this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType;\n this.position = 0;\n }\n\n if (buffer != null && !(buffer instanceof Number)) {\n // Only accept Buffer, Uint8Array or Arrays\n if (typeof buffer === 'string') {\n // Different ways of writing the length of the string for the different types\n if (typeof Buffer !== 'undefined') {\n this.buffer = utils.toBuffer(buffer);\n } else if (\n typeof Uint8Array !== 'undefined' ||\n Object.prototype.toString.call(buffer) === '[object Array]'\n ) {\n this.buffer = writeStringToArray(buffer);\n } else {\n throw new Error('only String, Buffer, Uint8Array or Array accepted');\n }\n } else {\n this.buffer = buffer;\n }\n this.position = buffer.length;\n } else {\n if (typeof Buffer !== 'undefined') {\n this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE);\n } else if (typeof Uint8Array !== 'undefined') {\n this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE));\n } else {\n this.buffer = new Array(Binary.BUFFER_SIZE);\n }\n // Set position to start of buffer\n this.position = 0;\n }\n}\n\n/**\n * Updates this binary with byte_value.\n *\n * @method\n * @param {string} byte_value a single byte we wish to write.\n */\nBinary.prototype.put = function put(byte_value) {\n // If it's a string and a has more than one character throw an error\n if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1)\n throw new Error('only accepts single character String, Uint8Array or Array');\n if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255)\n throw new Error('only accepts number in a valid unsigned byte range 0-255');\n\n // Decode the byte value once\n var decoded_byte = null;\n if (typeof byte_value === 'string') {\n decoded_byte = byte_value.charCodeAt(0);\n } else if (byte_value['length'] != null) {\n decoded_byte = byte_value[0];\n } else {\n decoded_byte = byte_value;\n }\n\n if (this.buffer.length > this.position) {\n this.buffer[this.position++] = decoded_byte;\n } else {\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {\n // Create additional overflow buffer\n var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length);\n // Combine the two buffers together\n this.buffer.copy(buffer, 0, 0, this.buffer.length);\n this.buffer = buffer;\n this.buffer[this.position++] = decoded_byte;\n } else {\n buffer = null;\n // Create a new buffer (typed or normal array)\n if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') {\n buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length));\n } else {\n buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length);\n }\n\n // We need to copy all the content to the new array\n for (var i = 0; i < this.buffer.length; i++) {\n buffer[i] = this.buffer[i];\n }\n\n // Reassign the buffer\n this.buffer = buffer;\n // Write the byte\n this.buffer[this.position++] = decoded_byte;\n }\n }\n};\n\n/**\n * Writes a buffer or string to the binary.\n *\n * @method\n * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object.\n * @param {number} offset specify the binary of where to write the content.\n * @return {null}\n */\nBinary.prototype.write = function write(string, offset) {\n offset = typeof offset === 'number' ? offset : this.position;\n\n // If the buffer is to small let's extend the buffer\n if (this.buffer.length < offset + string.length) {\n var buffer = null;\n // If we are in node.js\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {\n buffer = utils.allocBuffer(this.buffer.length + string.length);\n this.buffer.copy(buffer, 0, 0, this.buffer.length);\n } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') {\n // Create a new buffer\n buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length));\n // Copy the content\n for (var i = 0; i < this.position; i++) {\n buffer[i] = this.buffer[i];\n }\n }\n\n // Assign the new buffer\n this.buffer = buffer;\n }\n\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) {\n string.copy(this.buffer, offset, 0, string.length);\n this.position = offset + string.length > this.position ? offset + string.length : this.position;\n // offset = string.length\n } else if (\n typeof Buffer !== 'undefined' &&\n typeof string === 'string' &&\n Buffer.isBuffer(this.buffer)\n ) {\n this.buffer.write(string, offset, 'binary');\n this.position = offset + string.length > this.position ? offset + string.length : this.position;\n // offset = string.length;\n } else if (\n Object.prototype.toString.call(string) === '[object Uint8Array]' ||\n (Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string')\n ) {\n for (i = 0; i < string.length; i++) {\n this.buffer[offset++] = string[i];\n }\n\n this.position = offset > this.position ? offset : this.position;\n } else if (typeof string === 'string') {\n for (i = 0; i < string.length; i++) {\n this.buffer[offset++] = string.charCodeAt(i);\n }\n\n this.position = offset > this.position ? offset : this.position;\n }\n};\n\n/**\n * Reads **length** bytes starting at **position**.\n *\n * @method\n * @param {number} position read from the given position in the Binary.\n * @param {number} length the number of bytes to read.\n * @return {Buffer}\n */\nBinary.prototype.read = function read(position, length) {\n length = length && length > 0 ? length : this.position;\n\n // Let's return the data based on the type we have\n if (this.buffer['slice']) {\n return this.buffer.slice(position, position + length);\n } else {\n // Create a buffer to keep the result\n var buffer =\n typeof Uint8Array !== 'undefined'\n ? new Uint8Array(new ArrayBuffer(length))\n : new Array(length);\n for (var i = 0; i < length; i++) {\n buffer[i] = this.buffer[position++];\n }\n }\n // Return the buffer\n return buffer;\n};\n\n/**\n * Returns the value of this binary as a string.\n *\n * @method\n * @return {string}\n */\nBinary.prototype.value = function value(asRaw) {\n asRaw = asRaw == null ? false : asRaw;\n\n // Optimize to serialize for the situation where the data == size of buffer\n if (\n asRaw &&\n typeof Buffer !== 'undefined' &&\n Buffer.isBuffer(this.buffer) &&\n this.buffer.length === this.position\n )\n return this.buffer;\n\n // If it's a node.js buffer object\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {\n return asRaw\n ? this.buffer.slice(0, this.position)\n : this.buffer.toString('binary', 0, this.position);\n } else {\n if (asRaw) {\n // we support the slice command use it\n if (this.buffer['slice'] != null) {\n return this.buffer.slice(0, this.position);\n } else {\n // Create a new buffer to copy content to\n var newBuffer =\n Object.prototype.toString.call(this.buffer) === '[object Uint8Array]'\n ? new Uint8Array(new ArrayBuffer(this.position))\n : new Array(this.position);\n // Copy content\n for (var i = 0; i < this.position; i++) {\n newBuffer[i] = this.buffer[i];\n }\n // Return the buffer\n return newBuffer;\n }\n } else {\n return convertArraytoUtf8BinaryString(this.buffer, 0, this.position);\n }\n }\n};\n\n/**\n * Length.\n *\n * @method\n * @return {number} the length of the binary.\n */\nBinary.prototype.length = function length() {\n return this.position;\n};\n\n/**\n * @ignore\n */\nBinary.prototype.toJSON = function() {\n return this.buffer != null ? this.buffer.toString('base64') : '';\n};\n\n/**\n * @ignore\n */\nBinary.prototype.toString = function(format) {\n return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : '';\n};\n\n/**\n * Binary default subtype\n * @ignore\n */\nvar BSON_BINARY_SUBTYPE_DEFAULT = 0;\n\n/**\n * @ignore\n */\nvar writeStringToArray = function(data) {\n // Create a buffer\n var buffer =\n typeof Uint8Array !== 'undefined'\n ? new Uint8Array(new ArrayBuffer(data.length))\n : new Array(data.length);\n // Write the content to the buffer\n for (var i = 0; i < data.length; i++) {\n buffer[i] = data.charCodeAt(i);\n }\n // Write the string to the buffer\n return buffer;\n};\n\n/**\n * Convert Array ot Uint8Array to Binary String\n *\n * @ignore\n */\nvar convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) {\n var result = '';\n for (var i = startIndex; i < endIndex; i++) {\n result = result + String.fromCharCode(byteArray[i]);\n }\n return result;\n};\n\nBinary.BUFFER_SIZE = 256;\n\n/**\n * Default BSON type\n *\n * @classconstant SUBTYPE_DEFAULT\n **/\nBinary.SUBTYPE_DEFAULT = 0;\n/**\n * Function BSON type\n *\n * @classconstant SUBTYPE_DEFAULT\n **/\nBinary.SUBTYPE_FUNCTION = 1;\n/**\n * Byte Array BSON type\n *\n * @classconstant SUBTYPE_DEFAULT\n **/\nBinary.SUBTYPE_BYTE_ARRAY = 2;\n/**\n * OLD UUID BSON type\n *\n * @classconstant SUBTYPE_DEFAULT\n **/\nBinary.SUBTYPE_UUID_OLD = 3;\n/**\n * UUID BSON type\n *\n * @classconstant SUBTYPE_DEFAULT\n **/\nBinary.SUBTYPE_UUID = 4;\n/**\n * MD5 BSON type\n *\n * @classconstant SUBTYPE_DEFAULT\n **/\nBinary.SUBTYPE_MD5 = 5;\n/**\n * User BSON type\n *\n * @classconstant SUBTYPE_DEFAULT\n **/\nBinary.SUBTYPE_USER_DEFINED = 128;\n\n/**\n * Expose.\n */\nmodule.exports = Binary;\nmodule.exports.Binary = Binary;\n","'use strict';\n\nvar Map = require('./map'),\n Long = require('./long'),\n Double = require('./double'),\n Timestamp = require('./timestamp'),\n ObjectID = require('./objectid'),\n BSONRegExp = require('./regexp'),\n Symbol = require('./symbol'),\n Int32 = require('./int_32'),\n Code = require('./code'),\n Decimal128 = require('./decimal128'),\n MinKey = require('./min_key'),\n MaxKey = require('./max_key'),\n DBRef = require('./db_ref'),\n Binary = require('./binary');\n\n// Parts of the parser\nvar deserialize = require('./parser/deserializer'),\n serializer = require('./parser/serializer'),\n calculateObjectSize = require('./parser/calculate_size'),\n utils = require('./parser/utils');\n\n/**\n * @ignore\n * @api private\n */\n// Default Max Size\nvar MAXSIZE = 1024 * 1024 * 17;\n\n// Current Internal Temporary Serialization Buffer\nvar buffer = utils.allocBuffer(MAXSIZE);\n\nvar BSON = function() {};\n\n/**\n * Serialize a Javascript object.\n *\n * @param {Object} object the Javascript object to serialize.\n * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid.\n * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**.\n * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**.\n * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**.\n * @return {Buffer} returns the Buffer object containing the serialized object.\n * @api public\n */\nBSON.prototype.serialize = function serialize(object, options) {\n options = options || {};\n // Unpack the options\n var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;\n var serializeFunctions =\n typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;\n var ignoreUndefined =\n typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;\n var minInternalBufferSize =\n typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;\n \n // Resize the internal serialization buffer if needed\n if (buffer.length < minInternalBufferSize) {\n buffer = utils.allocBuffer(minInternalBufferSize);\n }\n\n // Attempt to serialize\n var serializationIndex = serializer(\n buffer,\n object,\n checkKeys,\n 0,\n 0,\n serializeFunctions,\n ignoreUndefined,\n []\n );\n // Create the final buffer\n var finishedBuffer = utils.allocBuffer(serializationIndex);\n // Copy into the finished buffer\n buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length);\n // Return the buffer\n return finishedBuffer;\n};\n\n/**\n * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.\n *\n * @param {Object} object the Javascript object to serialize.\n * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object.\n * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid.\n * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**.\n * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**.\n * @param {Number} [options.index] the index in the buffer where we wish to start serializing into.\n * @return {Number} returns the index pointing to the last written byte in the buffer.\n * @api public\n */\nBSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) {\n options = options || {};\n // Unpack the options\n var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;\n var serializeFunctions =\n typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;\n var ignoreUndefined =\n typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;\n var startIndex = typeof options.index === 'number' ? options.index : 0;\n\n // Attempt to serialize\n var serializationIndex = serializer(\n finalBuffer,\n object,\n checkKeys,\n startIndex || 0,\n 0,\n serializeFunctions,\n ignoreUndefined\n );\n\n // Return the index\n return serializationIndex - 1;\n};\n\n/**\n * Deserialize data as BSON.\n *\n * @param {Buffer} buffer the buffer containing the serialized set of BSON documents.\n * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized.\n * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse.\n * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function.\n * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits\n * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance.\n * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types.\n * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer.\n * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances.\n * @return {Object} returns the deserialized Javascript Object.\n * @api public\n */\nBSON.prototype.deserialize = function(buffer, options) {\n return deserialize(buffer, options);\n};\n\n/**\n * Calculate the bson size for a passed in Javascript object.\n *\n * @param {Object} object the Javascript object to calculate the BSON byte size for.\n * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**.\n * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**.\n * @return {Number} returns the number of bytes the BSON object will take up.\n * @api public\n */\nBSON.prototype.calculateObjectSize = function(object, options) {\n options = options || {};\n\n var serializeFunctions =\n typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;\n var ignoreUndefined =\n typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;\n\n return calculateObjectSize(object, serializeFunctions, ignoreUndefined);\n};\n\n/**\n * Deserialize stream data as BSON documents.\n *\n * @param {Buffer} data the buffer containing the serialized set of BSON documents.\n * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start.\n * @param {Number} numberOfDocuments number of documents to deserialize.\n * @param {Array} documents an array where to store the deserialized documents.\n * @param {Number} docStartIndex the index in the documents array from where to start inserting documents.\n * @param {Object} [options] additional options used for the deserialization.\n * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized.\n * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse.\n * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function.\n * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits\n * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance.\n * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types.\n * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer.\n * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances.\n * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents.\n * @api public\n */\nBSON.prototype.deserializeStream = function(\n data,\n startIndex,\n numberOfDocuments,\n documents,\n docStartIndex,\n options\n) {\n options = options != null ? options : {};\n var index = startIndex;\n // Loop over all documents\n for (var i = 0; i < numberOfDocuments; i++) {\n // Find size of the document\n var size =\n data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24);\n // Update options with index\n options['index'] = index;\n // Parse the document at this point\n documents[docStartIndex + i] = this.deserialize(data, options);\n // Adjust index by the document size\n index = index + size;\n }\n\n // Return object containing end index of parsing and list of documents\n return index;\n};\n\n/**\n * @ignore\n * @api private\n */\n// BSON MAX VALUES\nBSON.BSON_INT32_MAX = 0x7fffffff;\nBSON.BSON_INT32_MIN = -0x80000000;\n\nBSON.BSON_INT64_MAX = Math.pow(2, 63) - 1;\nBSON.BSON_INT64_MIN = -Math.pow(2, 63);\n\n// JS MAX PRECISE VALUES\nBSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.\nBSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.\n\n// Internal long versions\n// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double.\n// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double.\n\n/**\n * Number BSON Type\n *\n * @classconstant BSON_DATA_NUMBER\n **/\nBSON.BSON_DATA_NUMBER = 1;\n/**\n * String BSON Type\n *\n * @classconstant BSON_DATA_STRING\n **/\nBSON.BSON_DATA_STRING = 2;\n/**\n * Object BSON Type\n *\n * @classconstant BSON_DATA_OBJECT\n **/\nBSON.BSON_DATA_OBJECT = 3;\n/**\n * Array BSON Type\n *\n * @classconstant BSON_DATA_ARRAY\n **/\nBSON.BSON_DATA_ARRAY = 4;\n/**\n * Binary BSON Type\n *\n * @classconstant BSON_DATA_BINARY\n **/\nBSON.BSON_DATA_BINARY = 5;\n/**\n * ObjectID BSON Type\n *\n * @classconstant BSON_DATA_OID\n **/\nBSON.BSON_DATA_OID = 7;\n/**\n * Boolean BSON Type\n *\n * @classconstant BSON_DATA_BOOLEAN\n **/\nBSON.BSON_DATA_BOOLEAN = 8;\n/**\n * Date BSON Type\n *\n * @classconstant BSON_DATA_DATE\n **/\nBSON.BSON_DATA_DATE = 9;\n/**\n * null BSON Type\n *\n * @classconstant BSON_DATA_NULL\n **/\nBSON.BSON_DATA_NULL = 10;\n/**\n * RegExp BSON Type\n *\n * @classconstant BSON_DATA_REGEXP\n **/\nBSON.BSON_DATA_REGEXP = 11;\n/**\n * Code BSON Type\n *\n * @classconstant BSON_DATA_CODE\n **/\nBSON.BSON_DATA_CODE = 13;\n/**\n * Symbol BSON Type\n *\n * @classconstant BSON_DATA_SYMBOL\n **/\nBSON.BSON_DATA_SYMBOL = 14;\n/**\n * Code with Scope BSON Type\n *\n * @classconstant BSON_DATA_CODE_W_SCOPE\n **/\nBSON.BSON_DATA_CODE_W_SCOPE = 15;\n/**\n * 32 bit Integer BSON Type\n *\n * @classconstant BSON_DATA_INT\n **/\nBSON.BSON_DATA_INT = 16;\n/**\n * Timestamp BSON Type\n *\n * @classconstant BSON_DATA_TIMESTAMP\n **/\nBSON.BSON_DATA_TIMESTAMP = 17;\n/**\n * Long BSON Type\n *\n * @classconstant BSON_DATA_LONG\n **/\nBSON.BSON_DATA_LONG = 18;\n/**\n * MinKey BSON Type\n *\n * @classconstant BSON_DATA_MIN_KEY\n **/\nBSON.BSON_DATA_MIN_KEY = 0xff;\n/**\n * MaxKey BSON Type\n *\n * @classconstant BSON_DATA_MAX_KEY\n **/\nBSON.BSON_DATA_MAX_KEY = 0x7f;\n\n/**\n * Binary Default Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_DEFAULT\n **/\nBSON.BSON_BINARY_SUBTYPE_DEFAULT = 0;\n/**\n * Binary Function Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_FUNCTION\n **/\nBSON.BSON_BINARY_SUBTYPE_FUNCTION = 1;\n/**\n * Binary Byte Array Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY\n **/\nBSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;\n/**\n * Binary UUID Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_UUID\n **/\nBSON.BSON_BINARY_SUBTYPE_UUID = 3;\n/**\n * Binary MD5 Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_MD5\n **/\nBSON.BSON_BINARY_SUBTYPE_MD5 = 4;\n/**\n * Binary User Defined Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED\n **/\nBSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;\n\n// Return BSON\nmodule.exports = BSON;\nmodule.exports.Code = Code;\nmodule.exports.Map = Map;\nmodule.exports.Symbol = Symbol;\nmodule.exports.BSON = BSON;\nmodule.exports.DBRef = DBRef;\nmodule.exports.Binary = Binary;\nmodule.exports.ObjectID = ObjectID;\nmodule.exports.Long = Long;\nmodule.exports.Timestamp = Timestamp;\nmodule.exports.Double = Double;\nmodule.exports.Int32 = Int32;\nmodule.exports.MinKey = MinKey;\nmodule.exports.MaxKey = MaxKey;\nmodule.exports.BSONRegExp = BSONRegExp;\nmodule.exports.Decimal128 = Decimal128;\n","/**\n * A class representation of the BSON Code type.\n *\n * @class\n * @param {(string|function)} code a string or function.\n * @param {Object} [scope] an optional scope for the function.\n * @return {Code}\n */\nvar Code = function Code(code, scope) {\n if (!(this instanceof Code)) return new Code(code, scope);\n this._bsontype = 'Code';\n this.code = code;\n this.scope = scope;\n};\n\n/**\n * @ignore\n */\nCode.prototype.toJSON = function() {\n return { scope: this.scope, code: this.code };\n};\n\nmodule.exports = Code;\nmodule.exports.Code = Code;\n","/**\n * A class representation of the BSON DBRef type.\n *\n * @class\n * @param {string} namespace the collection name.\n * @param {ObjectID} oid the reference ObjectID.\n * @param {string} [db] optional db name, if omitted the reference is local to the current db.\n * @return {DBRef}\n */\nfunction DBRef(namespace, oid, db) {\n if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db);\n\n this._bsontype = 'DBRef';\n this.namespace = namespace;\n this.oid = oid;\n this.db = db;\n}\n\n/**\n * @ignore\n * @api private\n */\nDBRef.prototype.toJSON = function() {\n return {\n $ref: this.namespace,\n $id: this.oid,\n $db: this.db == null ? '' : this.db\n };\n};\n\nmodule.exports = DBRef;\nmodule.exports.DBRef = DBRef;\n","'use strict';\n\nvar Long = require('./long');\n\nvar PARSE_STRING_REGEXP = /^(\\+|-)?(\\d+|(\\d*\\.\\d*))?(E|e)?([-+])?(\\d+)?$/;\nvar PARSE_INF_REGEXP = /^(\\+|-)?(Infinity|inf)$/i;\nvar PARSE_NAN_REGEXP = /^(\\+|-)?NaN$/i;\n\nvar EXPONENT_MAX = 6111;\nvar EXPONENT_MIN = -6176;\nvar EXPONENT_BIAS = 6176;\nvar MAX_DIGITS = 34;\n\n// Nan value bits as 32 bit values (due to lack of longs)\nvar NAN_BUFFER = [\n 0x7c,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00\n].reverse();\n// Infinity value bits 32 bit values (due to lack of longs)\nvar INF_NEGATIVE_BUFFER = [\n 0xf8,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00\n].reverse();\nvar INF_POSITIVE_BUFFER = [\n 0x78,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00\n].reverse();\n\nvar EXPONENT_REGEX = /^([-+])?(\\d+)?$/;\n\nvar utils = require('./parser/utils');\n\n// Detect if the value is a digit\nvar isDigit = function(value) {\n return !isNaN(parseInt(value, 10));\n};\n\n// Divide two uint128 values\nvar divideu128 = function(value) {\n var DIVISOR = Long.fromNumber(1000 * 1000 * 1000);\n var _rem = Long.fromNumber(0);\n var i = 0;\n\n if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {\n return { quotient: value, rem: _rem };\n }\n\n for (i = 0; i <= 3; i++) {\n // Adjust remainder to match value of next dividend\n _rem = _rem.shiftLeft(32);\n // Add the divided to _rem\n _rem = _rem.add(new Long(value.parts[i], 0));\n value.parts[i] = _rem.div(DIVISOR).low_;\n _rem = _rem.modulo(DIVISOR);\n }\n\n return { quotient: value, rem: _rem };\n};\n\n// Multiply two Long values and return the 128 bit value\nvar multiply64x2 = function(left, right) {\n if (!left && !right) {\n return { high: Long.fromNumber(0), low: Long.fromNumber(0) };\n }\n\n var leftHigh = left.shiftRightUnsigned(32);\n var leftLow = new Long(left.getLowBits(), 0);\n var rightHigh = right.shiftRightUnsigned(32);\n var rightLow = new Long(right.getLowBits(), 0);\n\n var productHigh = leftHigh.multiply(rightHigh);\n var productMid = leftHigh.multiply(rightLow);\n var productMid2 = leftLow.multiply(rightHigh);\n var productLow = leftLow.multiply(rightLow);\n\n productHigh = productHigh.add(productMid.shiftRightUnsigned(32));\n productMid = new Long(productMid.getLowBits(), 0)\n .add(productMid2)\n .add(productLow.shiftRightUnsigned(32));\n\n productHigh = productHigh.add(productMid.shiftRightUnsigned(32));\n productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));\n\n // Return the 128 bit result\n return { high: productHigh, low: productLow };\n};\n\nvar lessThan = function(left, right) {\n // Make values unsigned\n var uhleft = left.high_ >>> 0;\n var uhright = right.high_ >>> 0;\n\n // Compare high bits first\n if (uhleft < uhright) {\n return true;\n } else if (uhleft === uhright) {\n var ulleft = left.low_ >>> 0;\n var ulright = right.low_ >>> 0;\n if (ulleft < ulright) return true;\n }\n\n return false;\n};\n\n// var longtoHex = function(value) {\n// var buffer = utils.allocBuffer(8);\n// var index = 0;\n// // Encode the low 64 bits of the decimal\n// // Encode low bits\n// buffer[index++] = value.low_ & 0xff;\n// buffer[index++] = (value.low_ >> 8) & 0xff;\n// buffer[index++] = (value.low_ >> 16) & 0xff;\n// buffer[index++] = (value.low_ >> 24) & 0xff;\n// // Encode high bits\n// buffer[index++] = value.high_ & 0xff;\n// buffer[index++] = (value.high_ >> 8) & 0xff;\n// buffer[index++] = (value.high_ >> 16) & 0xff;\n// buffer[index++] = (value.high_ >> 24) & 0xff;\n// return buffer.reverse().toString('hex');\n// };\n\n// var int32toHex = function(value) {\n// var buffer = utils.allocBuffer(4);\n// var index = 0;\n// // Encode the low 64 bits of the decimal\n// // Encode low bits\n// buffer[index++] = value & 0xff;\n// buffer[index++] = (value >> 8) & 0xff;\n// buffer[index++] = (value >> 16) & 0xff;\n// buffer[index++] = (value >> 24) & 0xff;\n// return buffer.reverse().toString('hex');\n// };\n\n/**\n * A class representation of the BSON Decimal128 type.\n *\n * @class\n * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes.\n * @return {Double}\n */\nvar Decimal128 = function(bytes) {\n this._bsontype = 'Decimal128';\n this.bytes = bytes;\n};\n\n/**\n * Create a Decimal128 instance from a string representation\n *\n * @method\n * @param {string} string a numeric string representation.\n * @return {Decimal128} returns a Decimal128 instance.\n */\nDecimal128.fromString = function(string) {\n // Parse state tracking\n var isNegative = false;\n var sawRadix = false;\n var foundNonZero = false;\n\n // Total number of significant digits (no leading or trailing zero)\n var significantDigits = 0;\n // Total number of significand digits read\n var nDigitsRead = 0;\n // Total number of digits (no leading zeros)\n var nDigits = 0;\n // The number of the digits after radix\n var radixPosition = 0;\n // The index of the first non-zero in *str*\n var firstNonZero = 0;\n\n // Digits Array\n var digits = [0];\n // The number of digits in digits\n var nDigitsStored = 0;\n // Insertion pointer for digits\n var digitsInsert = 0;\n // The index of the first non-zero digit\n var firstDigit = 0;\n // The index of the last digit\n var lastDigit = 0;\n\n // Exponent\n var exponent = 0;\n // loop index over array\n var i = 0;\n // The high 17 digits of the significand\n var significandHigh = [0, 0];\n // The low 17 digits of the significand\n var significandLow = [0, 0];\n // The biased exponent\n var biasedExponent = 0;\n\n // Read index\n var index = 0;\n\n // Trim the string\n string = string.trim();\n\n // Naively prevent against REDOS attacks.\n // TODO: implementing a custom parsing for this, or refactoring the regex would yield\n // further gains.\n if (string.length >= 7000) {\n throw new Error('' + string + ' not a valid Decimal128 string');\n }\n\n // Results\n var stringMatch = string.match(PARSE_STRING_REGEXP);\n var infMatch = string.match(PARSE_INF_REGEXP);\n var nanMatch = string.match(PARSE_NAN_REGEXP);\n\n // Validate the string\n if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) {\n throw new Error('' + string + ' not a valid Decimal128 string');\n }\n\n // Check if we have an illegal exponent format\n if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) {\n throw new Error('' + string + ' not a valid Decimal128 string');\n }\n\n // Get the negative or positive sign\n if (string[index] === '+' || string[index] === '-') {\n isNegative = string[index++] === '-';\n }\n\n // Check if user passed Infinity or NaN\n if (!isDigit(string[index]) && string[index] !== '.') {\n if (string[index] === 'i' || string[index] === 'I') {\n return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));\n } else if (string[index] === 'N') {\n return new Decimal128(utils.toBuffer(NAN_BUFFER));\n }\n }\n\n // Read all the digits\n while (isDigit(string[index]) || string[index] === '.') {\n if (string[index] === '.') {\n if (sawRadix) {\n return new Decimal128(utils.toBuffer(NAN_BUFFER));\n }\n\n sawRadix = true;\n index = index + 1;\n continue;\n }\n\n if (nDigitsStored < 34) {\n if (string[index] !== '0' || foundNonZero) {\n if (!foundNonZero) {\n firstNonZero = nDigitsRead;\n }\n\n foundNonZero = true;\n\n // Only store 34 digits\n digits[digitsInsert++] = parseInt(string[index], 10);\n nDigitsStored = nDigitsStored + 1;\n }\n }\n\n if (foundNonZero) {\n nDigits = nDigits + 1;\n }\n\n if (sawRadix) {\n radixPosition = radixPosition + 1;\n }\n\n nDigitsRead = nDigitsRead + 1;\n index = index + 1;\n }\n\n if (sawRadix && !nDigitsRead) {\n throw new Error('' + string + ' not a valid Decimal128 string');\n }\n\n // Read exponent if exists\n if (string[index] === 'e' || string[index] === 'E') {\n // Read exponent digits\n var match = string.substr(++index).match(EXPONENT_REGEX);\n\n // No digits read\n if (!match || !match[2]) {\n return new Decimal128(utils.toBuffer(NAN_BUFFER));\n }\n\n // Get exponent\n exponent = parseInt(match[0], 10);\n\n // Adjust the index\n index = index + match[0].length;\n }\n\n // Return not a number\n if (string[index]) {\n return new Decimal128(utils.toBuffer(NAN_BUFFER));\n }\n\n // Done reading input\n // Find first non-zero digit in digits\n firstDigit = 0;\n\n if (!nDigitsStored) {\n firstDigit = 0;\n lastDigit = 0;\n digits[0] = 0;\n nDigits = 1;\n nDigitsStored = 1;\n significantDigits = 0;\n } else {\n lastDigit = nDigitsStored - 1;\n significantDigits = nDigits;\n\n if (exponent !== 0 && significantDigits !== 1) {\n while (string[firstNonZero + significantDigits - 1] === '0') {\n significantDigits = significantDigits - 1;\n }\n }\n }\n\n // Normalization of exponent\n // Correct exponent based on radix position, and shift significand as needed\n // to represent user input\n\n // Overflow prevention\n if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) {\n exponent = EXPONENT_MIN;\n } else {\n exponent = exponent - radixPosition;\n }\n\n // Attempt to normalize the exponent\n while (exponent > EXPONENT_MAX) {\n // Shift exponent to significand and decrease\n lastDigit = lastDigit + 1;\n\n if (lastDigit - firstDigit > MAX_DIGITS) {\n // Check if we have a zero then just hard clamp, otherwise fail\n var digitsString = digits.join('');\n if (digitsString.match(/^0+$/)) {\n exponent = EXPONENT_MAX;\n break;\n } else {\n return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));\n }\n }\n\n exponent = exponent - 1;\n }\n\n while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {\n // Shift last digit\n if (lastDigit === 0) {\n exponent = EXPONENT_MIN;\n significantDigits = 0;\n break;\n }\n\n if (nDigitsStored < nDigits) {\n // adjust to match digits not stored\n nDigits = nDigits - 1;\n } else {\n // adjust to round\n lastDigit = lastDigit - 1;\n }\n\n if (exponent < EXPONENT_MAX) {\n exponent = exponent + 1;\n } else {\n // Check if we have a zero then just hard clamp, otherwise fail\n digitsString = digits.join('');\n if (digitsString.match(/^0+$/)) {\n exponent = EXPONENT_MAX;\n break;\n } else {\n return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));\n }\n }\n }\n\n // Round\n // We've normalized the exponent, but might still need to round.\n if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') {\n var endOfString = nDigitsRead;\n\n // If we have seen a radix point, 'string' is 1 longer than we have\n // documented with ndigits_read, so inc the position of the first nonzero\n // digit and the position that digits are read to.\n if (sawRadix && exponent === EXPONENT_MIN) {\n firstNonZero = firstNonZero + 1;\n endOfString = endOfString + 1;\n }\n\n var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10);\n var roundBit = 0;\n\n if (roundDigit >= 5) {\n roundBit = 1;\n\n if (roundDigit === 5) {\n roundBit = digits[lastDigit] % 2 === 1;\n\n for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) {\n if (parseInt(string[i], 10)) {\n roundBit = 1;\n break;\n }\n }\n }\n }\n\n if (roundBit) {\n var dIdx = lastDigit;\n\n for (; dIdx >= 0; dIdx--) {\n if (++digits[dIdx] > 9) {\n digits[dIdx] = 0;\n\n // overflowed most significant digit\n if (dIdx === 0) {\n if (exponent < EXPONENT_MAX) {\n exponent = exponent + 1;\n digits[dIdx] = 1;\n } else {\n return new Decimal128(\n utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)\n );\n }\n }\n } else {\n break;\n }\n }\n }\n }\n\n // Encode significand\n // The high 17 digits of the significand\n significandHigh = Long.fromNumber(0);\n // The low 17 digits of the significand\n significandLow = Long.fromNumber(0);\n\n // read a zero\n if (significantDigits === 0) {\n significandHigh = Long.fromNumber(0);\n significandLow = Long.fromNumber(0);\n } else if (lastDigit - firstDigit < 17) {\n dIdx = firstDigit;\n significandLow = Long.fromNumber(digits[dIdx++]);\n significandHigh = new Long(0, 0);\n\n for (; dIdx <= lastDigit; dIdx++) {\n significandLow = significandLow.multiply(Long.fromNumber(10));\n significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));\n }\n } else {\n dIdx = firstDigit;\n significandHigh = Long.fromNumber(digits[dIdx++]);\n\n for (; dIdx <= lastDigit - 17; dIdx++) {\n significandHigh = significandHigh.multiply(Long.fromNumber(10));\n significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));\n }\n\n significandLow = Long.fromNumber(digits[dIdx++]);\n\n for (; dIdx <= lastDigit; dIdx++) {\n significandLow = significandLow.multiply(Long.fromNumber(10));\n significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));\n }\n }\n\n var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));\n\n significand.low = significand.low.add(significandLow);\n\n if (lessThan(significand.low, significandLow)) {\n significand.high = significand.high.add(Long.fromNumber(1));\n }\n\n // Biased exponent\n biasedExponent = exponent + EXPONENT_BIAS;\n var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };\n\n // Encode combination, exponent, and significand.\n if (\n significand.high\n .shiftRightUnsigned(49)\n .and(Long.fromNumber(1))\n .equals(Long.fromNumber)\n ) {\n // Encode '11' into bits 1 to 3\n dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));\n dec.high = dec.high.or(\n Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))\n );\n dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));\n } else {\n dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));\n dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));\n }\n\n dec.low = significand.low;\n\n // Encode sign\n if (isNegative) {\n dec.high = dec.high.or(Long.fromString('9223372036854775808'));\n }\n\n // Encode into a buffer\n var buffer = utils.allocBuffer(16);\n index = 0;\n\n // Encode the low 64 bits of the decimal\n // Encode low bits\n buffer[index++] = dec.low.low_ & 0xff;\n buffer[index++] = (dec.low.low_ >> 8) & 0xff;\n buffer[index++] = (dec.low.low_ >> 16) & 0xff;\n buffer[index++] = (dec.low.low_ >> 24) & 0xff;\n // Encode high bits\n buffer[index++] = dec.low.high_ & 0xff;\n buffer[index++] = (dec.low.high_ >> 8) & 0xff;\n buffer[index++] = (dec.low.high_ >> 16) & 0xff;\n buffer[index++] = (dec.low.high_ >> 24) & 0xff;\n\n // Encode the high 64 bits of the decimal\n // Encode low bits\n buffer[index++] = dec.high.low_ & 0xff;\n buffer[index++] = (dec.high.low_ >> 8) & 0xff;\n buffer[index++] = (dec.high.low_ >> 16) & 0xff;\n buffer[index++] = (dec.high.low_ >> 24) & 0xff;\n // Encode high bits\n buffer[index++] = dec.high.high_ & 0xff;\n buffer[index++] = (dec.high.high_ >> 8) & 0xff;\n buffer[index++] = (dec.high.high_ >> 16) & 0xff;\n buffer[index++] = (dec.high.high_ >> 24) & 0xff;\n\n // Return the new Decimal128\n return new Decimal128(buffer);\n};\n\n// Extract least significant 5 bits\nvar COMBINATION_MASK = 0x1f;\n// Extract least significant 14 bits\nvar EXPONENT_MASK = 0x3fff;\n// Value of combination field for Inf\nvar COMBINATION_INFINITY = 30;\n// Value of combination field for NaN\nvar COMBINATION_NAN = 31;\n// Value of combination field for NaN\n// var COMBINATION_SNAN = 32;\n// decimal128 exponent bias\nEXPONENT_BIAS = 6176;\n\n/**\n * Create a string representation of the raw Decimal128 value\n *\n * @method\n * @return {string} returns a Decimal128 string representation.\n */\nDecimal128.prototype.toString = function() {\n // Note: bits in this routine are referred to starting at 0,\n // from the sign bit, towards the coefficient.\n\n // bits 0 - 31\n var high;\n // bits 32 - 63\n var midh;\n // bits 64 - 95\n var midl;\n // bits 96 - 127\n var low;\n // bits 1 - 5\n var combination;\n // decoded biased exponent (14 bits)\n var biased_exponent;\n // the number of significand digits\n var significand_digits = 0;\n // the base-10 digits in the significand\n var significand = new Array(36);\n for (var i = 0; i < significand.length; i++) significand[i] = 0;\n // read pointer into significand\n var index = 0;\n\n // unbiased exponent\n var exponent;\n // the exponent if scientific notation is used\n var scientific_exponent;\n\n // true if the number is zero\n var is_zero = false;\n\n // the most signifcant significand bits (50-46)\n var significand_msb;\n // temporary storage for significand decoding\n var significand128 = { parts: new Array(4) };\n // indexing variables\n i;\n var j, k;\n\n // Output string\n var string = [];\n\n // Unpack index\n index = 0;\n\n // Buffer reference\n var buffer = this.bytes;\n\n // Unpack the low 64bits into a long\n low =\n buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);\n midl =\n buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);\n\n // Unpack the high 64bits into a long\n midh =\n buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);\n high =\n buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);\n\n // Unpack index\n index = 0;\n\n // Create the state of the decimal\n var dec = {\n low: new Long(low, midl),\n high: new Long(midh, high)\n };\n\n if (dec.high.lessThan(Long.ZERO)) {\n string.push('-');\n }\n\n // Decode combination field and exponent\n combination = (high >> 26) & COMBINATION_MASK;\n\n if (combination >> 3 === 3) {\n // Check for 'special' values\n if (combination === COMBINATION_INFINITY) {\n return string.join('') + 'Infinity';\n } else if (combination === COMBINATION_NAN) {\n return 'NaN';\n } else {\n biased_exponent = (high >> 15) & EXPONENT_MASK;\n significand_msb = 0x08 + ((high >> 14) & 0x01);\n }\n } else {\n significand_msb = (high >> 14) & 0x07;\n biased_exponent = (high >> 17) & EXPONENT_MASK;\n }\n\n exponent = biased_exponent - EXPONENT_BIAS;\n\n // Create string of significand digits\n\n // Convert the 114-bit binary number represented by\n // (significand_high, significand_low) to at most 34 decimal\n // digits through modulo and division.\n significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);\n significand128.parts[1] = midh;\n significand128.parts[2] = midl;\n significand128.parts[3] = low;\n\n if (\n significand128.parts[0] === 0 &&\n significand128.parts[1] === 0 &&\n significand128.parts[2] === 0 &&\n significand128.parts[3] === 0\n ) {\n is_zero = true;\n } else {\n for (k = 3; k >= 0; k--) {\n var least_digits = 0;\n // Peform the divide\n var result = divideu128(significand128);\n significand128 = result.quotient;\n least_digits = result.rem.low_;\n\n // We now have the 9 least significant digits (in base 2).\n // Convert and output to string.\n if (!least_digits) continue;\n\n for (j = 8; j >= 0; j--) {\n // significand[k * 9 + j] = Math.round(least_digits % 10);\n significand[k * 9 + j] = least_digits % 10;\n // least_digits = Math.round(least_digits / 10);\n least_digits = Math.floor(least_digits / 10);\n }\n }\n }\n\n // Output format options:\n // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd\n // Regular - ddd.ddd\n\n if (is_zero) {\n significand_digits = 1;\n significand[index] = 0;\n } else {\n significand_digits = 36;\n i = 0;\n\n while (!significand[index]) {\n i++;\n significand_digits = significand_digits - 1;\n index = index + 1;\n }\n }\n\n scientific_exponent = significand_digits - 1 + exponent;\n\n // The scientific exponent checks are dictated by the string conversion\n // specification and are somewhat arbitrary cutoffs.\n //\n // We must check exponent > 0, because if this is the case, the number\n // has trailing zeros. However, we *cannot* output these trailing zeros,\n // because doing so would change the precision of the value, and would\n // change stored data if the string converted number is round tripped.\n\n if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {\n // Scientific format\n string.push(significand[index++]);\n significand_digits = significand_digits - 1;\n\n if (significand_digits) {\n string.push('.');\n }\n\n for (i = 0; i < significand_digits; i++) {\n string.push(significand[index++]);\n }\n\n // Exponent\n string.push('E');\n if (scientific_exponent > 0) {\n string.push('+' + scientific_exponent);\n } else {\n string.push(scientific_exponent);\n }\n } else {\n // Regular format with no decimal place\n if (exponent >= 0) {\n for (i = 0; i < significand_digits; i++) {\n string.push(significand[index++]);\n }\n } else {\n var radix_position = significand_digits + exponent;\n\n // non-zero digits before radix\n if (radix_position > 0) {\n for (i = 0; i < radix_position; i++) {\n string.push(significand[index++]);\n }\n } else {\n string.push('0');\n }\n\n string.push('.');\n // add leading zeros after radix\n while (radix_position++ < 0) {\n string.push('0');\n }\n\n for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {\n string.push(significand[index++]);\n }\n }\n }\n\n return string.join('');\n};\n\nDecimal128.prototype.toJSON = function() {\n return { $numberDecimal: this.toString() };\n};\n\nmodule.exports = Decimal128;\nmodule.exports.Decimal128 = Decimal128;\n","/**\n * A class representation of the BSON Double type.\n *\n * @class\n * @param {number} value the number we want to represent as a double.\n * @return {Double}\n */\nfunction Double(value) {\n if (!(this instanceof Double)) return new Double(value);\n\n this._bsontype = 'Double';\n this.value = value;\n}\n\n/**\n * Access the number value.\n *\n * @method\n * @return {number} returns the wrapped double number.\n */\nDouble.prototype.valueOf = function() {\n return this.value;\n};\n\n/**\n * @ignore\n */\nDouble.prototype.toJSON = function() {\n return this.value;\n};\n\nmodule.exports = Double;\nmodule.exports.Double = Double;\n","// Copyright (c) 2008, Fair Oaks Labs, Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// * Redistributions of source code must retain the above copyright notice,\n// this list of conditions and the following disclaimer.\n//\n// * Redistributions in binary form must reproduce the above copyright notice,\n// this list of conditions and the following disclaimer in the documentation\n// and/or other materials provided with the distribution.\n//\n// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors\n// may be used to endorse or promote products derived from this software\n// without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n//\n// Modifications to writeIEEE754 to support negative zeroes made by Brian White\n\nvar readIEEE754 = function(buffer, offset, endian, mLen, nBytes) {\n var e,\n m,\n bBE = endian === 'big',\n eLen = nBytes * 8 - mLen - 1,\n eMax = (1 << eLen) - 1,\n eBias = eMax >> 1,\n nBits = -7,\n i = bBE ? 0 : nBytes - 1,\n d = bBE ? 1 : -1,\n s = buffer[offset + i];\n\n i += d;\n\n e = s & ((1 << -nBits) - 1);\n s >>= -nBits;\n nBits += eLen;\n for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);\n\n m = e & ((1 << -nBits) - 1);\n e >>= -nBits;\n nBits += mLen;\n for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);\n\n if (e === 0) {\n e = 1 - eBias;\n } else if (e === eMax) {\n return m ? NaN : (s ? -1 : 1) * Infinity;\n } else {\n m = m + Math.pow(2, mLen);\n e = e - eBias;\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen);\n};\n\nvar writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) {\n var e,\n m,\n c,\n bBE = endian === 'big',\n eLen = nBytes * 8 - mLen - 1,\n eMax = (1 << eLen) - 1,\n eBias = eMax >> 1,\n rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0,\n i = bBE ? nBytes - 1 : 0,\n d = bBE ? -1 : 1,\n s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;\n\n value = Math.abs(value);\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0;\n e = eMax;\n } else {\n e = Math.floor(Math.log(value) / Math.LN2);\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--;\n c *= 2;\n }\n if (e + eBias >= 1) {\n value += rt / c;\n } else {\n value += rt * Math.pow(2, 1 - eBias);\n }\n if (value * c >= 2) {\n e++;\n c /= 2;\n }\n\n if (e + eBias >= eMax) {\n m = 0;\n e = eMax;\n } else if (e + eBias >= 1) {\n m = (value * c - 1) * Math.pow(2, mLen);\n e = e + eBias;\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);\n e = 0;\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);\n\n e = (e << mLen) | m;\n eLen += mLen;\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);\n\n buffer[offset + i - d] |= s * 128;\n};\n\nexports.readIEEE754 = readIEEE754;\nexports.writeIEEE754 = writeIEEE754;\n","/**\n * A class representation of a BSON Int32 type.\n *\n * @class\n * @param {number} value the number we want to represent as an int32.\n * @return {Int32}\n */\nvar Int32 = function(value) {\n if (!(this instanceof Int32)) return new Int32(value);\n\n this._bsontype = 'Int32';\n this.value = value;\n};\n\n/**\n * Access the number value.\n *\n * @method\n * @return {number} returns the wrapped int32 number.\n */\nInt32.prototype.valueOf = function() {\n return this.value;\n};\n\n/**\n * @ignore\n */\nInt32.prototype.toJSON = function() {\n return this.value;\n};\n\nmodule.exports = Int32;\nmodule.exports.Int32 = Int32;\n","// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Copyright 2009 Google Inc. All Rights Reserved\n\n/**\n * Defines a Long class for representing a 64-bit two's-complement\n * integer value, which faithfully simulates the behavior of a Java \"Long\". This\n * implementation is derived from LongLib in GWT.\n *\n * Constructs a 64-bit two's-complement integer, given its low and high 32-bit\n * values as *signed* integers. See the from* functions below for more\n * convenient ways of constructing Longs.\n *\n * The internal representation of a Long is the two given signed, 32-bit values.\n * We use 32-bit pieces because these are the size of integers on which\n * Javascript performs bit-operations. For operations like addition and\n * multiplication, we split each number into 16-bit pieces, which can easily be\n * multiplied within Javascript's floating-point representation without overflow\n * or change in sign.\n *\n * In the algorithms below, we frequently reduce the negative case to the\n * positive case by negating the input(s) and then post-processing the result.\n * Note that we must ALWAYS check specially whether those values are MIN_VALUE\n * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as\n * a positive number, it overflows back into a negative). Not handling this\n * case would often result in infinite recursion.\n *\n * @class\n * @param {number} low the low (signed) 32 bits of the Long.\n * @param {number} high the high (signed) 32 bits of the Long.\n * @return {Long}\n */\nfunction Long(low, high) {\n if (!(this instanceof Long)) return new Long(low, high);\n\n this._bsontype = 'Long';\n /**\n * @type {number}\n * @ignore\n */\n this.low_ = low | 0; // force into 32 signed bits.\n\n /**\n * @type {number}\n * @ignore\n */\n this.high_ = high | 0; // force into 32 signed bits.\n}\n\n/**\n * Return the int value.\n *\n * @method\n * @return {number} the value, assuming it is a 32-bit integer.\n */\nLong.prototype.toInt = function() {\n return this.low_;\n};\n\n/**\n * Return the Number value.\n *\n * @method\n * @return {number} the closest floating-point representation to this value.\n */\nLong.prototype.toNumber = function() {\n return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned();\n};\n\n/**\n * Return the JSON value.\n *\n * @method\n * @return {string} the JSON representation.\n */\nLong.prototype.toJSON = function() {\n return this.toString();\n};\n\n/**\n * Return the String value.\n *\n * @method\n * @param {number} [opt_radix] the radix in which the text should be written.\n * @return {string} the textual representation of this value.\n */\nLong.prototype.toString = function(opt_radix) {\n var radix = opt_radix || 10;\n if (radix < 2 || 36 < radix) {\n throw Error('radix out of range: ' + radix);\n }\n\n if (this.isZero()) {\n return '0';\n }\n\n if (this.isNegative()) {\n if (this.equals(Long.MIN_VALUE)) {\n // We need to change the Long value before it can be negated, so we remove\n // the bottom-most digit in this base and then recurse to do the rest.\n var radixLong = Long.fromNumber(radix);\n var div = this.div(radixLong);\n var rem = div.multiply(radixLong).subtract(this);\n return div.toString(radix) + rem.toInt().toString(radix);\n } else {\n return '-' + this.negate().toString(radix);\n }\n }\n\n // Do several (6) digits each time through the loop, so as to\n // minimize the calls to the very expensive emulated div.\n var radixToPower = Long.fromNumber(Math.pow(radix, 6));\n\n rem = this;\n var result = '';\n\n while (!rem.isZero()) {\n var remDiv = rem.div(radixToPower);\n var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();\n var digits = intval.toString(radix);\n\n rem = remDiv;\n if (rem.isZero()) {\n return digits + result;\n } else {\n while (digits.length < 6) {\n digits = '0' + digits;\n }\n result = '' + digits + result;\n }\n }\n};\n\n/**\n * Return the high 32-bits value.\n *\n * @method\n * @return {number} the high 32-bits as a signed value.\n */\nLong.prototype.getHighBits = function() {\n return this.high_;\n};\n\n/**\n * Return the low 32-bits value.\n *\n * @method\n * @return {number} the low 32-bits as a signed value.\n */\nLong.prototype.getLowBits = function() {\n return this.low_;\n};\n\n/**\n * Return the low unsigned 32-bits value.\n *\n * @method\n * @return {number} the low 32-bits as an unsigned value.\n */\nLong.prototype.getLowBitsUnsigned = function() {\n return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_;\n};\n\n/**\n * Returns the number of bits needed to represent the absolute value of this Long.\n *\n * @method\n * @return {number} Returns the number of bits needed to represent the absolute value of this Long.\n */\nLong.prototype.getNumBitsAbs = function() {\n if (this.isNegative()) {\n if (this.equals(Long.MIN_VALUE)) {\n return 64;\n } else {\n return this.negate().getNumBitsAbs();\n }\n } else {\n var val = this.high_ !== 0 ? this.high_ : this.low_;\n for (var bit = 31; bit > 0; bit--) {\n if ((val & (1 << bit)) !== 0) {\n break;\n }\n }\n return this.high_ !== 0 ? bit + 33 : bit + 1;\n }\n};\n\n/**\n * Return whether this value is zero.\n *\n * @method\n * @return {boolean} whether this value is zero.\n */\nLong.prototype.isZero = function() {\n return this.high_ === 0 && this.low_ === 0;\n};\n\n/**\n * Return whether this value is negative.\n *\n * @method\n * @return {boolean} whether this value is negative.\n */\nLong.prototype.isNegative = function() {\n return this.high_ < 0;\n};\n\n/**\n * Return whether this value is odd.\n *\n * @method\n * @return {boolean} whether this value is odd.\n */\nLong.prototype.isOdd = function() {\n return (this.low_ & 1) === 1;\n};\n\n/**\n * Return whether this Long equals the other\n *\n * @method\n * @param {Long} other Long to compare against.\n * @return {boolean} whether this Long equals the other\n */\nLong.prototype.equals = function(other) {\n return this.high_ === other.high_ && this.low_ === other.low_;\n};\n\n/**\n * Return whether this Long does not equal the other.\n *\n * @method\n * @param {Long} other Long to compare against.\n * @return {boolean} whether this Long does not equal the other.\n */\nLong.prototype.notEquals = function(other) {\n return this.high_ !== other.high_ || this.low_ !== other.low_;\n};\n\n/**\n * Return whether this Long is less than the other.\n *\n * @method\n * @param {Long} other Long to compare against.\n * @return {boolean} whether this Long is less than the other.\n */\nLong.prototype.lessThan = function(other) {\n return this.compare(other) < 0;\n};\n\n/**\n * Return whether this Long is less than or equal to the other.\n *\n * @method\n * @param {Long} other Long to compare against.\n * @return {boolean} whether this Long is less than or equal to the other.\n */\nLong.prototype.lessThanOrEqual = function(other) {\n return this.compare(other) <= 0;\n};\n\n/**\n * Return whether this Long is greater than the other.\n *\n * @method\n * @param {Long} other Long to compare against.\n * @return {boolean} whether this Long is greater than the other.\n */\nLong.prototype.greaterThan = function(other) {\n return this.compare(other) > 0;\n};\n\n/**\n * Return whether this Long is greater than or equal to the other.\n *\n * @method\n * @param {Long} other Long to compare against.\n * @return {boolean} whether this Long is greater than or equal to the other.\n */\nLong.prototype.greaterThanOrEqual = function(other) {\n return this.compare(other) >= 0;\n};\n\n/**\n * Compares this Long with the given one.\n *\n * @method\n * @param {Long} other Long to compare against.\n * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.\n */\nLong.prototype.compare = function(other) {\n if (this.equals(other)) {\n return 0;\n }\n\n var thisNeg = this.isNegative();\n var otherNeg = other.isNegative();\n if (thisNeg && !otherNeg) {\n return -1;\n }\n if (!thisNeg && otherNeg) {\n return 1;\n }\n\n // at this point, the signs are the same, so subtraction will not overflow\n if (this.subtract(other).isNegative()) {\n return -1;\n } else {\n return 1;\n }\n};\n\n/**\n * The negation of this value.\n *\n * @method\n * @return {Long} the negation of this value.\n */\nLong.prototype.negate = function() {\n if (this.equals(Long.MIN_VALUE)) {\n return Long.MIN_VALUE;\n } else {\n return this.not().add(Long.ONE);\n }\n};\n\n/**\n * Returns the sum of this and the given Long.\n *\n * @method\n * @param {Long} other Long to add to this one.\n * @return {Long} the sum of this and the given Long.\n */\nLong.prototype.add = function(other) {\n // Divide each number into 4 chunks of 16 bits, and then sum the chunks.\n\n var a48 = this.high_ >>> 16;\n var a32 = this.high_ & 0xffff;\n var a16 = this.low_ >>> 16;\n var a00 = this.low_ & 0xffff;\n\n var b48 = other.high_ >>> 16;\n var b32 = other.high_ & 0xffff;\n var b16 = other.low_ >>> 16;\n var b00 = other.low_ & 0xffff;\n\n var c48 = 0,\n c32 = 0,\n c16 = 0,\n c00 = 0;\n c00 += a00 + b00;\n c16 += c00 >>> 16;\n c00 &= 0xffff;\n c16 += a16 + b16;\n c32 += c16 >>> 16;\n c16 &= 0xffff;\n c32 += a32 + b32;\n c48 += c32 >>> 16;\n c32 &= 0xffff;\n c48 += a48 + b48;\n c48 &= 0xffff;\n return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);\n};\n\n/**\n * Returns the difference of this and the given Long.\n *\n * @method\n * @param {Long} other Long to subtract from this.\n * @return {Long} the difference of this and the given Long.\n */\nLong.prototype.subtract = function(other) {\n return this.add(other.negate());\n};\n\n/**\n * Returns the product of this and the given Long.\n *\n * @method\n * @param {Long} other Long to multiply with this.\n * @return {Long} the product of this and the other.\n */\nLong.prototype.multiply = function(other) {\n if (this.isZero()) {\n return Long.ZERO;\n } else if (other.isZero()) {\n return Long.ZERO;\n }\n\n if (this.equals(Long.MIN_VALUE)) {\n return other.isOdd() ? Long.MIN_VALUE : Long.ZERO;\n } else if (other.equals(Long.MIN_VALUE)) {\n return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;\n }\n\n if (this.isNegative()) {\n if (other.isNegative()) {\n return this.negate().multiply(other.negate());\n } else {\n return this.negate()\n .multiply(other)\n .negate();\n }\n } else if (other.isNegative()) {\n return this.multiply(other.negate()).negate();\n }\n\n // If both Longs are small, use float multiplication\n if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) {\n return Long.fromNumber(this.toNumber() * other.toNumber());\n }\n\n // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products.\n // We can skip products that would overflow.\n\n var a48 = this.high_ >>> 16;\n var a32 = this.high_ & 0xffff;\n var a16 = this.low_ >>> 16;\n var a00 = this.low_ & 0xffff;\n\n var b48 = other.high_ >>> 16;\n var b32 = other.high_ & 0xffff;\n var b16 = other.low_ >>> 16;\n var b00 = other.low_ & 0xffff;\n\n var c48 = 0,\n c32 = 0,\n c16 = 0,\n c00 = 0;\n c00 += a00 * b00;\n c16 += c00 >>> 16;\n c00 &= 0xffff;\n c16 += a16 * b00;\n c32 += c16 >>> 16;\n c16 &= 0xffff;\n c16 += a00 * b16;\n c32 += c16 >>> 16;\n c16 &= 0xffff;\n c32 += a32 * b00;\n c48 += c32 >>> 16;\n c32 &= 0xffff;\n c32 += a16 * b16;\n c48 += c32 >>> 16;\n c32 &= 0xffff;\n c32 += a00 * b32;\n c48 += c32 >>> 16;\n c32 &= 0xffff;\n c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;\n c48 &= 0xffff;\n return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);\n};\n\n/**\n * Returns this Long divided by the given one.\n *\n * @method\n * @param {Long} other Long by which to divide.\n * @return {Long} this Long divided by the given one.\n */\nLong.prototype.div = function(other) {\n if (other.isZero()) {\n throw Error('division by zero');\n } else if (this.isZero()) {\n return Long.ZERO;\n }\n\n if (this.equals(Long.MIN_VALUE)) {\n if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) {\n return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE\n } else if (other.equals(Long.MIN_VALUE)) {\n return Long.ONE;\n } else {\n // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.\n var halfThis = this.shiftRight(1);\n var approx = halfThis.div(other).shiftLeft(1);\n if (approx.equals(Long.ZERO)) {\n return other.isNegative() ? Long.ONE : Long.NEG_ONE;\n } else {\n var rem = this.subtract(other.multiply(approx));\n var result = approx.add(rem.div(other));\n return result;\n }\n }\n } else if (other.equals(Long.MIN_VALUE)) {\n return Long.ZERO;\n }\n\n if (this.isNegative()) {\n if (other.isNegative()) {\n return this.negate().div(other.negate());\n } else {\n return this.negate()\n .div(other)\n .negate();\n }\n } else if (other.isNegative()) {\n return this.div(other.negate()).negate();\n }\n\n // Repeat the following until the remainder is less than other: find a\n // floating-point that approximates remainder / other *from below*, add this\n // into the result, and subtract it from the remainder. It is critical that\n // the approximate value is less than or equal to the real value so that the\n // remainder never becomes negative.\n var res = Long.ZERO;\n rem = this;\n while (rem.greaterThanOrEqual(other)) {\n // Approximate the result of division. This may be a little greater or\n // smaller than the actual value.\n approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));\n\n // We will tweak the approximate result by changing it in the 48-th digit or\n // the smallest non-fractional digit, whichever is larger.\n var log2 = Math.ceil(Math.log(approx) / Math.LN2);\n var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);\n\n // Decrease the approximation until it is smaller than the remainder. Note\n // that if it is too large, the product overflows and is negative.\n var approxRes = Long.fromNumber(approx);\n var approxRem = approxRes.multiply(other);\n while (approxRem.isNegative() || approxRem.greaterThan(rem)) {\n approx -= delta;\n approxRes = Long.fromNumber(approx);\n approxRem = approxRes.multiply(other);\n }\n\n // We know the answer can't be zero... and actually, zero would cause\n // infinite recursion since we would make no progress.\n if (approxRes.isZero()) {\n approxRes = Long.ONE;\n }\n\n res = res.add(approxRes);\n rem = rem.subtract(approxRem);\n }\n return res;\n};\n\n/**\n * Returns this Long modulo the given one.\n *\n * @method\n * @param {Long} other Long by which to mod.\n * @return {Long} this Long modulo the given one.\n */\nLong.prototype.modulo = function(other) {\n return this.subtract(this.div(other).multiply(other));\n};\n\n/**\n * The bitwise-NOT of this value.\n *\n * @method\n * @return {Long} the bitwise-NOT of this value.\n */\nLong.prototype.not = function() {\n return Long.fromBits(~this.low_, ~this.high_);\n};\n\n/**\n * Returns the bitwise-AND of this Long and the given one.\n *\n * @method\n * @param {Long} other the Long with which to AND.\n * @return {Long} the bitwise-AND of this and the other.\n */\nLong.prototype.and = function(other) {\n return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_);\n};\n\n/**\n * Returns the bitwise-OR of this Long and the given one.\n *\n * @method\n * @param {Long} other the Long with which to OR.\n * @return {Long} the bitwise-OR of this and the other.\n */\nLong.prototype.or = function(other) {\n return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_);\n};\n\n/**\n * Returns the bitwise-XOR of this Long and the given one.\n *\n * @method\n * @param {Long} other the Long with which to XOR.\n * @return {Long} the bitwise-XOR of this and the other.\n */\nLong.prototype.xor = function(other) {\n return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_);\n};\n\n/**\n * Returns this Long with bits shifted to the left by the given amount.\n *\n * @method\n * @param {number} numBits the number of bits by which to shift.\n * @return {Long} this shifted to the left by the given amount.\n */\nLong.prototype.shiftLeft = function(numBits) {\n numBits &= 63;\n if (numBits === 0) {\n return this;\n } else {\n var low = this.low_;\n if (numBits < 32) {\n var high = this.high_;\n return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits)));\n } else {\n return Long.fromBits(0, low << (numBits - 32));\n }\n }\n};\n\n/**\n * Returns this Long with bits shifted to the right by the given amount.\n *\n * @method\n * @param {number} numBits the number of bits by which to shift.\n * @return {Long} this shifted to the right by the given amount.\n */\nLong.prototype.shiftRight = function(numBits) {\n numBits &= 63;\n if (numBits === 0) {\n return this;\n } else {\n var high = this.high_;\n if (numBits < 32) {\n var low = this.low_;\n return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits);\n } else {\n return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1);\n }\n }\n};\n\n/**\n * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.\n *\n * @method\n * @param {number} numBits the number of bits by which to shift.\n * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits.\n */\nLong.prototype.shiftRightUnsigned = function(numBits) {\n numBits &= 63;\n if (numBits === 0) {\n return this;\n } else {\n var high = this.high_;\n if (numBits < 32) {\n var low = this.low_;\n return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits);\n } else if (numBits === 32) {\n return Long.fromBits(high, 0);\n } else {\n return Long.fromBits(high >>> (numBits - 32), 0);\n }\n }\n};\n\n/**\n * Returns a Long representing the given (32-bit) integer value.\n *\n * @method\n * @param {number} value the 32-bit integer in question.\n * @return {Long} the corresponding Long value.\n */\nLong.fromInt = function(value) {\n if (-128 <= value && value < 128) {\n var cachedObj = Long.INT_CACHE_[value];\n if (cachedObj) {\n return cachedObj;\n }\n }\n\n var obj = new Long(value | 0, value < 0 ? -1 : 0);\n if (-128 <= value && value < 128) {\n Long.INT_CACHE_[value] = obj;\n }\n return obj;\n};\n\n/**\n * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.\n *\n * @method\n * @param {number} value the number in question.\n * @return {Long} the corresponding Long value.\n */\nLong.fromNumber = function(value) {\n if (isNaN(value) || !isFinite(value)) {\n return Long.ZERO;\n } else if (value <= -Long.TWO_PWR_63_DBL_) {\n return Long.MIN_VALUE;\n } else if (value + 1 >= Long.TWO_PWR_63_DBL_) {\n return Long.MAX_VALUE;\n } else if (value < 0) {\n return Long.fromNumber(-value).negate();\n } else {\n return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0);\n }\n};\n\n/**\n * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.\n *\n * @method\n * @param {number} lowBits the low 32-bits.\n * @param {number} highBits the high 32-bits.\n * @return {Long} the corresponding Long value.\n */\nLong.fromBits = function(lowBits, highBits) {\n return new Long(lowBits, highBits);\n};\n\n/**\n * Returns a Long representation of the given string, written using the given radix.\n *\n * @method\n * @param {string} str the textual representation of the Long.\n * @param {number} opt_radix the radix in which the text is written.\n * @return {Long} the corresponding Long value.\n */\nLong.fromString = function(str, opt_radix) {\n if (str.length === 0) {\n throw Error('number format error: empty string');\n }\n\n var radix = opt_radix || 10;\n if (radix < 2 || 36 < radix) {\n throw Error('radix out of range: ' + radix);\n }\n\n if (str.charAt(0) === '-') {\n return Long.fromString(str.substring(1), radix).negate();\n } else if (str.indexOf('-') >= 0) {\n throw Error('number format error: interior \"-\" character: ' + str);\n }\n\n // Do several (8) digits each time through the loop, so as to\n // minimize the calls to the very expensive emulated div.\n var radixToPower = Long.fromNumber(Math.pow(radix, 8));\n\n var result = Long.ZERO;\n for (var i = 0; i < str.length; i += 8) {\n var size = Math.min(8, str.length - i);\n var value = parseInt(str.substring(i, i + size), radix);\n if (size < 8) {\n var power = Long.fromNumber(Math.pow(radix, size));\n result = result.multiply(power).add(Long.fromNumber(value));\n } else {\n result = result.multiply(radixToPower);\n result = result.add(Long.fromNumber(value));\n }\n }\n return result;\n};\n\n// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the\n// from* methods on which they depend.\n\n/**\n * A cache of the Long representations of small integer values.\n * @type {Object}\n * @ignore\n */\nLong.INT_CACHE_ = {};\n\n// NOTE: the compiler should inline these constant values below and then remove\n// these variables, so there should be no runtime penalty for these.\n\n/**\n * Number used repeated below in calculations. This must appear before the\n * first call to any from* function below.\n * @type {number}\n * @ignore\n */\nLong.TWO_PWR_16_DBL_ = 1 << 16;\n\n/**\n * @type {number}\n * @ignore\n */\nLong.TWO_PWR_24_DBL_ = 1 << 24;\n\n/**\n * @type {number}\n * @ignore\n */\nLong.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_;\n\n/**\n * @type {number}\n * @ignore\n */\nLong.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2;\n\n/**\n * @type {number}\n * @ignore\n */\nLong.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_;\n\n/**\n * @type {number}\n * @ignore\n */\nLong.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_;\n\n/**\n * @type {number}\n * @ignore\n */\nLong.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2;\n\n/** @type {Long} */\nLong.ZERO = Long.fromInt(0);\n\n/** @type {Long} */\nLong.ONE = Long.fromInt(1);\n\n/** @type {Long} */\nLong.NEG_ONE = Long.fromInt(-1);\n\n/** @type {Long} */\nLong.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0);\n\n/** @type {Long} */\nLong.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0);\n\n/**\n * @type {Long}\n * @ignore\n */\nLong.TWO_PWR_24_ = Long.fromInt(1 << 24);\n\n/**\n * Expose.\n */\nmodule.exports = Long;\nmodule.exports.Long = Long;\n","'use strict';\n\n// We have an ES6 Map available, return the native instance\nif (typeof global.Map !== 'undefined') {\n module.exports = global.Map;\n module.exports.Map = global.Map;\n} else {\n // We will return a polyfill\n var Map = function(array) {\n this._keys = [];\n this._values = {};\n\n for (var i = 0; i < array.length; i++) {\n if (array[i] == null) continue; // skip null and undefined\n var entry = array[i];\n var key = entry[0];\n var value = entry[1];\n // Add the key to the list of keys in order\n this._keys.push(key);\n // Add the key and value to the values dictionary with a point\n // to the location in the ordered keys list\n this._values[key] = { v: value, i: this._keys.length - 1 };\n }\n };\n\n Map.prototype.clear = function() {\n this._keys = [];\n this._values = {};\n };\n\n Map.prototype.delete = function(key) {\n var value = this._values[key];\n if (value == null) return false;\n // Delete entry\n delete this._values[key];\n // Remove the key from the ordered keys list\n this._keys.splice(value.i, 1);\n return true;\n };\n\n Map.prototype.entries = function() {\n var self = this;\n var index = 0;\n\n return {\n next: function() {\n var key = self._keys[index++];\n return {\n value: key !== undefined ? [key, self._values[key].v] : undefined,\n done: key !== undefined ? false : true\n };\n }\n };\n };\n\n Map.prototype.forEach = function(callback, self) {\n self = self || this;\n\n for (var i = 0; i < this._keys.length; i++) {\n var key = this._keys[i];\n // Call the forEach callback\n callback.call(self, this._values[key].v, key, self);\n }\n };\n\n Map.prototype.get = function(key) {\n return this._values[key] ? this._values[key].v : undefined;\n };\n\n Map.prototype.has = function(key) {\n return this._values[key] != null;\n };\n\n Map.prototype.keys = function() {\n var self = this;\n var index = 0;\n\n return {\n next: function() {\n var key = self._keys[index++];\n return {\n value: key !== undefined ? key : undefined,\n done: key !== undefined ? false : true\n };\n }\n };\n };\n\n Map.prototype.set = function(key, value) {\n if (this._values[key]) {\n this._values[key].v = value;\n return this;\n }\n\n // Add the key to the list of keys in order\n this._keys.push(key);\n // Add the key and value to the values dictionary with a point\n // to the location in the ordered keys list\n this._values[key] = { v: value, i: this._keys.length - 1 };\n return this;\n };\n\n Map.prototype.values = function() {\n var self = this;\n var index = 0;\n\n return {\n next: function() {\n var key = self._keys[index++];\n return {\n value: key !== undefined ? self._values[key].v : undefined,\n done: key !== undefined ? false : true\n };\n }\n };\n };\n\n // Last ismaster\n Object.defineProperty(Map.prototype, 'size', {\n enumerable: true,\n get: function() {\n return this._keys.length;\n }\n });\n\n module.exports = Map;\n module.exports.Map = Map;\n}\n","/**\n * A class representation of the BSON MaxKey type.\n *\n * @class\n * @return {MaxKey} A MaxKey instance\n */\nfunction MaxKey() {\n if (!(this instanceof MaxKey)) return new MaxKey();\n\n this._bsontype = 'MaxKey';\n}\n\nmodule.exports = MaxKey;\nmodule.exports.MaxKey = MaxKey;\n","/**\n * A class representation of the BSON MinKey type.\n *\n * @class\n * @return {MinKey} A MinKey instance\n */\nfunction MinKey() {\n if (!(this instanceof MinKey)) return new MinKey();\n\n this._bsontype = 'MinKey';\n}\n\nmodule.exports = MinKey;\nmodule.exports.MinKey = MinKey;\n","// Custom inspect property name / symbol.\nvar inspect = 'inspect';\n\nvar utils = require('./parser/utils');\n\n/**\n * Machine id.\n *\n * Create a random 3-byte value (i.e. unique for this\n * process). Other drivers use a md5 of the machine id here, but\n * that would mean an asyc call to gethostname, so we don't bother.\n * @ignore\n */\nvar MACHINE_ID = parseInt(Math.random() * 0xffffff, 10);\n\n// Regular expression that checks for hex value\nvar checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');\n\n// Check if buffer exists\ntry {\n if (Buffer && Buffer.from) {\n var hasBufferType = true;\n inspect = require('util').inspect.custom || 'inspect';\n }\n} catch (err) {\n hasBufferType = false;\n}\n\n/**\n* Create a new ObjectID instance\n*\n* @class\n* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number.\n* @property {number} generationTime The generation time of this ObjectId instance\n* @return {ObjectID} instance of ObjectID.\n*/\nvar ObjectID = function ObjectID(id) {\n // Duck-typing to support ObjectId from different npm packages\n if (id instanceof ObjectID) return id;\n if (!(this instanceof ObjectID)) return new ObjectID(id);\n\n this._bsontype = 'ObjectID';\n\n // The most common usecase (blank id, new objectId instance)\n if (id == null || typeof id === 'number') {\n // Generate a new id\n this.id = this.generate(id);\n // If we are caching the hex string\n if (ObjectID.cacheHexString) this.__id = this.toString('hex');\n // Return the object\n return;\n }\n\n // Check if the passed in id is valid\n var valid = ObjectID.isValid(id);\n\n // Throw an error if it's not a valid setup\n if (!valid && id != null) {\n throw new Error(\n 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'\n );\n } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) {\n return new ObjectID(utils.toBuffer(id, 'hex'));\n } else if (valid && typeof id === 'string' && id.length === 24) {\n return ObjectID.createFromHexString(id);\n } else if (id != null && id.length === 12) {\n // assume 12 byte string\n this.id = id;\n } else if (id != null && typeof id.toHexString === 'function') {\n // Duck-typing to support ObjectId from different npm packages\n return id;\n } else {\n throw new Error(\n 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'\n );\n }\n\n if (ObjectID.cacheHexString) this.__id = this.toString('hex');\n};\n\n// Allow usage of ObjectId as well as ObjectID\n// var ObjectId = ObjectID;\n\n// Precomputed hex table enables speedy hex string conversion\nvar hexTable = [];\nfor (var i = 0; i < 256; i++) {\n hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16);\n}\n\n/**\n* Return the ObjectID id as a 24 byte hex string representation\n*\n* @method\n* @return {string} return the 24 byte hex string representation.\n*/\nObjectID.prototype.toHexString = function() {\n if (ObjectID.cacheHexString && this.__id) return this.__id;\n\n var hexString = '';\n if (!this.id || !this.id.length) {\n throw new Error(\n 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' +\n JSON.stringify(this.id) +\n ']'\n );\n }\n\n if (this.id instanceof _Buffer) {\n hexString = convertToHex(this.id);\n if (ObjectID.cacheHexString) this.__id = hexString;\n return hexString;\n }\n\n for (var i = 0; i < this.id.length; i++) {\n hexString += hexTable[this.id.charCodeAt(i)];\n }\n\n if (ObjectID.cacheHexString) this.__id = hexString;\n return hexString;\n};\n\n/**\n* Update the ObjectID index used in generating new ObjectID's on the driver\n*\n* @method\n* @return {number} returns next index value.\n* @ignore\n*/\nObjectID.prototype.get_inc = function() {\n return (ObjectID.index = (ObjectID.index + 1) % 0xffffff);\n};\n\n/**\n* Update the ObjectID index used in generating new ObjectID's on the driver\n*\n* @method\n* @return {number} returns next index value.\n* @ignore\n*/\nObjectID.prototype.getInc = function() {\n return this.get_inc();\n};\n\n/**\n* Generate a 12 byte id buffer used in ObjectID's\n*\n* @method\n* @param {number} [time] optional parameter allowing to pass in a second based timestamp.\n* @return {Buffer} return the 12 byte id buffer string.\n*/\nObjectID.prototype.generate = function(time) {\n if ('number' !== typeof time) {\n time = ~~(Date.now() / 1000);\n }\n\n // Use pid\n var pid =\n (typeof process === 'undefined' || process.pid === 1\n ? Math.floor(Math.random() * 100000)\n : process.pid) % 0xffff;\n var inc = this.get_inc();\n // Buffer used\n var buffer = utils.allocBuffer(12);\n // Encode time\n buffer[3] = time & 0xff;\n buffer[2] = (time >> 8) & 0xff;\n buffer[1] = (time >> 16) & 0xff;\n buffer[0] = (time >> 24) & 0xff;\n // Encode machine\n buffer[6] = MACHINE_ID & 0xff;\n buffer[5] = (MACHINE_ID >> 8) & 0xff;\n buffer[4] = (MACHINE_ID >> 16) & 0xff;\n // Encode pid\n buffer[8] = pid & 0xff;\n buffer[7] = (pid >> 8) & 0xff;\n // Encode index\n buffer[11] = inc & 0xff;\n buffer[10] = (inc >> 8) & 0xff;\n buffer[9] = (inc >> 16) & 0xff;\n // Return the buffer\n return buffer;\n};\n\n/**\n* Converts the id into a 24 byte hex string for printing\n*\n* @param {String} format The Buffer toString format parameter.\n* @return {String} return the 24 byte hex string representation.\n* @ignore\n*/\nObjectID.prototype.toString = function(format) {\n // Is the id a buffer then use the buffer toString method to return the format\n if (this.id && this.id.copy) {\n return this.id.toString(typeof format === 'string' ? format : 'hex');\n }\n\n // if(this.buffer )\n return this.toHexString();\n};\n\n/**\n* Converts to a string representation of this Id.\n*\n* @return {String} return the 24 byte hex string representation.\n* @ignore\n*/\nObjectID.prototype[inspect] = ObjectID.prototype.toString;\n\n/**\n* Converts to its JSON representation.\n*\n* @return {String} return the 24 byte hex string representation.\n* @ignore\n*/\nObjectID.prototype.toJSON = function() {\n return this.toHexString();\n};\n\n/**\n* Compares the equality of this ObjectID with `otherID`.\n*\n* @method\n* @param {object} otherID ObjectID instance to compare against.\n* @return {boolean} the result of comparing two ObjectID's\n*/\nObjectID.prototype.equals = function equals(otherId) {\n // var id;\n\n if (otherId instanceof ObjectID) {\n return this.toString() === otherId.toString();\n } else if (\n typeof otherId === 'string' &&\n ObjectID.isValid(otherId) &&\n otherId.length === 12 &&\n this.id instanceof _Buffer\n ) {\n return otherId === this.id.toString('binary');\n } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) {\n return otherId.toLowerCase() === this.toHexString();\n } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) {\n return otherId === this.id;\n } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) {\n return otherId.toHexString() === this.toHexString();\n } else {\n return false;\n }\n};\n\n/**\n* Returns the generation date (accurate up to the second) that this ID was generated.\n*\n* @method\n* @return {date} the generation date\n*/\nObjectID.prototype.getTimestamp = function() {\n var timestamp = new Date();\n var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24);\n timestamp.setTime(Math.floor(time) * 1000);\n return timestamp;\n};\n\n/**\n* @ignore\n*/\nObjectID.index = ~~(Math.random() * 0xffffff);\n\n/**\n* @ignore\n*/\nObjectID.createPk = function createPk() {\n return new ObjectID();\n};\n\n/**\n* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.\n*\n* @method\n* @param {number} time an integer number representing a number of seconds.\n* @return {ObjectID} return the created ObjectID\n*/\nObjectID.createFromTime = function createFromTime(time) {\n var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);\n // Encode time into first 4 bytes\n buffer[3] = time & 0xff;\n buffer[2] = (time >> 8) & 0xff;\n buffer[1] = (time >> 16) & 0xff;\n buffer[0] = (time >> 24) & 0xff;\n // Return the new objectId\n return new ObjectID(buffer);\n};\n\n// Lookup tables\n//var encodeLookup = '0123456789abcdef'.split('');\nvar decodeLookup = [];\ni = 0;\nwhile (i < 10) decodeLookup[0x30 + i] = i++;\nwhile (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++;\n\nvar _Buffer = Buffer;\nvar convertToHex = function(bytes) {\n return bytes.toString('hex');\n};\n\n/**\n* Creates an ObjectID from a hex string representation of an ObjectID.\n*\n* @method\n* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring.\n* @return {ObjectID} return the created ObjectID\n*/\nObjectID.createFromHexString = function createFromHexString(string) {\n // Throw an error if it's not a valid setup\n if (typeof string === 'undefined' || (string != null && string.length !== 24)) {\n throw new Error(\n 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'\n );\n }\n\n // Use Buffer.from method if available\n if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex'));\n\n // Calculate lengths\n var array = new _Buffer(12);\n var n = 0;\n var i = 0;\n\n while (i < 24) {\n array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)];\n }\n\n return new ObjectID(array);\n};\n\n/**\n* Checks if a value is a valid bson ObjectId\n*\n* @method\n* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise.\n*/\nObjectID.isValid = function isValid(id) {\n if (id == null) return false;\n\n if (typeof id === 'number') {\n return true;\n }\n\n if (typeof id === 'string') {\n return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id));\n }\n\n if (id instanceof ObjectID) {\n return true;\n }\n\n if (id instanceof _Buffer) {\n return true;\n }\n\n // Duck-Typing detection of ObjectId like objects\n if (\n typeof id.toHexString === 'function' &&\n (id.id instanceof _Buffer || typeof id.id === 'string')\n ) {\n return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id));\n }\n\n return false;\n};\n\n/**\n* @ignore\n*/\nObject.defineProperty(ObjectID.prototype, 'generationTime', {\n enumerable: true,\n get: function() {\n return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24);\n },\n set: function(value) {\n // Encode time into first 4 bytes\n this.id[3] = value & 0xff;\n this.id[2] = (value >> 8) & 0xff;\n this.id[1] = (value >> 16) & 0xff;\n this.id[0] = (value >> 24) & 0xff;\n }\n});\n\n/**\n * Expose.\n */\nmodule.exports = ObjectID;\nmodule.exports.ObjectID = ObjectID;\nmodule.exports.ObjectId = ObjectID;\n","'use strict';\n\nvar Long = require('../long').Long,\n Double = require('../double').Double,\n Timestamp = require('../timestamp').Timestamp,\n ObjectID = require('../objectid').ObjectID,\n Symbol = require('../symbol').Symbol,\n BSONRegExp = require('../regexp').BSONRegExp,\n Code = require('../code').Code,\n Decimal128 = require('../decimal128'),\n MinKey = require('../min_key').MinKey,\n MaxKey = require('../max_key').MaxKey,\n DBRef = require('../db_ref').DBRef,\n Binary = require('../binary').Binary;\n\nvar normalizedFunctionString = require('./utils').normalizedFunctionString;\n\n// To ensure that 0.4 of node works correctly\nvar isDate = function isDate(d) {\n return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]';\n};\n\nvar calculateObjectSize = function calculateObjectSize(\n object,\n serializeFunctions,\n ignoreUndefined\n) {\n var totalLength = 4 + 1;\n\n if (Array.isArray(object)) {\n for (var i = 0; i < object.length; i++) {\n totalLength += calculateElement(\n i.toString(),\n object[i],\n serializeFunctions,\n true,\n ignoreUndefined\n );\n }\n } else {\n // If we have toBSON defined, override the current object\n if (object.toBSON) {\n object = object.toBSON();\n }\n\n // Calculate size\n for (var key in object) {\n totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);\n }\n }\n\n return totalLength;\n};\n\n/**\n * @ignore\n * @api private\n */\nfunction calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) {\n // If we have toBSON defined, override the current object\n if (value && value.toBSON) {\n value = value.toBSON();\n }\n\n switch (typeof value) {\n case 'string':\n return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1;\n case 'number':\n if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) {\n if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) {\n // 32 bit\n return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1);\n } else {\n return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);\n }\n } else {\n // 64 bit\n return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);\n }\n case 'undefined':\n if (isArray || !ignoreUndefined)\n return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1;\n return 0;\n case 'boolean':\n return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1);\n case 'object':\n if (\n value == null ||\n value instanceof MinKey ||\n value instanceof MaxKey ||\n value['_bsontype'] === 'MinKey' ||\n value['_bsontype'] === 'MaxKey'\n ) {\n return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1;\n } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') {\n return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1);\n } else if (value instanceof Date || isDate(value)) {\n return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);\n } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length\n );\n } else if (\n value instanceof Long ||\n value instanceof Double ||\n value instanceof Timestamp ||\n value['_bsontype'] === 'Long' ||\n value['_bsontype'] === 'Double' ||\n value['_bsontype'] === 'Timestamp'\n ) {\n return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);\n } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') {\n return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1);\n } else if (value instanceof Code || value['_bsontype'] === 'Code') {\n // Calculate size depending on the availability of a scope\n if (value.scope != null && Object.keys(value.scope).length > 0) {\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +\n 1 +\n 4 +\n 4 +\n Buffer.byteLength(value.code.toString(), 'utf8') +\n 1 +\n calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)\n );\n } else {\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +\n 1 +\n 4 +\n Buffer.byteLength(value.code.toString(), 'utf8') +\n 1\n );\n }\n } else if (value instanceof Binary || value['_bsontype'] === 'Binary') {\n // Check what kind of subtype we have\n if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +\n (value.position + 1 + 4 + 1 + 4)\n );\n } else {\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)\n );\n }\n } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') {\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +\n Buffer.byteLength(value.value, 'utf8') +\n 4 +\n 1 +\n 1\n );\n } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') {\n // Set up correct object for serialization\n var ordered_values = {\n $ref: value.namespace,\n $id: value.oid\n };\n\n // Add db reference if it exists\n if (null != value.db) {\n ordered_values['$db'] = value.db;\n }\n\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +\n 1 +\n calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)\n );\n } else if (\n value instanceof RegExp ||\n Object.prototype.toString.call(value) === '[object RegExp]'\n ) {\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +\n 1 +\n Buffer.byteLength(value.source, 'utf8') +\n 1 +\n (value.global ? 1 : 0) +\n (value.ignoreCase ? 1 : 0) +\n (value.multiline ? 1 : 0) +\n 1\n );\n } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') {\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +\n 1 +\n Buffer.byteLength(value.pattern, 'utf8') +\n 1 +\n Buffer.byteLength(value.options, 'utf8') +\n 1\n );\n } else {\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +\n calculateObjectSize(value, serializeFunctions, ignoreUndefined) +\n 1\n );\n }\n case 'function':\n // WTF for 0.4.X where typeof /someregexp/ === 'function'\n if (\n value instanceof RegExp ||\n Object.prototype.toString.call(value) === '[object RegExp]' ||\n String.call(value) === '[object RegExp]'\n ) {\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +\n 1 +\n Buffer.byteLength(value.source, 'utf8') +\n 1 +\n (value.global ? 1 : 0) +\n (value.ignoreCase ? 1 : 0) +\n (value.multiline ? 1 : 0) +\n 1\n );\n } else {\n if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) {\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +\n 1 +\n 4 +\n 4 +\n Buffer.byteLength(normalizedFunctionString(value), 'utf8') +\n 1 +\n calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)\n );\n } else if (serializeFunctions) {\n return (\n (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +\n 1 +\n 4 +\n Buffer.byteLength(normalizedFunctionString(value), 'utf8') +\n 1\n );\n }\n }\n }\n\n return 0;\n}\n\nvar BSON = {};\n\n// BSON MAX VALUES\nBSON.BSON_INT32_MAX = 0x7fffffff;\nBSON.BSON_INT32_MIN = -0x80000000;\n\n// JS MAX PRECISE VALUES\nBSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.\nBSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.\n\nmodule.exports = calculateObjectSize;\n","'use strict';\n\nvar Long = require('../long').Long,\n Double = require('../double').Double,\n Timestamp = require('../timestamp').Timestamp,\n ObjectID = require('../objectid').ObjectID,\n Symbol = require('../symbol').Symbol,\n Code = require('../code').Code,\n MinKey = require('../min_key').MinKey,\n MaxKey = require('../max_key').MaxKey,\n Decimal128 = require('../decimal128'),\n Int32 = require('../int_32'),\n DBRef = require('../db_ref').DBRef,\n BSONRegExp = require('../regexp').BSONRegExp,\n Binary = require('../binary').Binary;\n\nvar utils = require('./utils');\n\nvar deserialize = function(buffer, options, isArray) {\n options = options == null ? {} : options;\n var index = options && options.index ? options.index : 0;\n // Read the document size\n var size =\n buffer[index] |\n (buffer[index + 1] << 8) |\n (buffer[index + 2] << 16) |\n (buffer[index + 3] << 24);\n\n // Ensure buffer is valid size\n if (size < 5 || buffer.length < size || size + index > buffer.length) {\n throw new Error('corrupt bson message');\n }\n\n // Illegal end value\n if (buffer[index + size - 1] !== 0) {\n throw new Error(\"One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00\");\n }\n\n // Start deserializtion\n return deserializeObject(buffer, index, options, isArray);\n};\n\nvar deserializeObject = function(buffer, index, options, isArray) {\n var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions'];\n var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions'];\n var cacheFunctionsCrc32 =\n options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32'];\n\n if (!cacheFunctionsCrc32) var crc32 = null;\n\n var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];\n\n // Return raw bson buffer instead of parsing it\n var raw = options['raw'] == null ? false : options['raw'];\n\n // Return BSONRegExp objects instead of native regular expressions\n var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;\n\n // Controls the promotion of values vs wrapper classes\n var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];\n var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];\n var promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];\n\n // Set the start index\n var startIndex = index;\n\n // Validate that we have at least 4 bytes of buffer\n if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long');\n\n // Read the document size\n var size =\n buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);\n\n // Ensure buffer is valid size\n if (size < 5 || size > buffer.length) throw new Error('corrupt bson message');\n\n // Create holding object\n var object = isArray ? [] : {};\n // Used for arrays to skip having to perform utf8 decoding\n var arrayIndex = 0;\n\n var done = false;\n\n // While we have more left data left keep parsing\n // while (buffer[index + 1] !== 0) {\n while (!done) {\n // Read the type\n var elementType = buffer[index++];\n // If we get a zero it's the last byte, exit\n if (elementType === 0) break;\n\n // Get the start search index\n var i = index;\n // Locate the end of the c string\n while (buffer[i] !== 0x00 && i < buffer.length) {\n i++;\n }\n\n // If are at the end of the buffer there is a problem with the document\n if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString');\n var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i);\n\n index = i + 1;\n\n if (elementType === BSON.BSON_DATA_STRING) {\n var stringSize =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n if (\n stringSize <= 0 ||\n stringSize > buffer.length - index ||\n buffer[index + stringSize - 1] !== 0\n )\n throw new Error('bad string length in bson');\n object[name] = buffer.toString('utf8', index, index + stringSize - 1);\n index = index + stringSize;\n } else if (elementType === BSON.BSON_DATA_OID) {\n var oid = utils.allocBuffer(12);\n buffer.copy(oid, 0, index, index + 12);\n object[name] = new ObjectID(oid);\n index = index + 12;\n } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) {\n object[name] = new Int32(\n buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)\n );\n } else if (elementType === BSON.BSON_DATA_INT) {\n object[name] =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) {\n object[name] = new Double(buffer.readDoubleLE(index));\n index = index + 8;\n } else if (elementType === BSON.BSON_DATA_NUMBER) {\n object[name] = buffer.readDoubleLE(index);\n index = index + 8;\n } else if (elementType === BSON.BSON_DATA_DATE) {\n var lowBits =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n var highBits =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n object[name] = new Date(new Long(lowBits, highBits).toNumber());\n } else if (elementType === BSON.BSON_DATA_BOOLEAN) {\n if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value');\n object[name] = buffer[index++] === 1;\n } else if (elementType === BSON.BSON_DATA_OBJECT) {\n var _index = index;\n var objectSize =\n buffer[index] |\n (buffer[index + 1] << 8) |\n (buffer[index + 2] << 16) |\n (buffer[index + 3] << 24);\n if (objectSize <= 0 || objectSize > buffer.length - index)\n throw new Error('bad embedded document length in bson');\n\n // We have a raw value\n if (raw) {\n object[name] = buffer.slice(index, index + objectSize);\n } else {\n object[name] = deserializeObject(buffer, _index, options, false);\n }\n\n index = index + objectSize;\n } else if (elementType === BSON.BSON_DATA_ARRAY) {\n _index = index;\n objectSize =\n buffer[index] |\n (buffer[index + 1] << 8) |\n (buffer[index + 2] << 16) |\n (buffer[index + 3] << 24);\n var arrayOptions = options;\n\n // Stop index\n var stopIndex = index + objectSize;\n\n // All elements of array to be returned as raw bson\n if (fieldsAsRaw && fieldsAsRaw[name]) {\n arrayOptions = {};\n for (var n in options) arrayOptions[n] = options[n];\n arrayOptions['raw'] = true;\n }\n\n object[name] = deserializeObject(buffer, _index, arrayOptions, true);\n index = index + objectSize;\n\n if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte');\n if (index !== stopIndex) throw new Error('corrupted array bson');\n } else if (elementType === BSON.BSON_DATA_UNDEFINED) {\n object[name] = undefined;\n } else if (elementType === BSON.BSON_DATA_NULL) {\n object[name] = null;\n } else if (elementType === BSON.BSON_DATA_LONG) {\n // Unpack the low and high bits\n lowBits =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n highBits =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n var long = new Long(lowBits, highBits);\n // Promote the long if possible\n if (promoteLongs && promoteValues === true) {\n object[name] =\n long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)\n ? long.toNumber()\n : long;\n } else {\n object[name] = long;\n }\n } else if (elementType === BSON.BSON_DATA_DECIMAL128) {\n // Buffer to contain the decimal bytes\n var bytes = utils.allocBuffer(16);\n // Copy the next 16 bytes into the bytes buffer\n buffer.copy(bytes, 0, index, index + 16);\n // Update index\n index = index + 16;\n // Assign the new Decimal128 value\n var decimal128 = new Decimal128(bytes);\n // If we have an alternative mapper use that\n object[name] = decimal128.toObject ? decimal128.toObject() : decimal128;\n } else if (elementType === BSON.BSON_DATA_BINARY) {\n var binarySize =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n var totalBinarySize = binarySize;\n var subType = buffer[index++];\n\n // Did we have a negative binary size, throw\n if (binarySize < 0) throw new Error('Negative binary type element size found');\n\n // Is the length longer than the document\n if (binarySize > buffer.length) throw new Error('Binary type size larger than document size');\n\n // Decode as raw Buffer object if options specifies it\n if (buffer['slice'] != null) {\n // If we have subtype 2 skip the 4 bytes for the size\n if (subType === Binary.SUBTYPE_BYTE_ARRAY) {\n binarySize =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n if (binarySize < 0)\n throw new Error('Negative binary type element size found for subtype 0x02');\n if (binarySize > totalBinarySize - 4)\n throw new Error('Binary type with subtype 0x02 contains to long binary size');\n if (binarySize < totalBinarySize - 4)\n throw new Error('Binary type with subtype 0x02 contains to short binary size');\n }\n\n if (promoteBuffers && promoteValues) {\n object[name] = buffer.slice(index, index + binarySize);\n } else {\n object[name] = new Binary(buffer.slice(index, index + binarySize), subType);\n }\n } else {\n var _buffer =\n typeof Uint8Array !== 'undefined'\n ? new Uint8Array(new ArrayBuffer(binarySize))\n : new Array(binarySize);\n // If we have subtype 2 skip the 4 bytes for the size\n if (subType === Binary.SUBTYPE_BYTE_ARRAY) {\n binarySize =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n if (binarySize < 0)\n throw new Error('Negative binary type element size found for subtype 0x02');\n if (binarySize > totalBinarySize - 4)\n throw new Error('Binary type with subtype 0x02 contains to long binary size');\n if (binarySize < totalBinarySize - 4)\n throw new Error('Binary type with subtype 0x02 contains to short binary size');\n }\n\n // Copy the data\n for (i = 0; i < binarySize; i++) {\n _buffer[i] = buffer[index + i];\n }\n\n if (promoteBuffers && promoteValues) {\n object[name] = _buffer;\n } else {\n object[name] = new Binary(_buffer, subType);\n }\n }\n\n // Update the index\n index = index + binarySize;\n } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) {\n // Get the start search index\n i = index;\n // Locate the end of the c string\n while (buffer[i] !== 0x00 && i < buffer.length) {\n i++;\n }\n // If are at the end of the buffer there is a problem with the document\n if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString');\n // Return the C string\n var source = buffer.toString('utf8', index, i);\n // Create the regexp\n index = i + 1;\n\n // Get the start search index\n i = index;\n // Locate the end of the c string\n while (buffer[i] !== 0x00 && i < buffer.length) {\n i++;\n }\n // If are at the end of the buffer there is a problem with the document\n if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString');\n // Return the C string\n var regExpOptions = buffer.toString('utf8', index, i);\n index = i + 1;\n\n // For each option add the corresponding one for javascript\n var optionsArray = new Array(regExpOptions.length);\n\n // Parse options\n for (i = 0; i < regExpOptions.length; i++) {\n switch (regExpOptions[i]) {\n case 'm':\n optionsArray[i] = 'm';\n break;\n case 's':\n optionsArray[i] = 'g';\n break;\n case 'i':\n optionsArray[i] = 'i';\n break;\n }\n }\n\n object[name] = new RegExp(source, optionsArray.join(''));\n } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) {\n // Get the start search index\n i = index;\n // Locate the end of the c string\n while (buffer[i] !== 0x00 && i < buffer.length) {\n i++;\n }\n // If are at the end of the buffer there is a problem with the document\n if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString');\n // Return the C string\n source = buffer.toString('utf8', index, i);\n index = i + 1;\n\n // Get the start search index\n i = index;\n // Locate the end of the c string\n while (buffer[i] !== 0x00 && i < buffer.length) {\n i++;\n }\n // If are at the end of the buffer there is a problem with the document\n if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString');\n // Return the C string\n regExpOptions = buffer.toString('utf8', index, i);\n index = i + 1;\n\n // Set the object\n object[name] = new BSONRegExp(source, regExpOptions);\n } else if (elementType === BSON.BSON_DATA_SYMBOL) {\n stringSize =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n if (\n stringSize <= 0 ||\n stringSize > buffer.length - index ||\n buffer[index + stringSize - 1] !== 0\n )\n throw new Error('bad string length in bson');\n object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1));\n index = index + stringSize;\n } else if (elementType === BSON.BSON_DATA_TIMESTAMP) {\n lowBits =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n highBits =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n object[name] = new Timestamp(lowBits, highBits);\n } else if (elementType === BSON.BSON_DATA_MIN_KEY) {\n object[name] = new MinKey();\n } else if (elementType === BSON.BSON_DATA_MAX_KEY) {\n object[name] = new MaxKey();\n } else if (elementType === BSON.BSON_DATA_CODE) {\n stringSize =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n if (\n stringSize <= 0 ||\n stringSize > buffer.length - index ||\n buffer[index + stringSize - 1] !== 0\n )\n throw new Error('bad string length in bson');\n var functionString = buffer.toString('utf8', index, index + stringSize - 1);\n\n // If we are evaluating the functions\n if (evalFunctions) {\n // If we have cache enabled let's look for the md5 of the function in the cache\n if (cacheFunctions) {\n var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString;\n // Got to do this to avoid V8 deoptimizing the call due to finding eval\n object[name] = isolateEvalWithHash(functionCache, hash, functionString, object);\n } else {\n object[name] = isolateEval(functionString);\n }\n } else {\n object[name] = new Code(functionString);\n }\n\n // Update parse index position\n index = index + stringSize;\n } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) {\n var totalSize =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n\n // Element cannot be shorter than totalSize + stringSize + documentSize + terminator\n if (totalSize < 4 + 4 + 4 + 1) {\n throw new Error('code_w_scope total size shorter minimum expected length');\n }\n\n // Get the code string size\n stringSize =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n // Check if we have a valid string\n if (\n stringSize <= 0 ||\n stringSize > buffer.length - index ||\n buffer[index + stringSize - 1] !== 0\n )\n throw new Error('bad string length in bson');\n\n // Javascript function\n functionString = buffer.toString('utf8', index, index + stringSize - 1);\n // Update parse index position\n index = index + stringSize;\n // Parse the element\n _index = index;\n // Decode the size of the object document\n objectSize =\n buffer[index] |\n (buffer[index + 1] << 8) |\n (buffer[index + 2] << 16) |\n (buffer[index + 3] << 24);\n // Decode the scope object\n var scopeObject = deserializeObject(buffer, _index, options, false);\n // Adjust the index\n index = index + objectSize;\n\n // Check if field length is to short\n if (totalSize < 4 + 4 + objectSize + stringSize) {\n throw new Error('code_w_scope total size is to short, truncating scope');\n }\n\n // Check if totalSize field is to long\n if (totalSize > 4 + 4 + objectSize + stringSize) {\n throw new Error('code_w_scope total size is to long, clips outer document');\n }\n\n // If we are evaluating the functions\n if (evalFunctions) {\n // If we have cache enabled let's look for the md5 of the function in the cache\n if (cacheFunctions) {\n hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString;\n // Got to do this to avoid V8 deoptimizing the call due to finding eval\n object[name] = isolateEvalWithHash(functionCache, hash, functionString, object);\n } else {\n object[name] = isolateEval(functionString);\n }\n\n object[name].scope = scopeObject;\n } else {\n object[name] = new Code(functionString, scopeObject);\n }\n } else if (elementType === BSON.BSON_DATA_DBPOINTER) {\n // Get the code string size\n stringSize =\n buffer[index++] |\n (buffer[index++] << 8) |\n (buffer[index++] << 16) |\n (buffer[index++] << 24);\n // Check if we have a valid string\n if (\n stringSize <= 0 ||\n stringSize > buffer.length - index ||\n buffer[index + stringSize - 1] !== 0\n )\n throw new Error('bad string length in bson');\n // Namespace\n var namespace = buffer.toString('utf8', index, index + stringSize - 1);\n // Update parse index position\n index = index + stringSize;\n\n // Read the oid\n var oidBuffer = utils.allocBuffer(12);\n buffer.copy(oidBuffer, 0, index, index + 12);\n oid = new ObjectID(oidBuffer);\n\n // Update the index\n index = index + 12;\n\n // Split the namespace\n var parts = namespace.split('.');\n var db = parts.shift();\n var collection = parts.join('.');\n // Upgrade to DBRef type\n object[name] = new DBRef(collection, oid, db);\n } else {\n throw new Error(\n 'Detected unknown BSON type ' +\n elementType.toString(16) +\n ' for fieldname \"' +\n name +\n '\", are you using the latest BSON parser'\n );\n }\n }\n\n // Check if the deserialization was against a valid array/object\n if (size !== index - startIndex) {\n if (isArray) throw new Error('corrupt array bson');\n throw new Error('corrupt object bson');\n }\n\n // Check if we have a db ref object\n if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']);\n return object;\n};\n\n/**\n * Ensure eval is isolated.\n *\n * @ignore\n * @api private\n */\nvar isolateEvalWithHash = function(functionCache, hash, functionString, object) {\n // Contains the value we are going to set\n var value = null;\n\n // Check for cache hit, eval if missing and return cached function\n if (functionCache[hash] == null) {\n eval('value = ' + functionString);\n functionCache[hash] = value;\n }\n // Set the object\n return functionCache[hash].bind(object);\n};\n\n/**\n * Ensure eval is isolated.\n *\n * @ignore\n * @api private\n */\nvar isolateEval = function(functionString) {\n // Contains the value we are going to set\n var value = null;\n // Eval the function\n eval('value = ' + functionString);\n return value;\n};\n\nvar BSON = {};\n\n/**\n * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5\n *\n * @ignore\n * @api private\n */\nvar functionCache = (BSON.functionCache = {});\n\n/**\n * Number BSON Type\n *\n * @classconstant BSON_DATA_NUMBER\n **/\nBSON.BSON_DATA_NUMBER = 1;\n/**\n * String BSON Type\n *\n * @classconstant BSON_DATA_STRING\n **/\nBSON.BSON_DATA_STRING = 2;\n/**\n * Object BSON Type\n *\n * @classconstant BSON_DATA_OBJECT\n **/\nBSON.BSON_DATA_OBJECT = 3;\n/**\n * Array BSON Type\n *\n * @classconstant BSON_DATA_ARRAY\n **/\nBSON.BSON_DATA_ARRAY = 4;\n/**\n * Binary BSON Type\n *\n * @classconstant BSON_DATA_BINARY\n **/\nBSON.BSON_DATA_BINARY = 5;\n/**\n * Binary BSON Type\n *\n * @classconstant BSON_DATA_UNDEFINED\n **/\nBSON.BSON_DATA_UNDEFINED = 6;\n/**\n * ObjectID BSON Type\n *\n * @classconstant BSON_DATA_OID\n **/\nBSON.BSON_DATA_OID = 7;\n/**\n * Boolean BSON Type\n *\n * @classconstant BSON_DATA_BOOLEAN\n **/\nBSON.BSON_DATA_BOOLEAN = 8;\n/**\n * Date BSON Type\n *\n * @classconstant BSON_DATA_DATE\n **/\nBSON.BSON_DATA_DATE = 9;\n/**\n * null BSON Type\n *\n * @classconstant BSON_DATA_NULL\n **/\nBSON.BSON_DATA_NULL = 10;\n/**\n * RegExp BSON Type\n *\n * @classconstant BSON_DATA_REGEXP\n **/\nBSON.BSON_DATA_REGEXP = 11;\n/**\n * Code BSON Type\n *\n * @classconstant BSON_DATA_DBPOINTER\n **/\nBSON.BSON_DATA_DBPOINTER = 12;\n/**\n * Code BSON Type\n *\n * @classconstant BSON_DATA_CODE\n **/\nBSON.BSON_DATA_CODE = 13;\n/**\n * Symbol BSON Type\n *\n * @classconstant BSON_DATA_SYMBOL\n **/\nBSON.BSON_DATA_SYMBOL = 14;\n/**\n * Code with Scope BSON Type\n *\n * @classconstant BSON_DATA_CODE_W_SCOPE\n **/\nBSON.BSON_DATA_CODE_W_SCOPE = 15;\n/**\n * 32 bit Integer BSON Type\n *\n * @classconstant BSON_DATA_INT\n **/\nBSON.BSON_DATA_INT = 16;\n/**\n * Timestamp BSON Type\n *\n * @classconstant BSON_DATA_TIMESTAMP\n **/\nBSON.BSON_DATA_TIMESTAMP = 17;\n/**\n * Long BSON Type\n *\n * @classconstant BSON_DATA_LONG\n **/\nBSON.BSON_DATA_LONG = 18;\n/**\n * Long BSON Type\n *\n * @classconstant BSON_DATA_DECIMAL128\n **/\nBSON.BSON_DATA_DECIMAL128 = 19;\n/**\n * MinKey BSON Type\n *\n * @classconstant BSON_DATA_MIN_KEY\n **/\nBSON.BSON_DATA_MIN_KEY = 0xff;\n/**\n * MaxKey BSON Type\n *\n * @classconstant BSON_DATA_MAX_KEY\n **/\nBSON.BSON_DATA_MAX_KEY = 0x7f;\n\n/**\n * Binary Default Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_DEFAULT\n **/\nBSON.BSON_BINARY_SUBTYPE_DEFAULT = 0;\n/**\n * Binary Function Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_FUNCTION\n **/\nBSON.BSON_BINARY_SUBTYPE_FUNCTION = 1;\n/**\n * Binary Byte Array Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY\n **/\nBSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;\n/**\n * Binary UUID Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_UUID\n **/\nBSON.BSON_BINARY_SUBTYPE_UUID = 3;\n/**\n * Binary MD5 Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_MD5\n **/\nBSON.BSON_BINARY_SUBTYPE_MD5 = 4;\n/**\n * Binary User Defined Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED\n **/\nBSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;\n\n// BSON MAX VALUES\nBSON.BSON_INT32_MAX = 0x7fffffff;\nBSON.BSON_INT32_MIN = -0x80000000;\n\nBSON.BSON_INT64_MAX = Math.pow(2, 63) - 1;\nBSON.BSON_INT64_MIN = -Math.pow(2, 63);\n\n// JS MAX PRECISE VALUES\nBSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.\nBSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.\n\n// Internal long versions\nvar JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double.\nvar JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double.\n\nmodule.exports = deserialize;\n","'use strict';\n\nvar writeIEEE754 = require('../float_parser').writeIEEE754,\n Long = require('../long').Long,\n Map = require('../map'),\n Binary = require('../binary').Binary;\n\nvar normalizedFunctionString = require('./utils').normalizedFunctionString;\n\n// try {\n// var _Buffer = Uint8Array;\n// } catch (e) {\n// _Buffer = Buffer;\n// }\n\nvar regexp = /\\x00/; // eslint-disable-line no-control-regex\nvar ignoreKeys = ['$db', '$ref', '$id', '$clusterTime'];\n\n// To ensure that 0.4 of node works correctly\nvar isDate = function isDate(d) {\n return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]';\n};\n\nvar isRegExp = function isRegExp(d) {\n return Object.prototype.toString.call(d) === '[object RegExp]';\n};\n\nvar serializeString = function(buffer, key, value, index, isArray) {\n // Encode String type\n buffer[index++] = BSON.BSON_DATA_STRING;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes + 1;\n buffer[index - 1] = 0;\n // Write the string\n var size = buffer.write(value, index + 4, 'utf8');\n // Write the size of the string to buffer\n buffer[index + 3] = ((size + 1) >> 24) & 0xff;\n buffer[index + 2] = ((size + 1) >> 16) & 0xff;\n buffer[index + 1] = ((size + 1) >> 8) & 0xff;\n buffer[index] = (size + 1) & 0xff;\n // Update index\n index = index + 4 + size;\n // Write zero\n buffer[index++] = 0;\n return index;\n};\n\nvar serializeNumber = function(buffer, key, value, index, isArray) {\n // We have an integer value\n if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) {\n // If the value fits in 32 bits encode as int, if it fits in a double\n // encode it as a double, otherwise long\n if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) {\n // Set int type 32 bits or less\n buffer[index++] = BSON.BSON_DATA_INT;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Write the int value\n buffer[index++] = value & 0xff;\n buffer[index++] = (value >> 8) & 0xff;\n buffer[index++] = (value >> 16) & 0xff;\n buffer[index++] = (value >> 24) & 0xff;\n } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) {\n // Encode as double\n buffer[index++] = BSON.BSON_DATA_NUMBER;\n // Number of written bytes\n numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Write float\n writeIEEE754(buffer, value, index, 'little', 52, 8);\n // Ajust index\n index = index + 8;\n } else {\n // Set long type\n buffer[index++] = BSON.BSON_DATA_LONG;\n // Number of written bytes\n numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n var longVal = Long.fromNumber(value);\n var lowBits = longVal.getLowBits();\n var highBits = longVal.getHighBits();\n // Encode low bits\n buffer[index++] = lowBits & 0xff;\n buffer[index++] = (lowBits >> 8) & 0xff;\n buffer[index++] = (lowBits >> 16) & 0xff;\n buffer[index++] = (lowBits >> 24) & 0xff;\n // Encode high bits\n buffer[index++] = highBits & 0xff;\n buffer[index++] = (highBits >> 8) & 0xff;\n buffer[index++] = (highBits >> 16) & 0xff;\n buffer[index++] = (highBits >> 24) & 0xff;\n }\n } else {\n // Encode as double\n buffer[index++] = BSON.BSON_DATA_NUMBER;\n // Number of written bytes\n numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Write float\n writeIEEE754(buffer, value, index, 'little', 52, 8);\n // Ajust index\n index = index + 8;\n }\n\n return index;\n};\n\nvar serializeNull = function(buffer, key, value, index, isArray) {\n // Set long type\n buffer[index++] = BSON.BSON_DATA_NULL;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n return index;\n};\n\nvar serializeBoolean = function(buffer, key, value, index, isArray) {\n // Write the type\n buffer[index++] = BSON.BSON_DATA_BOOLEAN;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Encode the boolean value\n buffer[index++] = value ? 1 : 0;\n return index;\n};\n\nvar serializeDate = function(buffer, key, value, index, isArray) {\n // Write the type\n buffer[index++] = BSON.BSON_DATA_DATE;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n\n // Write the date\n var dateInMilis = Long.fromNumber(value.getTime());\n var lowBits = dateInMilis.getLowBits();\n var highBits = dateInMilis.getHighBits();\n // Encode low bits\n buffer[index++] = lowBits & 0xff;\n buffer[index++] = (lowBits >> 8) & 0xff;\n buffer[index++] = (lowBits >> 16) & 0xff;\n buffer[index++] = (lowBits >> 24) & 0xff;\n // Encode high bits\n buffer[index++] = highBits & 0xff;\n buffer[index++] = (highBits >> 8) & 0xff;\n buffer[index++] = (highBits >> 16) & 0xff;\n buffer[index++] = (highBits >> 24) & 0xff;\n return index;\n};\n\nvar serializeRegExp = function(buffer, key, value, index, isArray) {\n // Write the type\n buffer[index++] = BSON.BSON_DATA_REGEXP;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n if (value.source && value.source.match(regexp) != null) {\n throw Error('value ' + value.source + ' must not contain null bytes');\n }\n // Adjust the index\n index = index + buffer.write(value.source, index, 'utf8');\n // Write zero\n buffer[index++] = 0x00;\n // Write the parameters\n if (value.global) buffer[index++] = 0x73; // s\n if (value.ignoreCase) buffer[index++] = 0x69; // i\n if (value.multiline) buffer[index++] = 0x6d; // m\n // Add ending zero\n buffer[index++] = 0x00;\n return index;\n};\n\nvar serializeBSONRegExp = function(buffer, key, value, index, isArray) {\n // Write the type\n buffer[index++] = BSON.BSON_DATA_REGEXP;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n\n // Check the pattern for 0 bytes\n if (value.pattern.match(regexp) != null) {\n // The BSON spec doesn't allow keys with null bytes because keys are\n // null-terminated.\n throw Error('pattern ' + value.pattern + ' must not contain null bytes');\n }\n\n // Adjust the index\n index = index + buffer.write(value.pattern, index, 'utf8');\n // Write zero\n buffer[index++] = 0x00;\n // Write the options\n index =\n index +\n buffer.write(\n value.options\n .split('')\n .sort()\n .join(''),\n index,\n 'utf8'\n );\n // Add ending zero\n buffer[index++] = 0x00;\n return index;\n};\n\nvar serializeMinMax = function(buffer, key, value, index, isArray) {\n // Write the type of either min or max key\n if (value === null) {\n buffer[index++] = BSON.BSON_DATA_NULL;\n } else if (value._bsontype === 'MinKey') {\n buffer[index++] = BSON.BSON_DATA_MIN_KEY;\n } else {\n buffer[index++] = BSON.BSON_DATA_MAX_KEY;\n }\n\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n return index;\n};\n\nvar serializeObjectId = function(buffer, key, value, index, isArray) {\n // Write the type\n buffer[index++] = BSON.BSON_DATA_OID;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n\n // Write the objectId into the shared buffer\n if (typeof value.id === 'string') {\n buffer.write(value.id, index, 'binary');\n } else if (value.id && value.id.copy) {\n value.id.copy(buffer, index, 0, 12);\n } else {\n throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId');\n }\n\n // Ajust index\n return index + 12;\n};\n\nvar serializeBuffer = function(buffer, key, value, index, isArray) {\n // Write the type\n buffer[index++] = BSON.BSON_DATA_BINARY;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Get size of the buffer (current write point)\n var size = value.length;\n // Write the size of the string to buffer\n buffer[index++] = size & 0xff;\n buffer[index++] = (size >> 8) & 0xff;\n buffer[index++] = (size >> 16) & 0xff;\n buffer[index++] = (size >> 24) & 0xff;\n // Write the default subtype\n buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT;\n // Copy the content form the binary field to the buffer\n value.copy(buffer, index, 0, size);\n // Adjust the index\n index = index + size;\n return index;\n};\n\nvar serializeObject = function(\n buffer,\n key,\n value,\n index,\n checkKeys,\n depth,\n serializeFunctions,\n ignoreUndefined,\n isArray,\n path\n) {\n for (var i = 0; i < path.length; i++) {\n if (path[i] === value) throw new Error('cyclic dependency detected');\n }\n\n // Push value to stack\n path.push(value);\n // Write the type\n buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n var endIndex = serializeInto(\n buffer,\n value,\n checkKeys,\n index,\n depth + 1,\n serializeFunctions,\n ignoreUndefined,\n path\n );\n // Pop stack\n path.pop();\n // Write size\n return endIndex;\n};\n\nvar serializeDecimal128 = function(buffer, key, value, index, isArray) {\n buffer[index++] = BSON.BSON_DATA_DECIMAL128;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Write the data from the value\n value.bytes.copy(buffer, index, 0, 16);\n return index + 16;\n};\n\nvar serializeLong = function(buffer, key, value, index, isArray) {\n // Write the type\n buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Write the date\n var lowBits = value.getLowBits();\n var highBits = value.getHighBits();\n // Encode low bits\n buffer[index++] = lowBits & 0xff;\n buffer[index++] = (lowBits >> 8) & 0xff;\n buffer[index++] = (lowBits >> 16) & 0xff;\n buffer[index++] = (lowBits >> 24) & 0xff;\n // Encode high bits\n buffer[index++] = highBits & 0xff;\n buffer[index++] = (highBits >> 8) & 0xff;\n buffer[index++] = (highBits >> 16) & 0xff;\n buffer[index++] = (highBits >> 24) & 0xff;\n return index;\n};\n\nvar serializeInt32 = function(buffer, key, value, index, isArray) {\n // Set int type 32 bits or less\n buffer[index++] = BSON.BSON_DATA_INT;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Write the int value\n buffer[index++] = value & 0xff;\n buffer[index++] = (value >> 8) & 0xff;\n buffer[index++] = (value >> 16) & 0xff;\n buffer[index++] = (value >> 24) & 0xff;\n return index;\n};\n\nvar serializeDouble = function(buffer, key, value, index, isArray) {\n // Encode as double\n buffer[index++] = BSON.BSON_DATA_NUMBER;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Write float\n writeIEEE754(buffer, value, index, 'little', 52, 8);\n // Ajust index\n index = index + 8;\n return index;\n};\n\nvar serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) {\n buffer[index++] = BSON.BSON_DATA_CODE;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Function string\n var functionString = normalizedFunctionString(value);\n\n // Write the string\n var size = buffer.write(functionString, index + 4, 'utf8') + 1;\n // Write the size of the string to buffer\n buffer[index] = size & 0xff;\n buffer[index + 1] = (size >> 8) & 0xff;\n buffer[index + 2] = (size >> 16) & 0xff;\n buffer[index + 3] = (size >> 24) & 0xff;\n // Update index\n index = index + 4 + size - 1;\n // Write zero\n buffer[index++] = 0;\n return index;\n};\n\nvar serializeCode = function(\n buffer,\n key,\n value,\n index,\n checkKeys,\n depth,\n serializeFunctions,\n ignoreUndefined,\n isArray\n) {\n if (value.scope && typeof value.scope === 'object') {\n // Write the type\n buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n\n // Starting index\n var startIndex = index;\n\n // Serialize the function\n // Get the function string\n var functionString = typeof value.code === 'string' ? value.code : value.code.toString();\n // Index adjustment\n index = index + 4;\n // Write string into buffer\n var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1;\n // Write the size of the string to buffer\n buffer[index] = codeSize & 0xff;\n buffer[index + 1] = (codeSize >> 8) & 0xff;\n buffer[index + 2] = (codeSize >> 16) & 0xff;\n buffer[index + 3] = (codeSize >> 24) & 0xff;\n // Write end 0\n buffer[index + 4 + codeSize - 1] = 0;\n // Write the\n index = index + codeSize + 4;\n\n //\n // Serialize the scope value\n var endIndex = serializeInto(\n buffer,\n value.scope,\n checkKeys,\n index,\n depth + 1,\n serializeFunctions,\n ignoreUndefined\n );\n index = endIndex - 1;\n\n // Writ the total\n var totalSize = endIndex - startIndex;\n\n // Write the total size of the object\n buffer[startIndex++] = totalSize & 0xff;\n buffer[startIndex++] = (totalSize >> 8) & 0xff;\n buffer[startIndex++] = (totalSize >> 16) & 0xff;\n buffer[startIndex++] = (totalSize >> 24) & 0xff;\n // Write trailing zero\n buffer[index++] = 0;\n } else {\n buffer[index++] = BSON.BSON_DATA_CODE;\n // Number of written bytes\n numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Function string\n functionString = value.code.toString();\n // Write the string\n var size = buffer.write(functionString, index + 4, 'utf8') + 1;\n // Write the size of the string to buffer\n buffer[index] = size & 0xff;\n buffer[index + 1] = (size >> 8) & 0xff;\n buffer[index + 2] = (size >> 16) & 0xff;\n buffer[index + 3] = (size >> 24) & 0xff;\n // Update index\n index = index + 4 + size - 1;\n // Write zero\n buffer[index++] = 0;\n }\n\n return index;\n};\n\nvar serializeBinary = function(buffer, key, value, index, isArray) {\n // Write the type\n buffer[index++] = BSON.BSON_DATA_BINARY;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Extract the buffer\n var data = value.value(true);\n // Calculate size\n var size = value.position;\n // Add the deprecated 02 type 4 bytes of size to total\n if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4;\n // Write the size of the string to buffer\n buffer[index++] = size & 0xff;\n buffer[index++] = (size >> 8) & 0xff;\n buffer[index++] = (size >> 16) & 0xff;\n buffer[index++] = (size >> 24) & 0xff;\n // Write the subtype to the buffer\n buffer[index++] = value.sub_type;\n\n // If we have binary type 2 the 4 first bytes are the size\n if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {\n size = size - 4;\n buffer[index++] = size & 0xff;\n buffer[index++] = (size >> 8) & 0xff;\n buffer[index++] = (size >> 16) & 0xff;\n buffer[index++] = (size >> 24) & 0xff;\n }\n\n // Write the data to the object\n data.copy(buffer, index, 0, value.position);\n // Adjust the index\n index = index + value.position;\n return index;\n};\n\nvar serializeSymbol = function(buffer, key, value, index, isArray) {\n // Write the type\n buffer[index++] = BSON.BSON_DATA_SYMBOL;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n // Write the string\n var size = buffer.write(value.value, index + 4, 'utf8') + 1;\n // Write the size of the string to buffer\n buffer[index] = size & 0xff;\n buffer[index + 1] = (size >> 8) & 0xff;\n buffer[index + 2] = (size >> 16) & 0xff;\n buffer[index + 3] = (size >> 24) & 0xff;\n // Update index\n index = index + 4 + size - 1;\n // Write zero\n buffer[index++] = 0x00;\n return index;\n};\n\nvar serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) {\n // Write the type\n buffer[index++] = BSON.BSON_DATA_OBJECT;\n // Number of written bytes\n var numberOfWrittenBytes = !isArray\n ? buffer.write(key, index, 'utf8')\n : buffer.write(key, index, 'ascii');\n\n // Encode the name\n index = index + numberOfWrittenBytes;\n buffer[index++] = 0;\n\n var startIndex = index;\n var endIndex;\n\n // Serialize object\n if (null != value.db) {\n endIndex = serializeInto(\n buffer,\n {\n $ref: value.namespace,\n $id: value.oid,\n $db: value.db\n },\n false,\n index,\n depth + 1,\n serializeFunctions\n );\n } else {\n endIndex = serializeInto(\n buffer,\n {\n $ref: value.namespace,\n $id: value.oid\n },\n false,\n index,\n depth + 1,\n serializeFunctions\n );\n }\n\n // Calculate object size\n var size = endIndex - startIndex;\n // Write the size\n buffer[startIndex++] = size & 0xff;\n buffer[startIndex++] = (size >> 8) & 0xff;\n buffer[startIndex++] = (size >> 16) & 0xff;\n buffer[startIndex++] = (size >> 24) & 0xff;\n // Set index\n return endIndex;\n};\n\nvar serializeInto = function serializeInto(\n buffer,\n object,\n checkKeys,\n startingIndex,\n depth,\n serializeFunctions,\n ignoreUndefined,\n path\n) {\n startingIndex = startingIndex || 0;\n path = path || [];\n\n // Push the object to the path\n path.push(object);\n\n // Start place to serialize into\n var index = startingIndex + 4;\n // var self = this;\n\n // Special case isArray\n if (Array.isArray(object)) {\n // Get object keys\n for (var i = 0; i < object.length; i++) {\n var key = '' + i;\n var value = object[i];\n\n // Is there an override value\n if (value && value.toBSON) {\n if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function');\n value = value.toBSON();\n }\n\n var type = typeof value;\n if (type === 'string') {\n index = serializeString(buffer, key, value, index, true);\n } else if (type === 'number') {\n index = serializeNumber(buffer, key, value, index, true);\n } else if (type === 'boolean') {\n index = serializeBoolean(buffer, key, value, index, true);\n } else if (value instanceof Date || isDate(value)) {\n index = serializeDate(buffer, key, value, index, true);\n } else if (value === undefined) {\n index = serializeNull(buffer, key, value, index, true);\n } else if (value === null) {\n index = serializeNull(buffer, key, value, index, true);\n } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') {\n index = serializeObjectId(buffer, key, value, index, true);\n } else if (Buffer.isBuffer(value)) {\n index = serializeBuffer(buffer, key, value, index, true);\n } else if (value instanceof RegExp || isRegExp(value)) {\n index = serializeRegExp(buffer, key, value, index, true);\n } else if (type === 'object' && value['_bsontype'] == null) {\n index = serializeObject(\n buffer,\n key,\n value,\n index,\n checkKeys,\n depth,\n serializeFunctions,\n ignoreUndefined,\n true,\n path\n );\n } else if (type === 'object' && value['_bsontype'] === 'Decimal128') {\n index = serializeDecimal128(buffer, key, value, index, true);\n } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {\n index = serializeLong(buffer, key, value, index, true);\n } else if (value['_bsontype'] === 'Double') {\n index = serializeDouble(buffer, key, value, index, true);\n } else if (typeof value === 'function' && serializeFunctions) {\n index = serializeFunction(\n buffer,\n key,\n value,\n index,\n checkKeys,\n depth,\n serializeFunctions,\n true\n );\n } else if (value['_bsontype'] === 'Code') {\n index = serializeCode(\n buffer,\n key,\n value,\n index,\n checkKeys,\n depth,\n serializeFunctions,\n ignoreUndefined,\n true\n );\n } else if (value['_bsontype'] === 'Binary') {\n index = serializeBinary(buffer, key, value, index, true);\n } else if (value['_bsontype'] === 'Symbol') {\n index = serializeSymbol(buffer, key, value, index, true);\n } else if (value['_bsontype'] === 'DBRef') {\n index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true);\n } else if (value['_bsontype'] === 'BSONRegExp') {\n index = serializeBSONRegExp(buffer, key, value, index, true);\n } else if (value['_bsontype'] === 'Int32') {\n index = serializeInt32(buffer, key, value, index, true);\n } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {\n index = serializeMinMax(buffer, key, value, index, true);\n } else if (typeof value['_bsontype'] !== 'undefined') {\n throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);\n }\n }\n } else if (object instanceof Map) {\n var iterator = object.entries();\n var done = false;\n\n while (!done) {\n // Unpack the next entry\n var entry = iterator.next();\n done = entry.done;\n // Are we done, then skip and terminate\n if (done) continue;\n\n // Get the entry values\n key = entry.value[0];\n value = entry.value[1];\n\n // Check the type of the value\n type = typeof value;\n\n // Check the key and throw error if it's illegal\n if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) {\n if (key.match(regexp) != null) {\n // The BSON spec doesn't allow keys with null bytes because keys are\n // null-terminated.\n throw Error('key ' + key + ' must not contain null bytes');\n }\n\n if (checkKeys) {\n if ('$' === key[0]) {\n throw Error('key ' + key + \" must not start with '$'\");\n } else if (~key.indexOf('.')) {\n throw Error('key ' + key + \" must not contain '.'\");\n }\n }\n }\n\n if (type === 'string') {\n index = serializeString(buffer, key, value, index);\n } else if (type === 'number') {\n index = serializeNumber(buffer, key, value, index);\n } else if (type === 'boolean') {\n index = serializeBoolean(buffer, key, value, index);\n } else if (value instanceof Date || isDate(value)) {\n index = serializeDate(buffer, key, value, index);\n // } else if (value === undefined && ignoreUndefined === true) {\n } else if (value === null || (value === undefined && ignoreUndefined === false)) {\n index = serializeNull(buffer, key, value, index);\n } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') {\n index = serializeObjectId(buffer, key, value, index);\n } else if (Buffer.isBuffer(value)) {\n index = serializeBuffer(buffer, key, value, index);\n } else if (value instanceof RegExp || isRegExp(value)) {\n index = serializeRegExp(buffer, key, value, index);\n } else if (type === 'object' && value['_bsontype'] == null) {\n index = serializeObject(\n buffer,\n key,\n value,\n index,\n checkKeys,\n depth,\n serializeFunctions,\n ignoreUndefined,\n false,\n path\n );\n } else if (type === 'object' && value['_bsontype'] === 'Decimal128') {\n index = serializeDecimal128(buffer, key, value, index);\n } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {\n index = serializeLong(buffer, key, value, index);\n } else if (value['_bsontype'] === 'Double') {\n index = serializeDouble(buffer, key, value, index);\n } else if (value['_bsontype'] === 'Code') {\n index = serializeCode(\n buffer,\n key,\n value,\n index,\n checkKeys,\n depth,\n serializeFunctions,\n ignoreUndefined\n );\n } else if (typeof value === 'function' && serializeFunctions) {\n index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);\n } else if (value['_bsontype'] === 'Binary') {\n index = serializeBinary(buffer, key, value, index);\n } else if (value['_bsontype'] === 'Symbol') {\n index = serializeSymbol(buffer, key, value, index);\n } else if (value['_bsontype'] === 'DBRef') {\n index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions);\n } else if (value['_bsontype'] === 'BSONRegExp') {\n index = serializeBSONRegExp(buffer, key, value, index);\n } else if (value['_bsontype'] === 'Int32') {\n index = serializeInt32(buffer, key, value, index);\n } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {\n index = serializeMinMax(buffer, key, value, index);\n } else if (typeof value['_bsontype'] !== 'undefined') {\n throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);\n }\n }\n } else {\n // Did we provide a custom serialization method\n if (object.toBSON) {\n if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function');\n object = object.toBSON();\n if (object != null && typeof object !== 'object')\n throw new Error('toBSON function did not return an object');\n }\n\n // Iterate over all the keys\n for (key in object) {\n value = object[key];\n // Is there an override value\n if (value && value.toBSON) {\n if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function');\n value = value.toBSON();\n }\n\n // Check the type of the value\n type = typeof value;\n\n // Check the key and throw error if it's illegal\n if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) {\n if (key.match(regexp) != null) {\n // The BSON spec doesn't allow keys with null bytes because keys are\n // null-terminated.\n throw Error('key ' + key + ' must not contain null bytes');\n }\n\n if (checkKeys) {\n if ('$' === key[0]) {\n throw Error('key ' + key + \" must not start with '$'\");\n } else if (~key.indexOf('.')) {\n throw Error('key ' + key + \" must not contain '.'\");\n }\n }\n }\n\n if (type === 'string') {\n index = serializeString(buffer, key, value, index);\n } else if (type === 'number') {\n index = serializeNumber(buffer, key, value, index);\n } else if (type === 'boolean') {\n index = serializeBoolean(buffer, key, value, index);\n } else if (value instanceof Date || isDate(value)) {\n index = serializeDate(buffer, key, value, index);\n } else if (value === undefined) {\n if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index);\n } else if (value === null) {\n index = serializeNull(buffer, key, value, index);\n } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') {\n index = serializeObjectId(buffer, key, value, index);\n } else if (Buffer.isBuffer(value)) {\n index = serializeBuffer(buffer, key, value, index);\n } else if (value instanceof RegExp || isRegExp(value)) {\n index = serializeRegExp(buffer, key, value, index);\n } else if (type === 'object' && value['_bsontype'] == null) {\n index = serializeObject(\n buffer,\n key,\n value,\n index,\n checkKeys,\n depth,\n serializeFunctions,\n ignoreUndefined,\n false,\n path\n );\n } else if (type === 'object' && value['_bsontype'] === 'Decimal128') {\n index = serializeDecimal128(buffer, key, value, index);\n } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {\n index = serializeLong(buffer, key, value, index);\n } else if (value['_bsontype'] === 'Double') {\n index = serializeDouble(buffer, key, value, index);\n } else if (value['_bsontype'] === 'Code') {\n index = serializeCode(\n buffer,\n key,\n value,\n index,\n checkKeys,\n depth,\n serializeFunctions,\n ignoreUndefined\n );\n } else if (typeof value === 'function' && serializeFunctions) {\n index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);\n } else if (value['_bsontype'] === 'Binary') {\n index = serializeBinary(buffer, key, value, index);\n } else if (value['_bsontype'] === 'Symbol') {\n index = serializeSymbol(buffer, key, value, index);\n } else if (value['_bsontype'] === 'DBRef') {\n index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions);\n } else if (value['_bsontype'] === 'BSONRegExp') {\n index = serializeBSONRegExp(buffer, key, value, index);\n } else if (value['_bsontype'] === 'Int32') {\n index = serializeInt32(buffer, key, value, index);\n } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {\n index = serializeMinMax(buffer, key, value, index);\n } else if (typeof value['_bsontype'] !== 'undefined') {\n throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);\n }\n }\n }\n\n // Remove the path\n path.pop();\n\n // Final padding byte for object\n buffer[index++] = 0x00;\n\n // Final size\n var size = index - startingIndex;\n // Write the size of the object\n buffer[startingIndex++] = size & 0xff;\n buffer[startingIndex++] = (size >> 8) & 0xff;\n buffer[startingIndex++] = (size >> 16) & 0xff;\n buffer[startingIndex++] = (size >> 24) & 0xff;\n return index;\n};\n\nvar BSON = {};\n\n/**\n * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5\n *\n * @ignore\n * @api private\n */\n// var functionCache = (BSON.functionCache = {});\n\n/**\n * Number BSON Type\n *\n * @classconstant BSON_DATA_NUMBER\n **/\nBSON.BSON_DATA_NUMBER = 1;\n/**\n * String BSON Type\n *\n * @classconstant BSON_DATA_STRING\n **/\nBSON.BSON_DATA_STRING = 2;\n/**\n * Object BSON Type\n *\n * @classconstant BSON_DATA_OBJECT\n **/\nBSON.BSON_DATA_OBJECT = 3;\n/**\n * Array BSON Type\n *\n * @classconstant BSON_DATA_ARRAY\n **/\nBSON.BSON_DATA_ARRAY = 4;\n/**\n * Binary BSON Type\n *\n * @classconstant BSON_DATA_BINARY\n **/\nBSON.BSON_DATA_BINARY = 5;\n/**\n * ObjectID BSON Type, deprecated\n *\n * @classconstant BSON_DATA_UNDEFINED\n **/\nBSON.BSON_DATA_UNDEFINED = 6;\n/**\n * ObjectID BSON Type\n *\n * @classconstant BSON_DATA_OID\n **/\nBSON.BSON_DATA_OID = 7;\n/**\n * Boolean BSON Type\n *\n * @classconstant BSON_DATA_BOOLEAN\n **/\nBSON.BSON_DATA_BOOLEAN = 8;\n/**\n * Date BSON Type\n *\n * @classconstant BSON_DATA_DATE\n **/\nBSON.BSON_DATA_DATE = 9;\n/**\n * null BSON Type\n *\n * @classconstant BSON_DATA_NULL\n **/\nBSON.BSON_DATA_NULL = 10;\n/**\n * RegExp BSON Type\n *\n * @classconstant BSON_DATA_REGEXP\n **/\nBSON.BSON_DATA_REGEXP = 11;\n/**\n * Code BSON Type\n *\n * @classconstant BSON_DATA_CODE\n **/\nBSON.BSON_DATA_CODE = 13;\n/**\n * Symbol BSON Type\n *\n * @classconstant BSON_DATA_SYMBOL\n **/\nBSON.BSON_DATA_SYMBOL = 14;\n/**\n * Code with Scope BSON Type\n *\n * @classconstant BSON_DATA_CODE_W_SCOPE\n **/\nBSON.BSON_DATA_CODE_W_SCOPE = 15;\n/**\n * 32 bit Integer BSON Type\n *\n * @classconstant BSON_DATA_INT\n **/\nBSON.BSON_DATA_INT = 16;\n/**\n * Timestamp BSON Type\n *\n * @classconstant BSON_DATA_TIMESTAMP\n **/\nBSON.BSON_DATA_TIMESTAMP = 17;\n/**\n * Long BSON Type\n *\n * @classconstant BSON_DATA_LONG\n **/\nBSON.BSON_DATA_LONG = 18;\n/**\n * Long BSON Type\n *\n * @classconstant BSON_DATA_DECIMAL128\n **/\nBSON.BSON_DATA_DECIMAL128 = 19;\n/**\n * MinKey BSON Type\n *\n * @classconstant BSON_DATA_MIN_KEY\n **/\nBSON.BSON_DATA_MIN_KEY = 0xff;\n/**\n * MaxKey BSON Type\n *\n * @classconstant BSON_DATA_MAX_KEY\n **/\nBSON.BSON_DATA_MAX_KEY = 0x7f;\n/**\n * Binary Default Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_DEFAULT\n **/\nBSON.BSON_BINARY_SUBTYPE_DEFAULT = 0;\n/**\n * Binary Function Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_FUNCTION\n **/\nBSON.BSON_BINARY_SUBTYPE_FUNCTION = 1;\n/**\n * Binary Byte Array Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY\n **/\nBSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;\n/**\n * Binary UUID Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_UUID\n **/\nBSON.BSON_BINARY_SUBTYPE_UUID = 3;\n/**\n * Binary MD5 Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_MD5\n **/\nBSON.BSON_BINARY_SUBTYPE_MD5 = 4;\n/**\n * Binary User Defined Type\n *\n * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED\n **/\nBSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;\n\n// BSON MAX VALUES\nBSON.BSON_INT32_MAX = 0x7fffffff;\nBSON.BSON_INT32_MIN = -0x80000000;\n\nBSON.BSON_INT64_MAX = Math.pow(2, 63) - 1;\nBSON.BSON_INT64_MIN = -Math.pow(2, 63);\n\n// JS MAX PRECISE VALUES\nBSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.\nBSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.\n\n// Internal long versions\n// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double.\n// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double.\n\nmodule.exports = serializeInto;\n","'use strict';\n\n/**\n * Normalizes our expected stringified form of a function across versions of node\n * @param {Function} fn The function to stringify\n */\nfunction normalizedFunctionString(fn) {\n return fn.toString().replace(/function *\\(/, 'function (');\n}\n\nfunction newBuffer(item, encoding) {\n return new Buffer(item, encoding);\n}\n\nfunction allocBuffer() {\n return Buffer.alloc.apply(Buffer, arguments);\n}\n\nfunction toBuffer() {\n return Buffer.from.apply(Buffer, arguments);\n}\n\nmodule.exports = {\n normalizedFunctionString: normalizedFunctionString,\n allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer,\n toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer\n};\n\n","/**\n * A class representation of the BSON RegExp type.\n *\n * @class\n * @return {BSONRegExp} A MinKey instance\n */\nfunction BSONRegExp(pattern, options) {\n if (!(this instanceof BSONRegExp)) return new BSONRegExp();\n\n // Execute\n this._bsontype = 'BSONRegExp';\n this.pattern = pattern || '';\n this.options = options || '';\n\n // Validate options\n for (var i = 0; i < this.options.length; i++) {\n if (\n !(\n this.options[i] === 'i' ||\n this.options[i] === 'm' ||\n this.options[i] === 'x' ||\n this.options[i] === 'l' ||\n this.options[i] === 's' ||\n this.options[i] === 'u'\n )\n ) {\n throw new Error('the regular expression options [' + this.options[i] + '] is not supported');\n }\n }\n}\n\nmodule.exports = BSONRegExp;\nmodule.exports.BSONRegExp = BSONRegExp;\n","// Custom inspect property name / symbol.\nvar inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect';\n\n/**\n * A class representation of the BSON Symbol type.\n *\n * @class\n * @deprecated\n * @param {string} value the string representing the symbol.\n * @return {Symbol}\n */\nfunction Symbol(value) {\n if (!(this instanceof Symbol)) return new Symbol(value);\n this._bsontype = 'Symbol';\n this.value = value;\n}\n\n/**\n * Access the wrapped string value.\n *\n * @method\n * @return {String} returns the wrapped string.\n */\nSymbol.prototype.valueOf = function() {\n return this.value;\n};\n\n/**\n * @ignore\n */\nSymbol.prototype.toString = function() {\n return this.value;\n};\n\n/**\n * @ignore\n */\nSymbol.prototype[inspect] = function() {\n return this.value;\n};\n\n/**\n * @ignore\n */\nSymbol.prototype.toJSON = function() {\n return this.value;\n};\n\nmodule.exports = Symbol;\nmodule.exports.Symbol = Symbol;\n","// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Copyright 2009 Google Inc. All Rights Reserved\n\n/**\n * This type is for INTERNAL use in MongoDB only and should not be used in applications.\n * The appropriate corresponding type is the JavaScript Date type.\n * \n * Defines a Timestamp class for representing a 64-bit two's-complement\n * integer value, which faithfully simulates the behavior of a Java \"Timestamp\". This\n * implementation is derived from TimestampLib in GWT.\n *\n * Constructs a 64-bit two's-complement integer, given its low and high 32-bit\n * values as *signed* integers. See the from* functions below for more\n * convenient ways of constructing Timestamps.\n *\n * The internal representation of a Timestamp is the two given signed, 32-bit values.\n * We use 32-bit pieces because these are the size of integers on which\n * Javascript performs bit-operations. For operations like addition and\n * multiplication, we split each number into 16-bit pieces, which can easily be\n * multiplied within Javascript's floating-point representation without overflow\n * or change in sign.\n *\n * In the algorithms below, we frequently reduce the negative case to the\n * positive case by negating the input(s) and then post-processing the result.\n * Note that we must ALWAYS check specially whether those values are MIN_VALUE\n * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as\n * a positive number, it overflows back into a negative). Not handling this\n * case would often result in infinite recursion.\n *\n * @class\n * @param {number} low the low (signed) 32 bits of the Timestamp.\n * @param {number} high the high (signed) 32 bits of the Timestamp.\n */\nfunction Timestamp(low, high) {\n if (!(this instanceof Timestamp)) return new Timestamp(low, high);\n this._bsontype = 'Timestamp';\n /**\n * @type {number}\n * @ignore\n */\n this.low_ = low | 0; // force into 32 signed bits.\n\n /**\n * @type {number}\n * @ignore\n */\n this.high_ = high | 0; // force into 32 signed bits.\n}\n\n/**\n * Return the int value.\n *\n * @return {number} the value, assuming it is a 32-bit integer.\n */\nTimestamp.prototype.toInt = function() {\n return this.low_;\n};\n\n/**\n * Return the Number value.\n *\n * @method\n * @return {number} the closest floating-point representation to this value.\n */\nTimestamp.prototype.toNumber = function() {\n return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned();\n};\n\n/**\n * Return the JSON value.\n *\n * @method\n * @return {string} the JSON representation.\n */\nTimestamp.prototype.toJSON = function() {\n return this.toString();\n};\n\n/**\n * Return the String value.\n *\n * @method\n * @param {number} [opt_radix] the radix in which the text should be written.\n * @return {string} the textual representation of this value.\n */\nTimestamp.prototype.toString = function(opt_radix) {\n var radix = opt_radix || 10;\n if (radix < 2 || 36 < radix) {\n throw Error('radix out of range: ' + radix);\n }\n\n if (this.isZero()) {\n return '0';\n }\n\n if (this.isNegative()) {\n if (this.equals(Timestamp.MIN_VALUE)) {\n // We need to change the Timestamp value before it can be negated, so we remove\n // the bottom-most digit in this base and then recurse to do the rest.\n var radixTimestamp = Timestamp.fromNumber(radix);\n var div = this.div(radixTimestamp);\n var rem = div.multiply(radixTimestamp).subtract(this);\n return div.toString(radix) + rem.toInt().toString(radix);\n } else {\n return '-' + this.negate().toString(radix);\n }\n }\n\n // Do several (6) digits each time through the loop, so as to\n // minimize the calls to the very expensive emulated div.\n var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6));\n\n rem = this;\n var result = '';\n\n while (!rem.isZero()) {\n var remDiv = rem.div(radixToPower);\n var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();\n var digits = intval.toString(radix);\n\n rem = remDiv;\n if (rem.isZero()) {\n return digits + result;\n } else {\n while (digits.length < 6) {\n digits = '0' + digits;\n }\n result = '' + digits + result;\n }\n }\n};\n\n/**\n * Return the high 32-bits value.\n *\n * @method\n * @return {number} the high 32-bits as a signed value.\n */\nTimestamp.prototype.getHighBits = function() {\n return this.high_;\n};\n\n/**\n * Return the low 32-bits value.\n *\n * @method\n * @return {number} the low 32-bits as a signed value.\n */\nTimestamp.prototype.getLowBits = function() {\n return this.low_;\n};\n\n/**\n * Return the low unsigned 32-bits value.\n *\n * @method\n * @return {number} the low 32-bits as an unsigned value.\n */\nTimestamp.prototype.getLowBitsUnsigned = function() {\n return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_;\n};\n\n/**\n * Returns the number of bits needed to represent the absolute value of this Timestamp.\n *\n * @method\n * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp.\n */\nTimestamp.prototype.getNumBitsAbs = function() {\n if (this.isNegative()) {\n if (this.equals(Timestamp.MIN_VALUE)) {\n return 64;\n } else {\n return this.negate().getNumBitsAbs();\n }\n } else {\n var val = this.high_ !== 0 ? this.high_ : this.low_;\n for (var bit = 31; bit > 0; bit--) {\n if ((val & (1 << bit)) !== 0) {\n break;\n }\n }\n return this.high_ !== 0 ? bit + 33 : bit + 1;\n }\n};\n\n/**\n * Return whether this value is zero.\n *\n * @method\n * @return {boolean} whether this value is zero.\n */\nTimestamp.prototype.isZero = function() {\n return this.high_ === 0 && this.low_ === 0;\n};\n\n/**\n * Return whether this value is negative.\n *\n * @method\n * @return {boolean} whether this value is negative.\n */\nTimestamp.prototype.isNegative = function() {\n return this.high_ < 0;\n};\n\n/**\n * Return whether this value is odd.\n *\n * @method\n * @return {boolean} whether this value is odd.\n */\nTimestamp.prototype.isOdd = function() {\n return (this.low_ & 1) === 1;\n};\n\n/**\n * Return whether this Timestamp equals the other\n *\n * @method\n * @param {Timestamp} other Timestamp to compare against.\n * @return {boolean} whether this Timestamp equals the other\n */\nTimestamp.prototype.equals = function(other) {\n return this.high_ === other.high_ && this.low_ === other.low_;\n};\n\n/**\n * Return whether this Timestamp does not equal the other.\n *\n * @method\n * @param {Timestamp} other Timestamp to compare against.\n * @return {boolean} whether this Timestamp does not equal the other.\n */\nTimestamp.prototype.notEquals = function(other) {\n return this.high_ !== other.high_ || this.low_ !== other.low_;\n};\n\n/**\n * Return whether this Timestamp is less than the other.\n *\n * @method\n * @param {Timestamp} other Timestamp to compare against.\n * @return {boolean} whether this Timestamp is less than the other.\n */\nTimestamp.prototype.lessThan = function(other) {\n return this.compare(other) < 0;\n};\n\n/**\n * Return whether this Timestamp is less than or equal to the other.\n *\n * @method\n * @param {Timestamp} other Timestamp to compare against.\n * @return {boolean} whether this Timestamp is less than or equal to the other.\n */\nTimestamp.prototype.lessThanOrEqual = function(other) {\n return this.compare(other) <= 0;\n};\n\n/**\n * Return whether this Timestamp is greater than the other.\n *\n * @method\n * @param {Timestamp} other Timestamp to compare against.\n * @return {boolean} whether this Timestamp is greater than the other.\n */\nTimestamp.prototype.greaterThan = function(other) {\n return this.compare(other) > 0;\n};\n\n/**\n * Return whether this Timestamp is greater than or equal to the other.\n *\n * @method\n * @param {Timestamp} other Timestamp to compare against.\n * @return {boolean} whether this Timestamp is greater than or equal to the other.\n */\nTimestamp.prototype.greaterThanOrEqual = function(other) {\n return this.compare(other) >= 0;\n};\n\n/**\n * Compares this Timestamp with the given one.\n *\n * @method\n * @param {Timestamp} other Timestamp to compare against.\n * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.\n */\nTimestamp.prototype.compare = function(other) {\n if (this.equals(other)) {\n return 0;\n }\n\n var thisNeg = this.isNegative();\n var otherNeg = other.isNegative();\n if (thisNeg && !otherNeg) {\n return -1;\n }\n if (!thisNeg && otherNeg) {\n return 1;\n }\n\n // at this point, the signs are the same, so subtraction will not overflow\n if (this.subtract(other).isNegative()) {\n return -1;\n } else {\n return 1;\n }\n};\n\n/**\n * The negation of this value.\n *\n * @method\n * @return {Timestamp} the negation of this value.\n */\nTimestamp.prototype.negate = function() {\n if (this.equals(Timestamp.MIN_VALUE)) {\n return Timestamp.MIN_VALUE;\n } else {\n return this.not().add(Timestamp.ONE);\n }\n};\n\n/**\n * Returns the sum of this and the given Timestamp.\n *\n * @method\n * @param {Timestamp} other Timestamp to add to this one.\n * @return {Timestamp} the sum of this and the given Timestamp.\n */\nTimestamp.prototype.add = function(other) {\n // Divide each number into 4 chunks of 16 bits, and then sum the chunks.\n\n var a48 = this.high_ >>> 16;\n var a32 = this.high_ & 0xffff;\n var a16 = this.low_ >>> 16;\n var a00 = this.low_ & 0xffff;\n\n var b48 = other.high_ >>> 16;\n var b32 = other.high_ & 0xffff;\n var b16 = other.low_ >>> 16;\n var b00 = other.low_ & 0xffff;\n\n var c48 = 0,\n c32 = 0,\n c16 = 0,\n c00 = 0;\n c00 += a00 + b00;\n c16 += c00 >>> 16;\n c00 &= 0xffff;\n c16 += a16 + b16;\n c32 += c16 >>> 16;\n c16 &= 0xffff;\n c32 += a32 + b32;\n c48 += c32 >>> 16;\n c32 &= 0xffff;\n c48 += a48 + b48;\n c48 &= 0xffff;\n return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);\n};\n\n/**\n * Returns the difference of this and the given Timestamp.\n *\n * @method\n * @param {Timestamp} other Timestamp to subtract from this.\n * @return {Timestamp} the difference of this and the given Timestamp.\n */\nTimestamp.prototype.subtract = function(other) {\n return this.add(other.negate());\n};\n\n/**\n * Returns the product of this and the given Timestamp.\n *\n * @method\n * @param {Timestamp} other Timestamp to multiply with this.\n * @return {Timestamp} the product of this and the other.\n */\nTimestamp.prototype.multiply = function(other) {\n if (this.isZero()) {\n return Timestamp.ZERO;\n } else if (other.isZero()) {\n return Timestamp.ZERO;\n }\n\n if (this.equals(Timestamp.MIN_VALUE)) {\n return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;\n } else if (other.equals(Timestamp.MIN_VALUE)) {\n return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;\n }\n\n if (this.isNegative()) {\n if (other.isNegative()) {\n return this.negate().multiply(other.negate());\n } else {\n return this.negate()\n .multiply(other)\n .negate();\n }\n } else if (other.isNegative()) {\n return this.multiply(other.negate()).negate();\n }\n\n // If both Timestamps are small, use float multiplication\n if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) {\n return Timestamp.fromNumber(this.toNumber() * other.toNumber());\n }\n\n // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products.\n // We can skip products that would overflow.\n\n var a48 = this.high_ >>> 16;\n var a32 = this.high_ & 0xffff;\n var a16 = this.low_ >>> 16;\n var a00 = this.low_ & 0xffff;\n\n var b48 = other.high_ >>> 16;\n var b32 = other.high_ & 0xffff;\n var b16 = other.low_ >>> 16;\n var b00 = other.low_ & 0xffff;\n\n var c48 = 0,\n c32 = 0,\n c16 = 0,\n c00 = 0;\n c00 += a00 * b00;\n c16 += c00 >>> 16;\n c00 &= 0xffff;\n c16 += a16 * b00;\n c32 += c16 >>> 16;\n c16 &= 0xffff;\n c16 += a00 * b16;\n c32 += c16 >>> 16;\n c16 &= 0xffff;\n c32 += a32 * b00;\n c48 += c32 >>> 16;\n c32 &= 0xffff;\n c32 += a16 * b16;\n c48 += c32 >>> 16;\n c32 &= 0xffff;\n c32 += a00 * b32;\n c48 += c32 >>> 16;\n c32 &= 0xffff;\n c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;\n c48 &= 0xffff;\n return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);\n};\n\n/**\n * Returns this Timestamp divided by the given one.\n *\n * @method\n * @param {Timestamp} other Timestamp by which to divide.\n * @return {Timestamp} this Timestamp divided by the given one.\n */\nTimestamp.prototype.div = function(other) {\n if (other.isZero()) {\n throw Error('division by zero');\n } else if (this.isZero()) {\n return Timestamp.ZERO;\n }\n\n if (this.equals(Timestamp.MIN_VALUE)) {\n if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) {\n return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE\n } else if (other.equals(Timestamp.MIN_VALUE)) {\n return Timestamp.ONE;\n } else {\n // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.\n var halfThis = this.shiftRight(1);\n var approx = halfThis.div(other).shiftLeft(1);\n if (approx.equals(Timestamp.ZERO)) {\n return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE;\n } else {\n var rem = this.subtract(other.multiply(approx));\n var result = approx.add(rem.div(other));\n return result;\n }\n }\n } else if (other.equals(Timestamp.MIN_VALUE)) {\n return Timestamp.ZERO;\n }\n\n if (this.isNegative()) {\n if (other.isNegative()) {\n return this.negate().div(other.negate());\n } else {\n return this.negate()\n .div(other)\n .negate();\n }\n } else if (other.isNegative()) {\n return this.div(other.negate()).negate();\n }\n\n // Repeat the following until the remainder is less than other: find a\n // floating-point that approximates remainder / other *from below*, add this\n // into the result, and subtract it from the remainder. It is critical that\n // the approximate value is less than or equal to the real value so that the\n // remainder never becomes negative.\n var res = Timestamp.ZERO;\n rem = this;\n while (rem.greaterThanOrEqual(other)) {\n // Approximate the result of division. This may be a little greater or\n // smaller than the actual value.\n approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));\n\n // We will tweak the approximate result by changing it in the 48-th digit or\n // the smallest non-fractional digit, whichever is larger.\n var log2 = Math.ceil(Math.log(approx) / Math.LN2);\n var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);\n\n // Decrease the approximation until it is smaller than the remainder. Note\n // that if it is too large, the product overflows and is negative.\n var approxRes = Timestamp.fromNumber(approx);\n var approxRem = approxRes.multiply(other);\n while (approxRem.isNegative() || approxRem.greaterThan(rem)) {\n approx -= delta;\n approxRes = Timestamp.fromNumber(approx);\n approxRem = approxRes.multiply(other);\n }\n\n // We know the answer can't be zero... and actually, zero would cause\n // infinite recursion since we would make no progress.\n if (approxRes.isZero()) {\n approxRes = Timestamp.ONE;\n }\n\n res = res.add(approxRes);\n rem = rem.subtract(approxRem);\n }\n return res;\n};\n\n/**\n * Returns this Timestamp modulo the given one.\n *\n * @method\n * @param {Timestamp} other Timestamp by which to mod.\n * @return {Timestamp} this Timestamp modulo the given one.\n */\nTimestamp.prototype.modulo = function(other) {\n return this.subtract(this.div(other).multiply(other));\n};\n\n/**\n * The bitwise-NOT of this value.\n *\n * @method\n * @return {Timestamp} the bitwise-NOT of this value.\n */\nTimestamp.prototype.not = function() {\n return Timestamp.fromBits(~this.low_, ~this.high_);\n};\n\n/**\n * Returns the bitwise-AND of this Timestamp and the given one.\n *\n * @method\n * @param {Timestamp} other the Timestamp with which to AND.\n * @return {Timestamp} the bitwise-AND of this and the other.\n */\nTimestamp.prototype.and = function(other) {\n return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_);\n};\n\n/**\n * Returns the bitwise-OR of this Timestamp and the given one.\n *\n * @method\n * @param {Timestamp} other the Timestamp with which to OR.\n * @return {Timestamp} the bitwise-OR of this and the other.\n */\nTimestamp.prototype.or = function(other) {\n return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_);\n};\n\n/**\n * Returns the bitwise-XOR of this Timestamp and the given one.\n *\n * @method\n * @param {Timestamp} other the Timestamp with which to XOR.\n * @return {Timestamp} the bitwise-XOR of this and the other.\n */\nTimestamp.prototype.xor = function(other) {\n return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_);\n};\n\n/**\n * Returns this Timestamp with bits shifted to the left by the given amount.\n *\n * @method\n * @param {number} numBits the number of bits by which to shift.\n * @return {Timestamp} this shifted to the left by the given amount.\n */\nTimestamp.prototype.shiftLeft = function(numBits) {\n numBits &= 63;\n if (numBits === 0) {\n return this;\n } else {\n var low = this.low_;\n if (numBits < 32) {\n var high = this.high_;\n return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits)));\n } else {\n return Timestamp.fromBits(0, low << (numBits - 32));\n }\n }\n};\n\n/**\n * Returns this Timestamp with bits shifted to the right by the given amount.\n *\n * @method\n * @param {number} numBits the number of bits by which to shift.\n * @return {Timestamp} this shifted to the right by the given amount.\n */\nTimestamp.prototype.shiftRight = function(numBits) {\n numBits &= 63;\n if (numBits === 0) {\n return this;\n } else {\n var high = this.high_;\n if (numBits < 32) {\n var low = this.low_;\n return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits);\n } else {\n return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1);\n }\n }\n};\n\n/**\n * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.\n *\n * @method\n * @param {number} numBits the number of bits by which to shift.\n * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits.\n */\nTimestamp.prototype.shiftRightUnsigned = function(numBits) {\n numBits &= 63;\n if (numBits === 0) {\n return this;\n } else {\n var high = this.high_;\n if (numBits < 32) {\n var low = this.low_;\n return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits);\n } else if (numBits === 32) {\n return Timestamp.fromBits(high, 0);\n } else {\n return Timestamp.fromBits(high >>> (numBits - 32), 0);\n }\n }\n};\n\n/**\n * Returns a Timestamp representing the given (32-bit) integer value.\n *\n * @method\n * @param {number} value the 32-bit integer in question.\n * @return {Timestamp} the corresponding Timestamp value.\n */\nTimestamp.fromInt = function(value) {\n if (-128 <= value && value < 128) {\n var cachedObj = Timestamp.INT_CACHE_[value];\n if (cachedObj) {\n return cachedObj;\n }\n }\n\n var obj = new Timestamp(value | 0, value < 0 ? -1 : 0);\n if (-128 <= value && value < 128) {\n Timestamp.INT_CACHE_[value] = obj;\n }\n return obj;\n};\n\n/**\n * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned.\n *\n * @method\n * @param {number} value the number in question.\n * @return {Timestamp} the corresponding Timestamp value.\n */\nTimestamp.fromNumber = function(value) {\n if (isNaN(value) || !isFinite(value)) {\n return Timestamp.ZERO;\n } else if (value <= -Timestamp.TWO_PWR_63_DBL_) {\n return Timestamp.MIN_VALUE;\n } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) {\n return Timestamp.MAX_VALUE;\n } else if (value < 0) {\n return Timestamp.fromNumber(-value).negate();\n } else {\n return new Timestamp(\n (value % Timestamp.TWO_PWR_32_DBL_) | 0,\n (value / Timestamp.TWO_PWR_32_DBL_) | 0\n );\n }\n};\n\n/**\n * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.\n *\n * @method\n * @param {number} lowBits the low 32-bits.\n * @param {number} highBits the high 32-bits.\n * @return {Timestamp} the corresponding Timestamp value.\n */\nTimestamp.fromBits = function(lowBits, highBits) {\n return new Timestamp(lowBits, highBits);\n};\n\n/**\n * Returns a Timestamp representation of the given string, written using the given radix.\n *\n * @method\n * @param {string} str the textual representation of the Timestamp.\n * @param {number} opt_radix the radix in which the text is written.\n * @return {Timestamp} the corresponding Timestamp value.\n */\nTimestamp.fromString = function(str, opt_radix) {\n if (str.length === 0) {\n throw Error('number format error: empty string');\n }\n\n var radix = opt_radix || 10;\n if (radix < 2 || 36 < radix) {\n throw Error('radix out of range: ' + radix);\n }\n\n if (str.charAt(0) === '-') {\n return Timestamp.fromString(str.substring(1), radix).negate();\n } else if (str.indexOf('-') >= 0) {\n throw Error('number format error: interior \"-\" character: ' + str);\n }\n\n // Do several (8) digits each time through the loop, so as to\n // minimize the calls to the very expensive emulated div.\n var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8));\n\n var result = Timestamp.ZERO;\n for (var i = 0; i < str.length; i += 8) {\n var size = Math.min(8, str.length - i);\n var value = parseInt(str.substring(i, i + size), radix);\n if (size < 8) {\n var power = Timestamp.fromNumber(Math.pow(radix, size));\n result = result.multiply(power).add(Timestamp.fromNumber(value));\n } else {\n result = result.multiply(radixToPower);\n result = result.add(Timestamp.fromNumber(value));\n }\n }\n return result;\n};\n\n// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the\n// from* methods on which they depend.\n\n/**\n * A cache of the Timestamp representations of small integer values.\n * @type {Object}\n * @ignore\n */\nTimestamp.INT_CACHE_ = {};\n\n// NOTE: the compiler should inline these constant values below and then remove\n// these variables, so there should be no runtime penalty for these.\n\n/**\n * Number used repeated below in calculations. This must appear before the\n * first call to any from* function below.\n * @type {number}\n * @ignore\n */\nTimestamp.TWO_PWR_16_DBL_ = 1 << 16;\n\n/**\n * @type {number}\n * @ignore\n */\nTimestamp.TWO_PWR_24_DBL_ = 1 << 24;\n\n/**\n * @type {number}\n * @ignore\n */\nTimestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_;\n\n/**\n * @type {number}\n * @ignore\n */\nTimestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2;\n\n/**\n * @type {number}\n * @ignore\n */\nTimestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_;\n\n/**\n * @type {number}\n * @ignore\n */\nTimestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_;\n\n/**\n * @type {number}\n * @ignore\n */\nTimestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2;\n\n/** @type {Timestamp} */\nTimestamp.ZERO = Timestamp.fromInt(0);\n\n/** @type {Timestamp} */\nTimestamp.ONE = Timestamp.fromInt(1);\n\n/** @type {Timestamp} */\nTimestamp.NEG_ONE = Timestamp.fromInt(-1);\n\n/** @type {Timestamp} */\nTimestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0);\n\n/** @type {Timestamp} */\nTimestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0);\n\n/**\n * @type {Timestamp}\n * @ignore\n */\nTimestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24);\n\n/**\n * Expose.\n */\nmodule.exports = Timestamp;\nmodule.exports.Timestamp = Timestamp;\n","'use strict';\n\nconst preserveCamelCase = string => {\n\tlet isLastCharLower = false;\n\tlet isLastCharUpper = false;\n\tlet isLastLastCharUpper = false;\n\n\tfor (let i = 0; i < string.length; i++) {\n\t\tconst character = string[i];\n\n\t\tif (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) {\n\t\t\tstring = string.slice(0, i) + '-' + string.slice(i);\n\t\t\tisLastCharLower = false;\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = true;\n\t\t\ti++;\n\t\t} else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) {\n\t\t\tstring = string.slice(0, i - 1) + '-' + string.slice(i - 1);\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = false;\n\t\t\tisLastCharLower = true;\n\t\t} else {\n\t\t\tisLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character;\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character;\n\t\t}\n\t}\n\n\treturn string;\n};\n\nconst camelCase = (input, options) => {\n\tif (!(typeof input === 'string' || Array.isArray(input))) {\n\t\tthrow new TypeError('Expected the input to be `string | string[]`');\n\t}\n\n\toptions = Object.assign({\n\t\tpascalCase: false\n\t}, options);\n\n\tconst postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x;\n\n\tif (Array.isArray(input)) {\n\t\tinput = input.map(x => x.trim())\n\t\t\t.filter(x => x.length)\n\t\t\t.join('-');\n\t} else {\n\t\tinput = input.trim();\n\t}\n\n\tif (input.length === 0) {\n\t\treturn '';\n\t}\n\n\tif (input.length === 1) {\n\t\treturn options.pascalCase ? input.toUpperCase() : input.toLowerCase();\n\t}\n\n\tconst hasUpperCase = input !== input.toLowerCase();\n\n\tif (hasUpperCase) {\n\t\tinput = preserveCamelCase(input);\n\t}\n\n\tinput = input\n\t\t.replace(/^[_.\\- ]+/, '')\n\t\t.toLowerCase()\n\t\t.replace(/[_.\\- ]+(\\w|$)/g, (_, p1) => p1.toUpperCase())\n\t\t.replace(/\\d+(\\w|$)/g, m => m.toUpperCase());\n\n\treturn postProcess(input);\n};\n\nmodule.exports = camelCase;\n// TODO: Remove this for the next major release\nmodule.exports.default = camelCase;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n","/*\n * Date Format 1.2.3\n * (c) 2007-2009 Steven Levithan \n * MIT license\n *\n * Includes enhancements by Scott Trenda \n * and Kris Kowal \n *\n * Accepts a date, a mask, or a date and a mask.\n * Returns a formatted version of the given date.\n * The date defaults to the current date/time.\n * The mask defaults to dateFormat.masks.default.\n */\n\n(function(global) {\n 'use strict';\n\n var dateFormat = (function() {\n var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\\1?|[LloSZWN]|\"[^\"]*\"|'[^']*'/g;\n var timezone = /\\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\\d{4})?)\\b/g;\n var timezoneClip = /[^-+\\dA-Z]/g;\n \n // Regexes and supporting functions are cached through closure\n return function (date, mask, utc, gmt) {\n \n // You can't provide utc if you skip other args (use the 'UTC:' mask prefix)\n if (arguments.length === 1 && kindOf(date) === 'string' && !/\\d/.test(date)) {\n mask = date;\n date = undefined;\n }\n \n date = date || new Date;\n \n if(!(date instanceof Date)) {\n date = new Date(date);\n }\n \n if (isNaN(date)) {\n throw TypeError('Invalid date');\n }\n \n mask = String(dateFormat.masks[mask] || mask || dateFormat.masks['default']);\n \n // Allow setting the utc/gmt argument via the mask\n var maskSlice = mask.slice(0, 4);\n if (maskSlice === 'UTC:' || maskSlice === 'GMT:') {\n mask = mask.slice(4);\n utc = true;\n if (maskSlice === 'GMT:') {\n gmt = true;\n }\n }\n \n var _ = utc ? 'getUTC' : 'get';\n var d = date[_ + 'Date']();\n var D = date[_ + 'Day']();\n var m = date[_ + 'Month']();\n var y = date[_ + 'FullYear']();\n var H = date[_ + 'Hours']();\n var M = date[_ + 'Minutes']();\n var s = date[_ + 'Seconds']();\n var L = date[_ + 'Milliseconds']();\n var o = utc ? 0 : date.getTimezoneOffset();\n var W = getWeek(date);\n var N = getDayOfWeek(date);\n var flags = {\n d: d,\n dd: pad(d),\n ddd: dateFormat.i18n.dayNames[D],\n dddd: dateFormat.i18n.dayNames[D + 7],\n m: m + 1,\n mm: pad(m + 1),\n mmm: dateFormat.i18n.monthNames[m],\n mmmm: dateFormat.i18n.monthNames[m + 12],\n yy: String(y).slice(2),\n yyyy: y,\n h: H % 12 || 12,\n hh: pad(H % 12 || 12),\n H: H,\n HH: pad(H),\n M: M,\n MM: pad(M),\n s: s,\n ss: pad(s),\n l: pad(L, 3),\n L: pad(Math.round(L / 10)),\n t: H < 12 ? dateFormat.i18n.timeNames[0] : dateFormat.i18n.timeNames[1],\n tt: H < 12 ? dateFormat.i18n.timeNames[2] : dateFormat.i18n.timeNames[3],\n T: H < 12 ? dateFormat.i18n.timeNames[4] : dateFormat.i18n.timeNames[5],\n TT: H < 12 ? dateFormat.i18n.timeNames[6] : dateFormat.i18n.timeNames[7],\n Z: gmt ? 'GMT' : utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''),\n o: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),\n S: ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10],\n W: W,\n N: N\n };\n \n return mask.replace(token, function (match) {\n if (match in flags) {\n return flags[match];\n }\n return match.slice(1, match.length - 1);\n });\n };\n })();\n\n dateFormat.masks = {\n 'default': 'ddd mmm dd yyyy HH:MM:ss',\n 'shortDate': 'm/d/yy',\n 'mediumDate': 'mmm d, yyyy',\n 'longDate': 'mmmm d, yyyy',\n 'fullDate': 'dddd, mmmm d, yyyy',\n 'shortTime': 'h:MM TT',\n 'mediumTime': 'h:MM:ss TT',\n 'longTime': 'h:MM:ss TT Z',\n 'isoDate': 'yyyy-mm-dd',\n 'isoTime': 'HH:MM:ss',\n 'isoDateTime': 'yyyy-mm-dd\\'T\\'HH:MM:sso',\n 'isoUtcDateTime': 'UTC:yyyy-mm-dd\\'T\\'HH:MM:ss\\'Z\\'',\n 'expiresHeaderFormat': 'ddd, dd mmm yyyy HH:MM:ss Z'\n };\n\n // Internationalization strings\n dateFormat.i18n = {\n dayNames: [\n 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',\n 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'\n ],\n monthNames: [\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',\n 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'\n ],\n timeNames: [\n 'a', 'p', 'am', 'pm', 'A', 'P', 'AM', 'PM'\n ]\n };\n\nfunction pad(val, len) {\n val = String(val);\n len = len || 2;\n while (val.length < len) {\n val = '0' + val;\n }\n return val;\n}\n\n/**\n * Get the ISO 8601 week number\n * Based on comments from\n * http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html\n *\n * @param {Object} `date`\n * @return {Number}\n */\nfunction getWeek(date) {\n // Remove time components of date\n var targetThursday = new Date(date.getFullYear(), date.getMonth(), date.getDate());\n\n // Change date to Thursday same week\n targetThursday.setDate(targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3);\n\n // Take January 4th as it is always in week 1 (see ISO 8601)\n var firstThursday = new Date(targetThursday.getFullYear(), 0, 4);\n\n // Change date to Thursday same week\n firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3);\n\n // Check if daylight-saving-time-switch occurred and correct for it\n var ds = targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset();\n targetThursday.setHours(targetThursday.getHours() - ds);\n\n // Number of weeks between target Thursday and first Thursday\n var weekDiff = (targetThursday - firstThursday) / (86400000*7);\n return 1 + Math.floor(weekDiff);\n}\n\n/**\n * Get ISO-8601 numeric representation of the day of the week\n * 1 (for Monday) through 7 (for Sunday)\n * \n * @param {Object} `date`\n * @return {Number}\n */\nfunction getDayOfWeek(date) {\n var dow = date.getDay();\n if(dow === 0) {\n dow = 7;\n }\n return dow;\n}\n\n/**\n * kind-of shortcut\n * @param {*} val\n * @return {String}\n */\nfunction kindOf(val) {\n if (val === null) {\n return 'null';\n }\n\n if (val === undefined) {\n return 'undefined';\n }\n\n if (typeof val !== 'object') {\n return typeof val;\n }\n\n if (Array.isArray(val)) {\n return 'array';\n }\n\n return {}.toString.call(val)\n .slice(8, -1).toLowerCase();\n};\n\n\n\n if (typeof define === 'function' && define.amd) {\n define(function () {\n return dateFormat;\n });\n } else if (typeof exports === 'object') {\n module.exports = dateFormat;\n } else {\n global.dateFormat = dateFormat;\n }\n})(this);\n","'use strict';\nmodule.exports = function (str, sep) {\n\tif (typeof str !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\tsep = typeof sep === 'undefined' ? '_' : sep;\n\n\treturn str\n\t\t.replace(/([a-z\\d])([A-Z])/g, '$1' + sep + '$2')\n\t\t.replace(/([A-Z]+)([A-Z][a-z\\d]+)/g, '$1' + sep + '$2')\n\t\t.toLowerCase();\n};\n","'use strict';\n\n/**\n * Custom implementation of a double ended queue.\n */\nfunction Denque(array) {\n this._head = 0;\n this._tail = 0;\n this._capacityMask = 0x3;\n this._list = new Array(4);\n if (Array.isArray(array)) {\n this._fromArray(array);\n }\n}\n\n/**\n * -------------\n * PUBLIC API\n * -------------\n */\n\n/**\n * Returns the item at the specified index from the list.\n * 0 is the first element, 1 is the second, and so on...\n * Elements at negative values are that many from the end: -1 is one before the end\n * (the last element), -2 is two before the end (one before last), etc.\n * @param index\n * @returns {*}\n */\nDenque.prototype.peekAt = function peekAt(index) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n var len = this.size();\n if (i >= len || i < -len) return undefined;\n if (i < 0) i += len;\n i = (this._head + i) & this._capacityMask;\n return this._list[i];\n};\n\n/**\n * Alias for peakAt()\n * @param i\n * @returns {*}\n */\nDenque.prototype.get = function get(i) {\n return this.peekAt(i);\n};\n\n/**\n * Returns the first item in the list without removing it.\n * @returns {*}\n */\nDenque.prototype.peek = function peek() {\n if (this._head === this._tail) return undefined;\n return this._list[this._head];\n};\n\n/**\n * Alias for peek()\n * @returns {*}\n */\nDenque.prototype.peekFront = function peekFront() {\n return this.peek();\n};\n\n/**\n * Returns the item that is at the back of the queue without removing it.\n * Uses peekAt(-1)\n */\nDenque.prototype.peekBack = function peekBack() {\n return this.peekAt(-1);\n};\n\n/**\n * Returns the current length of the queue\n * @return {Number}\n */\nObject.defineProperty(Denque.prototype, 'length', {\n get: function length() {\n return this.size();\n }\n});\n\n/**\n * Return the number of items on the list, or 0 if empty.\n * @returns {number}\n */\nDenque.prototype.size = function size() {\n if (this._head === this._tail) return 0;\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Add an item at the beginning of the list.\n * @param item\n */\nDenque.prototype.unshift = function unshift(item) {\n if (item === undefined) return this.size();\n var len = this._list.length;\n this._head = (this._head - 1 + len) & this._capacityMask;\n this._list[this._head] = item;\n if (this._tail === this._head) this._growArray();\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the first item on the list,\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.shift = function shift() {\n var head = this._head;\n if (head === this._tail) return undefined;\n var item = this._list[head];\n this._list[head] = undefined;\n this._head = (head + 1) & this._capacityMask;\n if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray();\n return item;\n};\n\n/**\n * Add an item to the bottom of the list.\n * @param item\n */\nDenque.prototype.push = function push(item) {\n if (item === undefined) return this.size();\n var tail = this._tail;\n this._list[tail] = item;\n this._tail = (tail + 1) & this._capacityMask;\n if (this._tail === this._head) {\n this._growArray();\n }\n\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the last item on the list.\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.pop = function pop() {\n var tail = this._tail;\n if (tail === this._head) return undefined;\n var len = this._list.length;\n this._tail = (tail - 1 + len) & this._capacityMask;\n var item = this._list[this._tail];\n this._list[this._tail] = undefined;\n if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray();\n return item;\n};\n\n/**\n * Remove and return the item at the specified index from the list.\n * Returns undefined if the list is empty.\n * @param index\n * @returns {*}\n */\nDenque.prototype.removeOne = function removeOne(index) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n if (this._head === this._tail) return void 0;\n var size = this.size();\n var len = this._list.length;\n if (i >= size || i < -size) return void 0;\n if (i < 0) i += size;\n i = (this._head + i) & this._capacityMask;\n var item = this._list[i];\n var k;\n if (index < size / 2) {\n for (k = index; k > 0; k--) {\n this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask];\n }\n this._list[i] = void 0;\n this._head = (this._head + 1 + len) & this._capacityMask;\n } else {\n for (k = size - 1 - index; k > 0; k--) {\n this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask];\n }\n this._list[i] = void 0;\n this._tail = (this._tail - 1 + len) & this._capacityMask;\n }\n return item;\n};\n\n/**\n * Remove number of items from the specified index from the list.\n * Returns array of removed items.\n * Returns undefined if the list is empty.\n * @param index\n * @param count\n * @returns {array}\n */\nDenque.prototype.remove = function remove(index, count) {\n var i = index;\n var removed;\n var del_count = count;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n if (this._head === this._tail) return void 0;\n var size = this.size();\n var len = this._list.length;\n if (i >= size || i < -size || count < 1) return void 0;\n if (i < 0) i += size;\n if (count === 1 || !count) {\n removed = new Array(1);\n removed[0] = this.removeOne(i);\n return removed;\n }\n if (i === 0 && i + count >= size) {\n removed = this.toArray();\n this.clear();\n return removed;\n }\n if (i + count > size) count = size - i;\n var k;\n removed = new Array(count);\n for (k = 0; k < count; k++) {\n removed[k] = this._list[(this._head + i + k) & this._capacityMask];\n }\n i = (this._head + i) & this._capacityMask;\n if (index + count === size) {\n this._tail = (this._tail - count + len) & this._capacityMask;\n for (k = count; k > 0; k--) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n }\n return removed;\n }\n if (index === 0) {\n this._head = (this._head + count + len) & this._capacityMask;\n for (k = count - 1; k > 0; k--) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n }\n return removed;\n }\n if (i < size / 2) {\n this._head = (this._head + index + count + len) & this._capacityMask;\n for (k = index; k > 0; k--) {\n this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]);\n }\n i = (this._head - 1 + len) & this._capacityMask;\n while (del_count > 0) {\n this._list[i = (i - 1 + len) & this._capacityMask] = void 0;\n del_count--;\n }\n if (index < 0) this._tail = i;\n } else {\n this._tail = i;\n i = (i + count + len) & this._capacityMask;\n for (k = size - (count + index); k > 0; k--) {\n this.push(this._list[i++]);\n }\n i = this._tail;\n while (del_count > 0) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n del_count--;\n }\n }\n if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray();\n return removed;\n};\n\n/**\n * Native splice implementation.\n * Remove number of items from the specified index from the list and/or add new elements.\n * Returns array of removed items or empty array if count == 0.\n * Returns undefined if the list is empty.\n *\n * @param index\n * @param count\n * @param {...*} [elements]\n * @returns {array}\n */\nDenque.prototype.splice = function splice(index, count) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n var size = this.size();\n if (i < 0) i += size;\n if (i > size) return void 0;\n if (arguments.length > 2) {\n var k;\n var temp;\n var removed;\n var arg_len = arguments.length;\n var len = this._list.length;\n var arguments_index = 2;\n if (!size || i < size / 2) {\n temp = new Array(i);\n for (k = 0; k < i; k++) {\n temp[k] = this._list[(this._head + k) & this._capacityMask];\n }\n if (count === 0) {\n removed = [];\n if (i > 0) {\n this._head = (this._head + i + len) & this._capacityMask;\n }\n } else {\n removed = this.remove(i, count);\n this._head = (this._head + i + len) & this._capacityMask;\n }\n while (arg_len > arguments_index) {\n this.unshift(arguments[--arg_len]);\n }\n for (k = i; k > 0; k--) {\n this.unshift(temp[k - 1]);\n }\n } else {\n temp = new Array(size - (i + count));\n var leng = temp.length;\n for (k = 0; k < leng; k++) {\n temp[k] = this._list[(this._head + i + count + k) & this._capacityMask];\n }\n if (count === 0) {\n removed = [];\n if (i != size) {\n this._tail = (this._head + i + len) & this._capacityMask;\n }\n } else {\n removed = this.remove(i, count);\n this._tail = (this._tail - leng + len) & this._capacityMask;\n }\n while (arguments_index < arg_len) {\n this.push(arguments[arguments_index++]);\n }\n for (k = 0; k < leng; k++) {\n this.push(temp[k]);\n }\n }\n return removed;\n } else {\n return this.remove(i, count);\n }\n};\n\n/**\n * Soft clear - does not reset capacity.\n */\nDenque.prototype.clear = function clear() {\n this._head = 0;\n this._tail = 0;\n};\n\n/**\n * Returns true or false whether the list is empty.\n * @returns {boolean}\n */\nDenque.prototype.isEmpty = function isEmpty() {\n return this._head === this._tail;\n};\n\n/**\n * Returns an array of all queue items.\n * @returns {Array}\n */\nDenque.prototype.toArray = function toArray() {\n return this._copyArray(false);\n};\n\n/**\n * -------------\n * INTERNALS\n * -------------\n */\n\n/**\n * Fills the queue with items from an array\n * For use in the constructor\n * @param array\n * @private\n */\nDenque.prototype._fromArray = function _fromArray(array) {\n for (var i = 0; i < array.length; i++) this.push(array[i]);\n};\n\n/**\n *\n * @param fullCopy\n * @returns {Array}\n * @private\n */\nDenque.prototype._copyArray = function _copyArray(fullCopy) {\n var newArray = [];\n var list = this._list;\n var len = list.length;\n var i;\n if (fullCopy || this._head > this._tail) {\n for (i = this._head; i < len; i++) newArray.push(list[i]);\n for (i = 0; i < this._tail; i++) newArray.push(list[i]);\n } else {\n for (i = this._head; i < this._tail; i++) newArray.push(list[i]);\n }\n return newArray;\n};\n\n/**\n * Grows the internal list array.\n * @private\n */\nDenque.prototype._growArray = function _growArray() {\n if (this._head) {\n // copy existing data, head to end, then beginning to tail.\n this._list = this._copyArray(true);\n this._head = 0;\n }\n\n // head is at 0 and array is now full, safe to extend\n this._tail = this._list.length;\n\n this._list.length *= 2;\n this._capacityMask = (this._capacityMask << 1) | 1;\n};\n\n/**\n * Shrinks the internal list array.\n * @private\n */\nDenque.prototype._shrinkArray = function _shrinkArray() {\n this._list.length >>>= 1;\n this._capacityMask >>>= 1;\n};\n\n\nmodule.exports = Denque;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nclass Deprecation extends Error {\n constructor(message) {\n super(message); // Maintains proper stack trace (only available on V8)\n\n /* istanbul ignore next */\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n this.name = 'Deprecation';\n }\n\n}\n\nexports.Deprecation = Deprecation;\n","\"use strict\";\n\nmodule.exports = function () {\n // https://mths.be/emoji\n return /\\uD83C\\uDFF4(?:\\uDB40\\uDC67\\uDB40\\uDC62(?:\\uDB40\\uDC65\\uDB40\\uDC6E\\uDB40\\uDC67|\\uDB40\\uDC77\\uDB40\\uDC6C\\uDB40\\uDC73|\\uDB40\\uDC73\\uDB40\\uDC63\\uDB40\\uDC74)\\uDB40\\uDC7F|\\u200D\\u2620\\uFE0F)|\\uD83D\\uDC69\\u200D\\uD83D\\uDC69\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|\\uD83D\\uDC68(?:\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83D\\uDC68|(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDB0-\\uDDB3])|(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDB0-\\uDDB3]))|\\uD83D\\uDC69\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDB0-\\uDDB3])|\\uD83D\\uDC69\\u200D\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|(?:\\uD83D\\uDC41\\uFE0F\\u200D\\uD83D\\uDDE8|\\uD83D\\uDC69(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D[\\u2695\\u2696\\u2708]|\\uD83D\\uDC68(?:(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])|(?:(?:\\u26F9|\\uD83C[\\uDFCB\\uDFCC]|\\uD83D\\uDD75)\\uFE0F|\\uD83D\\uDC6F|\\uD83E[\\uDD3C\\uDDDE\\uDDDF])\\u200D[\\u2640\\u2642]|(?:\\u26F9|\\uD83C[\\uDFCB\\uDFCC]|\\uD83D\\uDD75)(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D[\\u2640\\u2642]|(?:\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDD6-\\uDDDD])(?:(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D[\\u2640\\u2642]|\\u200D[\\u2640\\u2642])|\\uD83D\\uDC69\\u200D[\\u2695\\u2696\\u2708])\\uFE0F|\\uD83D\\uDC69\\u200D\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83D\\uDC69\\u200D\\uD83D\\uDC69\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83D\\uDC68(?:\\u200D(?:(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83D[\\uDC66\\uDC67])|\\uD83C[\\uDFFB-\\uDFFF])|\\uD83C\\uDFF3\\uFE0F\\u200D\\uD83C\\uDF08|\\uD83D\\uDC69\\u200D\\uD83D\\uDC67|\\uD83D\\uDC69(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDB0-\\uDDB3])|\\uD83D\\uDC69\\u200D\\uD83D\\uDC66|\\uD83C\\uDDF6\\uD83C\\uDDE6|\\uD83C\\uDDFD\\uD83C\\uDDF0|\\uD83C\\uDDF4\\uD83C\\uDDF2|\\uD83D\\uDC69(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83C\\uDDED(?:\\uD83C[\\uDDF0\\uDDF2\\uDDF3\\uDDF7\\uDDF9\\uDDFA])|\\uD83C\\uDDEC(?:\\uD83C[\\uDDE6\\uDDE7\\uDDE9-\\uDDEE\\uDDF1-\\uDDF3\\uDDF5-\\uDDFA\\uDDFC\\uDDFE])|\\uD83C\\uDDEA(?:\\uD83C[\\uDDE6\\uDDE8\\uDDEA\\uDDEC\\uDDED\\uDDF7-\\uDDFA])|\\uD83C\\uDDE8(?:\\uD83C[\\uDDE6\\uDDE8\\uDDE9\\uDDEB-\\uDDEE\\uDDF0-\\uDDF5\\uDDF7\\uDDFA-\\uDDFF])|\\uD83C\\uDDF2(?:\\uD83C[\\uDDE6\\uDDE8-\\uDDED\\uDDF0-\\uDDFF])|\\uD83C\\uDDF3(?:\\uD83C[\\uDDE6\\uDDE8\\uDDEA-\\uDDEC\\uDDEE\\uDDF1\\uDDF4\\uDDF5\\uDDF7\\uDDFA\\uDDFF])|\\uD83C\\uDDFC(?:\\uD83C[\\uDDEB\\uDDF8])|\\uD83C\\uDDFA(?:\\uD83C[\\uDDE6\\uDDEC\\uDDF2\\uDDF3\\uDDF8\\uDDFE\\uDDFF])|\\uD83C\\uDDF0(?:\\uD83C[\\uDDEA\\uDDEC-\\uDDEE\\uDDF2\\uDDF3\\uDDF5\\uDDF7\\uDDFC\\uDDFE\\uDDFF])|\\uD83C\\uDDEF(?:\\uD83C[\\uDDEA\\uDDF2\\uDDF4\\uDDF5])|\\uD83C\\uDDF8(?:\\uD83C[\\uDDE6-\\uDDEA\\uDDEC-\\uDDF4\\uDDF7-\\uDDF9\\uDDFB\\uDDFD-\\uDDFF])|\\uD83C\\uDDEE(?:\\uD83C[\\uDDE8-\\uDDEA\\uDDF1-\\uDDF4\\uDDF6-\\uDDF9])|\\uD83C\\uDDFF(?:\\uD83C[\\uDDE6\\uDDF2\\uDDFC])|\\uD83C\\uDDEB(?:\\uD83C[\\uDDEE-\\uDDF0\\uDDF2\\uDDF4\\uDDF7])|\\uD83C\\uDDF5(?:\\uD83C[\\uDDE6\\uDDEA-\\uDDED\\uDDF0-\\uDDF3\\uDDF7-\\uDDF9\\uDDFC\\uDDFE])|\\uD83C\\uDDE9(?:\\uD83C[\\uDDEA\\uDDEC\\uDDEF\\uDDF0\\uDDF2\\uDDF4\\uDDFF])|\\uD83C\\uDDF9(?:\\uD83C[\\uDDE6\\uDDE8\\uDDE9\\uDDEB-\\uDDED\\uDDEF-\\uDDF4\\uDDF7\\uDDF9\\uDDFB\\uDDFC\\uDDFF])|\\uD83C\\uDDE7(?:\\uD83C[\\uDDE6\\uDDE7\\uDDE9-\\uDDEF\\uDDF1-\\uDDF4\\uDDF6-\\uDDF9\\uDDFB\\uDDFC\\uDDFE\\uDDFF])|[#\\*0-9]\\uFE0F\\u20E3|\\uD83C\\uDDF1(?:\\uD83C[\\uDDE6-\\uDDE8\\uDDEE\\uDDF0\\uDDF7-\\uDDFB\\uDDFE])|\\uD83C\\uDDE6(?:\\uD83C[\\uDDE8-\\uDDEC\\uDDEE\\uDDF1\\uDDF2\\uDDF4\\uDDF6-\\uDDFA\\uDDFC\\uDDFD\\uDDFF])|\\uD83C\\uDDF7(?:\\uD83C[\\uDDEA\\uDDF4\\uDDF8\\uDDFA\\uDDFC])|\\uD83C\\uDDFB(?:\\uD83C[\\uDDE6\\uDDE8\\uDDEA\\uDDEC\\uDDEE\\uDDF3\\uDDFA])|\\uD83C\\uDDFE(?:\\uD83C[\\uDDEA\\uDDF9])|(?:\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDD6-\\uDDDD])(?:\\uD83C[\\uDFFB-\\uDFFF])|(?:\\u26F9|\\uD83C[\\uDFCB\\uDFCC]|\\uD83D\\uDD75)(?:\\uD83C[\\uDFFB-\\uDFFF])|(?:[\\u261D\\u270A-\\u270D]|\\uD83C[\\uDF85\\uDFC2\\uDFC7]|\\uD83D[\\uDC42\\uDC43\\uDC46-\\uDC50\\uDC66\\uDC67\\uDC70\\uDC72\\uDC74-\\uDC76\\uDC78\\uDC7C\\uDC83\\uDC85\\uDCAA\\uDD74\\uDD7A\\uDD90\\uDD95\\uDD96\\uDE4C\\uDE4F\\uDEC0\\uDECC]|\\uD83E[\\uDD18-\\uDD1C\\uDD1E\\uDD1F\\uDD30-\\uDD36\\uDDB5\\uDDB6\\uDDD1-\\uDDD5])(?:\\uD83C[\\uDFFB-\\uDFFF])|(?:[\\u231A\\u231B\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u25FE\\u2614\\u2615\\u2648-\\u2653\\u267F\\u2693\\u26A1\\u26AA\\u26AB\\u26BD\\u26BE\\u26C4\\u26C5\\u26CE\\u26D4\\u26EA\\u26F2\\u26F3\\u26F5\\u26FA\\u26FD\\u2705\\u270A\\u270B\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2795-\\u2797\\u27B0\\u27BF\\u2B1B\\u2B1C\\u2B50\\u2B55]|\\uD83C[\\uDC04\\uDCCF\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE1A\\uDE2F\\uDE32-\\uDE36\\uDE38-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF20\\uDF2D-\\uDF35\\uDF37-\\uDF7C\\uDF7E-\\uDF93\\uDFA0-\\uDFCA\\uDFCF-\\uDFD3\\uDFE0-\\uDFF0\\uDFF4\\uDFF8-\\uDFFF]|\\uD83D[\\uDC00-\\uDC3E\\uDC40\\uDC42-\\uDCFC\\uDCFF-\\uDD3D\\uDD4B-\\uDD4E\\uDD50-\\uDD67\\uDD7A\\uDD95\\uDD96\\uDDA4\\uDDFB-\\uDE4F\\uDE80-\\uDEC5\\uDECC\\uDED0-\\uDED2\\uDEEB\\uDEEC\\uDEF4-\\uDEF9]|\\uD83E[\\uDD10-\\uDD3A\\uDD3C-\\uDD3E\\uDD40-\\uDD45\\uDD47-\\uDD70\\uDD73-\\uDD76\\uDD7A\\uDD7C-\\uDDA2\\uDDB0-\\uDDB9\\uDDC0-\\uDDC2\\uDDD0-\\uDDFF])|(?:[#\\*0-9\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u231A\\u231B\\u2328\\u23CF\\u23E9-\\u23F3\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB-\\u25FE\\u2600-\\u2604\\u260E\\u2611\\u2614\\u2615\\u2618\\u261D\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u2648-\\u2653\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u267F\\u2692-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A1\\u26AA\\u26AB\\u26B0\\u26B1\\u26BD\\u26BE\\u26C4\\u26C5\\u26C8\\u26CE\\u26CF\\u26D1\\u26D3\\u26D4\\u26E9\\u26EA\\u26F0-\\u26F5\\u26F7-\\u26FA\\u26FD\\u2702\\u2705\\u2708-\\u270D\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2728\\u2733\\u2734\\u2744\\u2747\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2763\\u2764\\u2795-\\u2797\\u27A1\\u27B0\\u27BF\\u2934\\u2935\\u2B05-\\u2B07\\u2B1B\\u2B1C\\u2B50\\u2B55\\u3030\\u303D\\u3297\\u3299]|\\uD83C[\\uDC04\\uDCCF\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE02\\uDE1A\\uDE2F\\uDE32-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF21\\uDF24-\\uDF93\\uDF96\\uDF97\\uDF99-\\uDF9B\\uDF9E-\\uDFF0\\uDFF3-\\uDFF5\\uDFF7-\\uDFFF]|\\uD83D[\\uDC00-\\uDCFD\\uDCFF-\\uDD3D\\uDD49-\\uDD4E\\uDD50-\\uDD67\\uDD6F\\uDD70\\uDD73-\\uDD7A\\uDD87\\uDD8A-\\uDD8D\\uDD90\\uDD95\\uDD96\\uDDA4\\uDDA5\\uDDA8\\uDDB1\\uDDB2\\uDDBC\\uDDC2-\\uDDC4\\uDDD1-\\uDDD3\\uDDDC-\\uDDDE\\uDDE1\\uDDE3\\uDDE8\\uDDEF\\uDDF3\\uDDFA-\\uDE4F\\uDE80-\\uDEC5\\uDECB-\\uDED2\\uDEE0-\\uDEE5\\uDEE9\\uDEEB\\uDEEC\\uDEF0\\uDEF3-\\uDEF9]|\\uD83E[\\uDD10-\\uDD3A\\uDD3C-\\uDD3E\\uDD40-\\uDD45\\uDD47-\\uDD70\\uDD73-\\uDD76\\uDD7A\\uDD7C-\\uDDA2\\uDDB0-\\uDDB9\\uDDC0-\\uDDC2\\uDDD0-\\uDDFF])\\uFE0F|(?:[\\u261D\\u26F9\\u270A-\\u270D]|\\uD83C[\\uDF85\\uDFC2-\\uDFC4\\uDFC7\\uDFCA-\\uDFCC]|\\uD83D[\\uDC42\\uDC43\\uDC46-\\uDC50\\uDC66-\\uDC69\\uDC6E\\uDC70-\\uDC78\\uDC7C\\uDC81-\\uDC83\\uDC85-\\uDC87\\uDCAA\\uDD74\\uDD75\\uDD7A\\uDD90\\uDD95\\uDD96\\uDE45-\\uDE47\\uDE4B-\\uDE4F\\uDEA3\\uDEB4-\\uDEB6\\uDEC0\\uDECC]|\\uD83E[\\uDD18-\\uDD1C\\uDD1E\\uDD1F\\uDD26\\uDD30-\\uDD39\\uDD3D\\uDD3E\\uDDB5\\uDDB6\\uDDB8\\uDDB9\\uDDD1-\\uDDDD])/g;\n};\n","'use strict';\n\nvar matchOperatorsRe = /[|\\\\{}()[\\]^$+*?.]/g;\n\nmodule.exports = function (str) {\n\tif (typeof str !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\treturn str.replace(matchOperatorsRe, '\\\\$&');\n};\n","'use strict'\n\nconst validator = require('./lib/validator')\nconst parse = require('./lib/parse')\nconst redactor = require('./lib/redactor')\nconst restorer = require('./lib/restorer')\nconst { groupRedact, nestedRedact } = require('./lib/modifiers')\nconst state = require('./lib/state')\nconst rx = require('./lib/rx')\nconst validate = validator()\nconst noop = (o) => o\nnoop.restore = noop\n\nconst DEFAULT_CENSOR = '[REDACTED]'\nfastRedact.rx = rx\nfastRedact.validator = validator\n\nmodule.exports = fastRedact\n\nfunction fastRedact (opts = {}) {\n const paths = Array.from(new Set(opts.paths || []))\n const serialize = 'serialize' in opts ? (\n opts.serialize === false ? opts.serialize\n : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify)\n ) : JSON.stringify\n const remove = opts.remove\n if (remove === true && serialize !== JSON.stringify) {\n throw Error('fast-redact – remove option may only be set when serializer is JSON.stringify')\n }\n const censor = remove === true\n ? undefined\n : 'censor' in opts ? opts.censor : DEFAULT_CENSOR\n\n const isCensorFct = typeof censor === 'function'\n\n if (paths.length === 0) return serialize || noop\n\n validate({ paths, serialize, censor })\n\n const { wildcards, wcLen, secret } = parse({ paths, censor })\n\n const compileRestore = restorer({ secret, wcLen })\n const strict = 'strict' in opts ? opts.strict : true\n\n return redactor({ secret, wcLen, serialize, strict, isCensorFct }, state({\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n }))\n}\n","'use strict'\n\nmodule.exports = {\n groupRedact,\n groupRestore,\n nestedRedact,\n nestedRestore\n}\n\nfunction groupRestore ({ keys, values, target }) {\n if (target == null) return\n const length = keys.length\n for (var i = 0; i < length; i++) {\n const k = keys[i]\n target[k] = values[i]\n }\n}\n\nfunction groupRedact (o, path, censor, isCensorFct) {\n const target = get(o, path)\n if (target == null) return { keys: null, values: null, target: null, flat: true }\n const keys = Object.keys(target)\n const length = keys.length\n const values = new Array(length)\n for (var i = 0; i < length; i++) {\n const k = keys[i]\n values[i] = target[k]\n target[k] = isCensorFct ? censor(target[k]) : censor\n }\n return { keys, values, target, flat: true }\n}\n\nfunction nestedRestore (arr) {\n const length = arr.length\n for (var i = 0; i < length; i++) {\n const { key, target, value } = arr[i]\n target[key] = value\n }\n}\n\nfunction nestedRedact (store, o, path, ns, censor, isCensorFct) {\n const target = get(o, path)\n if (target == null) return\n const keys = Object.keys(target)\n const length = keys.length\n for (var i = 0; i < length; i++) {\n const key = keys[i]\n const { value, parent, exists } = specialSet(target, key, ns, censor, isCensorFct)\n\n if (exists === true && parent !== null) {\n store.push({ key: ns[ns.length - 1], target: parent, value })\n }\n }\n return store\n}\n\nfunction has (obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop)\n}\n\nfunction specialSet (o, k, p, v, f) {\n var i = -1\n var l = p.length\n var li = l - 1\n var n\n var nv\n var ov\n var oov = null\n var exists = true\n ov = n = o[k]\n if (typeof n !== 'object') return { value: null, parent: null, exists }\n while (n != null && ++i < l) {\n k = p[i]\n oov = ov\n if (!(k in n)) {\n exists = false\n break\n }\n ov = n[k]\n nv = f ? v(ov) : v\n nv = (i !== li) ? ov : nv\n n[k] = (has(n, k) && nv === ov) || (nv === undefined && v !== undefined) ? n[k] : nv\n n = n[k]\n if (typeof n !== 'object') break\n }\n return { value: ov, parent: oov, exists }\n}\nfunction get (o, p) {\n var i = -1\n var l = p.length\n var n = o\n while (n != null && ++i < l) {\n n = n[p[i]]\n }\n return n\n}\n","'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = parse\n\nfunction parse ({ paths }) {\n const wildcards = []\n var wcLen = 0\n const secret = paths.reduce(function (o, strPath, ix) {\n var path = strPath.match(rx).map((p) => p.replace(/'|\"|`/g, ''))\n const leadingBracket = strPath[0] === '['\n path = path.map((p) => {\n if (p[0] === '[') return p.substr(1, p.length - 2)\n else return p\n })\n const star = path.indexOf('*')\n if (star > -1) {\n const before = path.slice(0, star)\n const beforeStr = before.join('.')\n const after = path.slice(star + 1, path.length)\n if (after.indexOf('*') > -1) throw Error('fast-redact – Only one wildcard per path is supported')\n const nested = after.length > 0\n wcLen++\n wildcards.push({\n before,\n beforeStr,\n after,\n nested\n })\n } else {\n o[strPath] = {\n path: path,\n val: undefined,\n precensored: false,\n circle: '',\n escPath: JSON.stringify(strPath),\n leadingBracket: leadingBracket\n }\n }\n return o\n }, {})\n\n return { wildcards, wcLen, secret }\n}\n","'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = redactor\n\nfunction redactor ({ secret, serialize, wcLen, strict, isCensorFct }, state) {\n /* eslint-disable-next-line */\n const redact = Function('o', `\n if (typeof o !== 'object' || o == null) {\n ${strictImpl(strict, serialize)}\n }\n const { censor, secret } = this\n ${redactTmpl(secret, isCensorFct)}\n this.compileRestore()\n ${dynamicRedactTmpl(wcLen > 0, isCensorFct)}\n ${resultTmpl(serialize)}\n `).bind(state)\n\n if (serialize === false) {\n redact.restore = (o) => state.restore(o)\n }\n\n return redact\n}\n\nfunction redactTmpl (secret, isCensorFct) {\n return Object.keys(secret).map((path) => {\n const { escPath, leadingBracket } = secret[path]\n const skip = leadingBracket ? 1 : 0\n const delim = leadingBracket ? '' : '.'\n const hops = []\n var match\n while ((match = rx.exec(path)) !== null) {\n const [ , ix ] = match\n const { index, input } = match\n if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1)))\n }\n var existence = hops.map((p) => `o${delim}${p}`).join(' && ')\n if (existence.length === 0) existence += `o${delim}${path} != null`\n else existence += ` && o${delim}${path} != null`\n\n const circularDetection = `\n switch (true) {\n ${hops.reverse().map((p) => `\n case o${delim}${p} === censor:\n secret[${escPath}].circle = ${JSON.stringify(p)}\n break\n `).join('\\n')}\n }\n `\n return `\n if (${existence}) {\n const val = o${delim}${path}\n if (val === censor) {\n secret[${escPath}].precensored = true\n } else {\n secret[${escPath}].val = val\n o${delim}${path} = ${isCensorFct ? 'censor(val)' : 'censor'}\n ${circularDetection}\n }\n }\n `\n }).join('\\n')\n}\n\nfunction dynamicRedactTmpl (hasWildcards, isCensorFct) {\n return hasWildcards === true ? `\n {\n const { wildcards, wcLen, groupRedact, nestedRedact } = this\n for (var i = 0; i < wcLen; i++) {\n const { before, beforeStr, after, nested } = wildcards[i]\n if (nested === true) {\n secret[beforeStr] = secret[beforeStr] || []\n nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct})\n } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct})\n }\n }\n ` : ''\n}\n\nfunction resultTmpl (serialize) {\n return serialize === false ? `return o` : `\n var s = this.serialize(o)\n this.restore(o)\n return s\n `\n}\n\nfunction strictImpl (strict, serialize) {\n return strict === true\n ? `throw Error('fast-redact: primitives cannot be redacted')`\n : serialize === false ? `return o` : `return this.serialize(o)`\n}\n","'use strict'\n\nconst { groupRestore, nestedRestore } = require('./modifiers')\n\nmodule.exports = restorer\n\nfunction restorer ({ secret, wcLen }) {\n return function compileRestore () {\n if (this.restore) return\n const paths = Object.keys(secret)\n .filter((path) => secret[path].precensored === false)\n const resetters = resetTmpl(secret, paths)\n const hasWildcards = wcLen > 0\n const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret }\n /* eslint-disable-next-line */\n this.restore = Function(\n 'o',\n restoreTmpl(resetters, paths, hasWildcards)\n ).bind(state)\n }\n}\n\n/**\n * Mutates the original object to be censored by restoring its original values\n * prior to censoring.\n *\n * @param {object} secret Compiled object describing which target fields should\n * be censored and the field states.\n * @param {string[]} paths The list of paths to censor as provided at\n * initialization time.\n *\n * @returns {string} String of JavaScript to be used by `Function()`. The\n * string compiles to the function that does the work in the description.\n */\nfunction resetTmpl (secret, paths) {\n return paths.map((path) => {\n const { circle, escPath, leadingBracket } = secret[path]\n const delim = leadingBracket ? '' : '.'\n const reset = circle\n ? `o.${circle} = secret[${escPath}].val`\n : `o${delim}${path} = secret[${escPath}].val`\n const clear = `secret[${escPath}].val = undefined`\n return `\n if (secret[${escPath}].val !== undefined) {\n try { ${reset} } catch (e) {}\n ${clear}\n }\n `\n }).join('')\n}\n\nfunction restoreTmpl (resetters, paths, hasWildcards) {\n const dynamicReset = hasWildcards === true ? `\n const keys = Object.keys(secret)\n const len = keys.length\n for (var i = ${paths.length}; i < len; i++) {\n const k = keys[i]\n const o = secret[k]\n if (o.flat === true) this.groupRestore(o)\n else this.nestedRestore(o)\n secret[k] = null\n }\n ` : ''\n\n return `\n const secret = this.secret\n ${resetters}\n ${dynamicReset}\n return o\n `\n}\n","'use strict'\n\nmodule.exports = /[^.[\\]]+|\\[((?:.)*?)\\]/g\n","'use strict'\n\nmodule.exports = state\n\nfunction state (o) {\n const {\n secret,\n censor,\n isCensorFct,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n } = o\n const builder = [{ secret, censor, isCensorFct, compileRestore }]\n builder.push({ secret })\n if (serialize !== false) builder.push({ serialize })\n if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen })\n return Object.assign(...builder)\n}\n","'use strict'\n\nconst { createContext, runInContext } = require('vm')\n\nmodule.exports = validator\n\nfunction validator (opts = {}) {\n const {\n ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be strings',\n ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})`\n } = opts\n\n return function validate ({ paths }) {\n paths.forEach((s) => {\n if (typeof s !== 'string') {\n throw Error(ERR_PATHS_MUST_BE_STRINGS())\n }\n try {\n if (/〇/.test(s)) throw Error()\n const proxy = new Proxy({}, { get: () => proxy, set: () => { throw Error() } })\n const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\\*/, '〇').replace(/\\.\\*/g, '.〇').replace(/\\[\\*\\]/g, '[〇]')\n if (/\\n|\\r|;/.test(expr)) throw Error()\n if (/\\/\\*/.test(expr)) throw Error()\n runInContext(`\n (function () {\n 'use strict'\n o${expr}\n if ([o${expr}].length !== 1) throw Error()\n })()\n `, createContext({ o: proxy, 〇: null }), {\n codeGeneration: { strings: false, wasm: false }\n })\n } catch (e) {\n throw Error(ERR_INVALID_PATH(s))\n }\n })\n }\n}\n","module.exports = stringify\nstringify.default = stringify\nstringify.stable = deterministicStringify\nstringify.stableStringify = deterministicStringify\n\nvar arr = []\nvar replacerStack = []\n\n// Regular stringify\nfunction stringify (obj, replacer, spacer) {\n decirc(obj, '', [], undefined)\n var res\n if (replacerStack.length === 0) {\n res = JSON.stringify(obj, replacer, spacer)\n } else {\n res = JSON.stringify(obj, replaceGetterValues(replacer), spacer)\n }\n while (arr.length !== 0) {\n var part = arr.pop()\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3])\n } else {\n part[0][part[1]] = part[2]\n }\n }\n return res\n}\nfunction decirc (val, k, stack, parent) {\n var i\n if (typeof val === 'object' && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)\n if (propertyDescriptor.get !== undefined) {\n if (propertyDescriptor.configurable) {\n Object.defineProperty(parent, k, { value: '[Circular]' })\n arr.push([parent, k, val, propertyDescriptor])\n } else {\n replacerStack.push([val, k])\n }\n } else {\n parent[k] = '[Circular]'\n arr.push([parent, k, val])\n }\n return\n }\n }\n stack.push(val)\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n decirc(val[i], i, stack, val)\n }\n } else {\n var keys = Object.keys(val)\n for (i = 0; i < keys.length; i++) {\n var key = keys[i]\n decirc(val[key], key, stack, val)\n }\n }\n stack.pop()\n }\n}\n\n// Stable-stringify\nfunction compareFunction (a, b) {\n if (a < b) {\n return -1\n }\n if (a > b) {\n return 1\n }\n return 0\n}\n\nfunction deterministicStringify (obj, replacer, spacer) {\n var tmp = deterministicDecirc(obj, '', [], undefined) || obj\n var res\n if (replacerStack.length === 0) {\n res = JSON.stringify(tmp, replacer, spacer)\n } else {\n res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer)\n }\n while (arr.length !== 0) {\n var part = arr.pop()\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3])\n } else {\n part[0][part[1]] = part[2]\n }\n }\n return res\n}\n\nfunction deterministicDecirc (val, k, stack, parent) {\n var i\n if (typeof val === 'object' && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)\n if (propertyDescriptor.get !== undefined) {\n if (propertyDescriptor.configurable) {\n Object.defineProperty(parent, k, { value: '[Circular]' })\n arr.push([parent, k, val, propertyDescriptor])\n } else {\n replacerStack.push([val, k])\n }\n } else {\n parent[k] = '[Circular]'\n arr.push([parent, k, val])\n }\n return\n }\n }\n if (typeof val.toJSON === 'function') {\n return\n }\n stack.push(val)\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n deterministicDecirc(val[i], i, stack, val)\n }\n } else {\n // Create a temporary object in the required way\n var tmp = {}\n var keys = Object.keys(val).sort(compareFunction)\n for (i = 0; i < keys.length; i++) {\n var key = keys[i]\n deterministicDecirc(val[key], key, stack, val)\n tmp[key] = val[key]\n }\n if (parent !== undefined) {\n arr.push([parent, k, val])\n parent[k] = tmp\n } else {\n return tmp\n }\n }\n stack.pop()\n }\n}\n\n// wraps replacer function to handle values we couldn't replace\n// and mark them as [Circular]\nfunction replaceGetterValues (replacer) {\n replacer = replacer !== undefined ? replacer : function (k, v) { return v }\n return function (key, val) {\n if (replacerStack.length > 0) {\n for (var i = 0; i < replacerStack.length; i++) {\n var part = replacerStack[i]\n if (part[1] === key && part[0] === val) {\n val = '[Circular]'\n replacerStack.splice(i, 1)\n break\n }\n }\n }\n return replacer.call(this, key, val)\n }\n}\n","'use strict'\n\n// You may be tempted to copy and paste this, \n// but take a look at the commit history first,\n// this is a moving target so relying on the module\n// is the best way to make sure the optimization\n// method is kept up to date and compatible with\n// every Node version.\n\nfunction flatstr (s) {\n s | 0\n return s\n}\n\nmodule.exports = flatstr","\"use strict\";\n// Call this function in a another function to find out the file from\n// which that function was called from. (Inspects the v8 stack trace)\n//\n// Inspired by http://stackoverflow.com/questions/13227489\nmodule.exports = function getCallerFile(position) {\n if (position === void 0) { position = 2; }\n if (position >= Error.stackTraceLimit) {\n throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`');\n }\n var oldPrepareStackTrace = Error.prepareStackTrace;\n Error.prepareStackTrace = function (_, stack) { return stack; };\n var stack = new Error().stack;\n Error.prepareStackTrace = oldPrepareStackTrace;\n if (stack !== null && typeof stack === 'object') {\n // stack[0] holds this file\n // stack[1] holds where this function was called\n // stack[2] holds the file we're interested in\n return stack[position] ? stack[position].getFileName() : undefined;\n }\n};\n//# sourceMappingURL=index.js.map","'use strict';\nmodule.exports = (flag, argv) => {\n\targv = argv || process.argv;\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst pos = argv.indexOf(prefix + flag);\n\tconst terminatorPos = argv.indexOf('--');\n\treturn pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);\n};\n","try {\n var util = require('util');\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = require('./inherits_browser.js');\n}\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\n/**\n * Use invariant() to assert state which your program assumes to be true.\n *\n * Provide sprintf-style format (only %s is supported) and arguments\n * to provide information about what broke and what you were\n * expecting.\n *\n * The invariant message will be stripped in production, but the invariant\n * will remain to ensure logic does not differ in production.\n */\n\nvar NODE_ENV = process.env.NODE_ENV;\n\nvar invariant = function(condition, format, a, b, c, d, e, f) {\n if (NODE_ENV !== 'production') {\n if (format === undefined) {\n throw new Error('invariant requires an error message argument');\n }\n }\n\n if (!condition) {\n var error;\n if (format === undefined) {\n error = new Error(\n 'Minified exception occurred; use the non-minified dev environment ' +\n 'for the full error message and additional helpful warnings.'\n );\n } else {\n var args = [a, b, c, d, e, f];\n var argIndex = 0;\n error = new Error(\n format.replace(/%s/g, function() { return args[argIndex++]; })\n );\n error.name = 'Invariant Violation';\n }\n\n error.framesToPop = 1; // we don't care about invariant's own frame\n throw error;\n }\n};\n\nmodule.exports = invariant;\n","'use strict';\n/* eslint-disable yoda */\nmodule.exports = x => {\n\tif (Number.isNaN(x)) {\n\t\treturn false;\n\t}\n\n\t// code points are derived from:\n\t// http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt\n\tif (\n\t\tx >= 0x1100 && (\n\t\t\tx <= 0x115f || // Hangul Jamo\n\t\t\tx === 0x2329 || // LEFT-POINTING ANGLE BRACKET\n\t\t\tx === 0x232a || // RIGHT-POINTING ANGLE BRACKET\n\t\t\t// CJK Radicals Supplement .. Enclosed CJK Letters and Months\n\t\t\t(0x2e80 <= x && x <= 0x3247 && x !== 0x303f) ||\n\t\t\t// Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A\n\t\t\t(0x3250 <= x && x <= 0x4dbf) ||\n\t\t\t// CJK Unified Ideographs .. Yi Radicals\n\t\t\t(0x4e00 <= x && x <= 0xa4c6) ||\n\t\t\t// Hangul Jamo Extended-A\n\t\t\t(0xa960 <= x && x <= 0xa97c) ||\n\t\t\t// Hangul Syllables\n\t\t\t(0xac00 <= x && x <= 0xd7a3) ||\n\t\t\t// CJK Compatibility Ideographs\n\t\t\t(0xf900 <= x && x <= 0xfaff) ||\n\t\t\t// Vertical Forms\n\t\t\t(0xfe10 <= x && x <= 0xfe19) ||\n\t\t\t// CJK Compatibility Forms .. Small Form Variants\n\t\t\t(0xfe30 <= x && x <= 0xfe6b) ||\n\t\t\t// Halfwidth and Fullwidth Forms\n\t\t\t(0xff01 <= x && x <= 0xff60) ||\n\t\t\t(0xffe0 <= x && x <= 0xffe6) ||\n\t\t\t// Kana Supplement\n\t\t\t(0x1b000 <= x && x <= 0x1b001) ||\n\t\t\t// Enclosed Ideographic Supplement\n\t\t\t(0x1f200 <= x && x <= 0x1f251) ||\n\t\t\t// CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane\n\t\t\t(0x20000 <= x && x <= 0x3fffd)\n\t\t)\n\t) {\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","(function(exports) {\n \"use strict\";\n\n function isArray(obj) {\n if (obj !== null) {\n return Object.prototype.toString.call(obj) === \"[object Array]\";\n } else {\n return false;\n }\n }\n\n function isObject(obj) {\n if (obj !== null) {\n return Object.prototype.toString.call(obj) === \"[object Object]\";\n } else {\n return false;\n }\n }\n\n function strictDeepEqual(first, second) {\n // Check the scalar case first.\n if (first === second) {\n return true;\n }\n\n // Check if they are the same type.\n var firstType = Object.prototype.toString.call(first);\n if (firstType !== Object.prototype.toString.call(second)) {\n return false;\n }\n // We know that first and second have the same type so we can just check the\n // first type from now on.\n if (isArray(first) === true) {\n // Short circuit if they're not the same length;\n if (first.length !== second.length) {\n return false;\n }\n for (var i = 0; i < first.length; i++) {\n if (strictDeepEqual(first[i], second[i]) === false) {\n return false;\n }\n }\n return true;\n }\n if (isObject(first) === true) {\n // An object is equal if it has the same key/value pairs.\n var keysSeen = {};\n for (var key in first) {\n if (hasOwnProperty.call(first, key)) {\n if (strictDeepEqual(first[key], second[key]) === false) {\n return false;\n }\n keysSeen[key] = true;\n }\n }\n // Now check that there aren't any keys in second that weren't\n // in first.\n for (var key2 in second) {\n if (hasOwnProperty.call(second, key2)) {\n if (keysSeen[key2] !== true) {\n return false;\n }\n }\n }\n return true;\n }\n return false;\n }\n\n function isFalse(obj) {\n // From the spec:\n // A false value corresponds to the following values:\n // Empty list\n // Empty object\n // Empty string\n // False boolean\n // null value\n\n // First check the scalar values.\n if (obj === \"\" || obj === false || obj === null) {\n return true;\n } else if (isArray(obj) && obj.length === 0) {\n // Check for an empty array.\n return true;\n } else if (isObject(obj)) {\n // Check for an empty object.\n for (var key in obj) {\n // If there are any keys, then\n // the object is not empty so the object\n // is not false.\n if (obj.hasOwnProperty(key)) {\n return false;\n }\n }\n return true;\n } else {\n return false;\n }\n }\n\n function objValues(obj) {\n var keys = Object.keys(obj);\n var values = [];\n for (var i = 0; i < keys.length; i++) {\n values.push(obj[keys[i]]);\n }\n return values;\n }\n\n function merge(a, b) {\n var merged = {};\n for (var key in a) {\n merged[key] = a[key];\n }\n for (var key2 in b) {\n merged[key2] = b[key2];\n }\n return merged;\n }\n\n var trimLeft;\n if (typeof String.prototype.trimLeft === \"function\") {\n trimLeft = function(str) {\n return str.trimLeft();\n };\n } else {\n trimLeft = function(str) {\n return str.match(/^\\s*(.*)/)[1];\n };\n }\n\n // Type constants used to define functions.\n var TYPE_NUMBER = 0;\n var TYPE_ANY = 1;\n var TYPE_STRING = 2;\n var TYPE_ARRAY = 3;\n var TYPE_OBJECT = 4;\n var TYPE_BOOLEAN = 5;\n var TYPE_EXPREF = 6;\n var TYPE_NULL = 7;\n var TYPE_ARRAY_NUMBER = 8;\n var TYPE_ARRAY_STRING = 9;\n\n var TOK_EOF = \"EOF\";\n var TOK_UNQUOTEDIDENTIFIER = \"UnquotedIdentifier\";\n var TOK_QUOTEDIDENTIFIER = \"QuotedIdentifier\";\n var TOK_RBRACKET = \"Rbracket\";\n var TOK_RPAREN = \"Rparen\";\n var TOK_COMMA = \"Comma\";\n var TOK_COLON = \"Colon\";\n var TOK_RBRACE = \"Rbrace\";\n var TOK_NUMBER = \"Number\";\n var TOK_CURRENT = \"Current\";\n var TOK_EXPREF = \"Expref\";\n var TOK_PIPE = \"Pipe\";\n var TOK_OR = \"Or\";\n var TOK_AND = \"And\";\n var TOK_EQ = \"EQ\";\n var TOK_GT = \"GT\";\n var TOK_LT = \"LT\";\n var TOK_GTE = \"GTE\";\n var TOK_LTE = \"LTE\";\n var TOK_NE = \"NE\";\n var TOK_FLATTEN = \"Flatten\";\n var TOK_STAR = \"Star\";\n var TOK_FILTER = \"Filter\";\n var TOK_DOT = \"Dot\";\n var TOK_NOT = \"Not\";\n var TOK_LBRACE = \"Lbrace\";\n var TOK_LBRACKET = \"Lbracket\";\n var TOK_LPAREN= \"Lparen\";\n var TOK_LITERAL= \"Literal\";\n\n // The \"&\", \"[\", \"<\", \">\" tokens\n // are not in basicToken because\n // there are two token variants\n // (\"&&\", \"[?\", \"<=\", \">=\"). This is specially handled\n // below.\n\n var basicTokens = {\n \".\": TOK_DOT,\n \"*\": TOK_STAR,\n \",\": TOK_COMMA,\n \":\": TOK_COLON,\n \"{\": TOK_LBRACE,\n \"}\": TOK_RBRACE,\n \"]\": TOK_RBRACKET,\n \"(\": TOK_LPAREN,\n \")\": TOK_RPAREN,\n \"@\": TOK_CURRENT\n };\n\n var operatorStartToken = {\n \"<\": true,\n \">\": true,\n \"=\": true,\n \"!\": true\n };\n\n var skipChars = {\n \" \": true,\n \"\\t\": true,\n \"\\n\": true\n };\n\n\n function isAlpha(ch) {\n return (ch >= \"a\" && ch <= \"z\") ||\n (ch >= \"A\" && ch <= \"Z\") ||\n ch === \"_\";\n }\n\n function isNum(ch) {\n return (ch >= \"0\" && ch <= \"9\") ||\n ch === \"-\";\n }\n function isAlphaNum(ch) {\n return (ch >= \"a\" && ch <= \"z\") ||\n (ch >= \"A\" && ch <= \"Z\") ||\n (ch >= \"0\" && ch <= \"9\") ||\n ch === \"_\";\n }\n\n function Lexer() {\n }\n Lexer.prototype = {\n tokenize: function(stream) {\n var tokens = [];\n this._current = 0;\n var start;\n var identifier;\n var token;\n while (this._current < stream.length) {\n if (isAlpha(stream[this._current])) {\n start = this._current;\n identifier = this._consumeUnquotedIdentifier(stream);\n tokens.push({type: TOK_UNQUOTEDIDENTIFIER,\n value: identifier,\n start: start});\n } else if (basicTokens[stream[this._current]] !== undefined) {\n tokens.push({type: basicTokens[stream[this._current]],\n value: stream[this._current],\n start: this._current});\n this._current++;\n } else if (isNum(stream[this._current])) {\n token = this._consumeNumber(stream);\n tokens.push(token);\n } else if (stream[this._current] === \"[\") {\n // No need to increment this._current. This happens\n // in _consumeLBracket\n token = this._consumeLBracket(stream);\n tokens.push(token);\n } else if (stream[this._current] === \"\\\"\") {\n start = this._current;\n identifier = this._consumeQuotedIdentifier(stream);\n tokens.push({type: TOK_QUOTEDIDENTIFIER,\n value: identifier,\n start: start});\n } else if (stream[this._current] === \"'\") {\n start = this._current;\n identifier = this._consumeRawStringLiteral(stream);\n tokens.push({type: TOK_LITERAL,\n value: identifier,\n start: start});\n } else if (stream[this._current] === \"`\") {\n start = this._current;\n var literal = this._consumeLiteral(stream);\n tokens.push({type: TOK_LITERAL,\n value: literal,\n start: start});\n } else if (operatorStartToken[stream[this._current]] !== undefined) {\n tokens.push(this._consumeOperator(stream));\n } else if (skipChars[stream[this._current]] !== undefined) {\n // Ignore whitespace.\n this._current++;\n } else if (stream[this._current] === \"&\") {\n start = this._current;\n this._current++;\n if (stream[this._current] === \"&\") {\n this._current++;\n tokens.push({type: TOK_AND, value: \"&&\", start: start});\n } else {\n tokens.push({type: TOK_EXPREF, value: \"&\", start: start});\n }\n } else if (stream[this._current] === \"|\") {\n start = this._current;\n this._current++;\n if (stream[this._current] === \"|\") {\n this._current++;\n tokens.push({type: TOK_OR, value: \"||\", start: start});\n } else {\n tokens.push({type: TOK_PIPE, value: \"|\", start: start});\n }\n } else {\n var error = new Error(\"Unknown character:\" + stream[this._current]);\n error.name = \"LexerError\";\n throw error;\n }\n }\n return tokens;\n },\n\n _consumeUnquotedIdentifier: function(stream) {\n var start = this._current;\n this._current++;\n while (this._current < stream.length && isAlphaNum(stream[this._current])) {\n this._current++;\n }\n return stream.slice(start, this._current);\n },\n\n _consumeQuotedIdentifier: function(stream) {\n var start = this._current;\n this._current++;\n var maxLength = stream.length;\n while (stream[this._current] !== \"\\\"\" && this._current < maxLength) {\n // You can escape a double quote and you can escape an escape.\n var current = this._current;\n if (stream[current] === \"\\\\\" && (stream[current + 1] === \"\\\\\" ||\n stream[current + 1] === \"\\\"\")) {\n current += 2;\n } else {\n current++;\n }\n this._current = current;\n }\n this._current++;\n return JSON.parse(stream.slice(start, this._current));\n },\n\n _consumeRawStringLiteral: function(stream) {\n var start = this._current;\n this._current++;\n var maxLength = stream.length;\n while (stream[this._current] !== \"'\" && this._current < maxLength) {\n // You can escape a single quote and you can escape an escape.\n var current = this._current;\n if (stream[current] === \"\\\\\" && (stream[current + 1] === \"\\\\\" ||\n stream[current + 1] === \"'\")) {\n current += 2;\n } else {\n current++;\n }\n this._current = current;\n }\n this._current++;\n var literal = stream.slice(start + 1, this._current - 1);\n return literal.replace(\"\\\\'\", \"'\");\n },\n\n _consumeNumber: function(stream) {\n var start = this._current;\n this._current++;\n var maxLength = stream.length;\n while (isNum(stream[this._current]) && this._current < maxLength) {\n this._current++;\n }\n var value = parseInt(stream.slice(start, this._current));\n return {type: TOK_NUMBER, value: value, start: start};\n },\n\n _consumeLBracket: function(stream) {\n var start = this._current;\n this._current++;\n if (stream[this._current] === \"?\") {\n this._current++;\n return {type: TOK_FILTER, value: \"[?\", start: start};\n } else if (stream[this._current] === \"]\") {\n this._current++;\n return {type: TOK_FLATTEN, value: \"[]\", start: start};\n } else {\n return {type: TOK_LBRACKET, value: \"[\", start: start};\n }\n },\n\n _consumeOperator: function(stream) {\n var start = this._current;\n var startingChar = stream[start];\n this._current++;\n if (startingChar === \"!\") {\n if (stream[this._current] === \"=\") {\n this._current++;\n return {type: TOK_NE, value: \"!=\", start: start};\n } else {\n return {type: TOK_NOT, value: \"!\", start: start};\n }\n } else if (startingChar === \"<\") {\n if (stream[this._current] === \"=\") {\n this._current++;\n return {type: TOK_LTE, value: \"<=\", start: start};\n } else {\n return {type: TOK_LT, value: \"<\", start: start};\n }\n } else if (startingChar === \">\") {\n if (stream[this._current] === \"=\") {\n this._current++;\n return {type: TOK_GTE, value: \">=\", start: start};\n } else {\n return {type: TOK_GT, value: \">\", start: start};\n }\n } else if (startingChar === \"=\") {\n if (stream[this._current] === \"=\") {\n this._current++;\n return {type: TOK_EQ, value: \"==\", start: start};\n }\n }\n },\n\n _consumeLiteral: function(stream) {\n this._current++;\n var start = this._current;\n var maxLength = stream.length;\n var literal;\n while(stream[this._current] !== \"`\" && this._current < maxLength) {\n // You can escape a literal char or you can escape the escape.\n var current = this._current;\n if (stream[current] === \"\\\\\" && (stream[current + 1] === \"\\\\\" ||\n stream[current + 1] === \"`\")) {\n current += 2;\n } else {\n current++;\n }\n this._current = current;\n }\n var literalString = trimLeft(stream.slice(start, this._current));\n literalString = literalString.replace(\"\\\\`\", \"`\");\n if (this._looksLikeJSON(literalString)) {\n literal = JSON.parse(literalString);\n } else {\n // Try to JSON parse it as \"\"\n literal = JSON.parse(\"\\\"\" + literalString + \"\\\"\");\n }\n // +1 gets us to the ending \"`\", +1 to move on to the next char.\n this._current++;\n return literal;\n },\n\n _looksLikeJSON: function(literalString) {\n var startingChars = \"[{\\\"\";\n var jsonLiterals = [\"true\", \"false\", \"null\"];\n var numberLooking = \"-0123456789\";\n\n if (literalString === \"\") {\n return false;\n } else if (startingChars.indexOf(literalString[0]) >= 0) {\n return true;\n } else if (jsonLiterals.indexOf(literalString) >= 0) {\n return true;\n } else if (numberLooking.indexOf(literalString[0]) >= 0) {\n try {\n JSON.parse(literalString);\n return true;\n } catch (ex) {\n return false;\n }\n } else {\n return false;\n }\n }\n };\n\n var bindingPower = {};\n bindingPower[TOK_EOF] = 0;\n bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0;\n bindingPower[TOK_QUOTEDIDENTIFIER] = 0;\n bindingPower[TOK_RBRACKET] = 0;\n bindingPower[TOK_RPAREN] = 0;\n bindingPower[TOK_COMMA] = 0;\n bindingPower[TOK_RBRACE] = 0;\n bindingPower[TOK_NUMBER] = 0;\n bindingPower[TOK_CURRENT] = 0;\n bindingPower[TOK_EXPREF] = 0;\n bindingPower[TOK_PIPE] = 1;\n bindingPower[TOK_OR] = 2;\n bindingPower[TOK_AND] = 3;\n bindingPower[TOK_EQ] = 5;\n bindingPower[TOK_GT] = 5;\n bindingPower[TOK_LT] = 5;\n bindingPower[TOK_GTE] = 5;\n bindingPower[TOK_LTE] = 5;\n bindingPower[TOK_NE] = 5;\n bindingPower[TOK_FLATTEN] = 9;\n bindingPower[TOK_STAR] = 20;\n bindingPower[TOK_FILTER] = 21;\n bindingPower[TOK_DOT] = 40;\n bindingPower[TOK_NOT] = 45;\n bindingPower[TOK_LBRACE] = 50;\n bindingPower[TOK_LBRACKET] = 55;\n bindingPower[TOK_LPAREN] = 60;\n\n function Parser() {\n }\n\n Parser.prototype = {\n parse: function(expression) {\n this._loadTokens(expression);\n this.index = 0;\n var ast = this.expression(0);\n if (this._lookahead(0) !== TOK_EOF) {\n var t = this._lookaheadToken(0);\n var error = new Error(\n \"Unexpected token type: \" + t.type + \", value: \" + t.value);\n error.name = \"ParserError\";\n throw error;\n }\n return ast;\n },\n\n _loadTokens: function(expression) {\n var lexer = new Lexer();\n var tokens = lexer.tokenize(expression);\n tokens.push({type: TOK_EOF, value: \"\", start: expression.length});\n this.tokens = tokens;\n },\n\n expression: function(rbp) {\n var leftToken = this._lookaheadToken(0);\n this._advance();\n var left = this.nud(leftToken);\n var currentToken = this._lookahead(0);\n while (rbp < bindingPower[currentToken]) {\n this._advance();\n left = this.led(currentToken, left);\n currentToken = this._lookahead(0);\n }\n return left;\n },\n\n _lookahead: function(number) {\n return this.tokens[this.index + number].type;\n },\n\n _lookaheadToken: function(number) {\n return this.tokens[this.index + number];\n },\n\n _advance: function() {\n this.index++;\n },\n\n nud: function(token) {\n var left;\n var right;\n var expression;\n switch (token.type) {\n case TOK_LITERAL:\n return {type: \"Literal\", value: token.value};\n case TOK_UNQUOTEDIDENTIFIER:\n return {type: \"Field\", name: token.value};\n case TOK_QUOTEDIDENTIFIER:\n var node = {type: \"Field\", name: token.value};\n if (this._lookahead(0) === TOK_LPAREN) {\n throw new Error(\"Quoted identifier not allowed for function names.\");\n } else {\n return node;\n }\n break;\n case TOK_NOT:\n right = this.expression(bindingPower.Not);\n return {type: \"NotExpression\", children: [right]};\n case TOK_STAR:\n left = {type: \"Identity\"};\n right = null;\n if (this._lookahead(0) === TOK_RBRACKET) {\n // This can happen in a multiselect,\n // [a, b, *]\n right = {type: \"Identity\"};\n } else {\n right = this._parseProjectionRHS(bindingPower.Star);\n }\n return {type: \"ValueProjection\", children: [left, right]};\n case TOK_FILTER:\n return this.led(token.type, {type: \"Identity\"});\n case TOK_LBRACE:\n return this._parseMultiselectHash();\n case TOK_FLATTEN:\n left = {type: TOK_FLATTEN, children: [{type: \"Identity\"}]};\n right = this._parseProjectionRHS(bindingPower.Flatten);\n return {type: \"Projection\", children: [left, right]};\n case TOK_LBRACKET:\n if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) {\n right = this._parseIndexExpression();\n return this._projectIfSlice({type: \"Identity\"}, right);\n } else if (this._lookahead(0) === TOK_STAR &&\n this._lookahead(1) === TOK_RBRACKET) {\n this._advance();\n this._advance();\n right = this._parseProjectionRHS(bindingPower.Star);\n return {type: \"Projection\",\n children: [{type: \"Identity\"}, right]};\n } else {\n return this._parseMultiselectList();\n }\n break;\n case TOK_CURRENT:\n return {type: TOK_CURRENT};\n case TOK_EXPREF:\n expression = this.expression(bindingPower.Expref);\n return {type: \"ExpressionReference\", children: [expression]};\n case TOK_LPAREN:\n var args = [];\n while (this._lookahead(0) !== TOK_RPAREN) {\n if (this._lookahead(0) === TOK_CURRENT) {\n expression = {type: TOK_CURRENT};\n this._advance();\n } else {\n expression = this.expression(0);\n }\n args.push(expression);\n }\n this._match(TOK_RPAREN);\n return args[0];\n default:\n this._errorToken(token);\n }\n },\n\n led: function(tokenName, left) {\n var right;\n switch(tokenName) {\n case TOK_DOT:\n var rbp = bindingPower.Dot;\n if (this._lookahead(0) !== TOK_STAR) {\n right = this._parseDotRHS(rbp);\n return {type: \"Subexpression\", children: [left, right]};\n } else {\n // Creating a projection.\n this._advance();\n right = this._parseProjectionRHS(rbp);\n return {type: \"ValueProjection\", children: [left, right]};\n }\n break;\n case TOK_PIPE:\n right = this.expression(bindingPower.Pipe);\n return {type: TOK_PIPE, children: [left, right]};\n case TOK_OR:\n right = this.expression(bindingPower.Or);\n return {type: \"OrExpression\", children: [left, right]};\n case TOK_AND:\n right = this.expression(bindingPower.And);\n return {type: \"AndExpression\", children: [left, right]};\n case TOK_LPAREN:\n var name = left.name;\n var args = [];\n var expression, node;\n while (this._lookahead(0) !== TOK_RPAREN) {\n if (this._lookahead(0) === TOK_CURRENT) {\n expression = {type: TOK_CURRENT};\n this._advance();\n } else {\n expression = this.expression(0);\n }\n if (this._lookahead(0) === TOK_COMMA) {\n this._match(TOK_COMMA);\n }\n args.push(expression);\n }\n this._match(TOK_RPAREN);\n node = {type: \"Function\", name: name, children: args};\n return node;\n case TOK_FILTER:\n var condition = this.expression(0);\n this._match(TOK_RBRACKET);\n if (this._lookahead(0) === TOK_FLATTEN) {\n right = {type: \"Identity\"};\n } else {\n right = this._parseProjectionRHS(bindingPower.Filter);\n }\n return {type: \"FilterProjection\", children: [left, right, condition]};\n case TOK_FLATTEN:\n var leftNode = {type: TOK_FLATTEN, children: [left]};\n var rightNode = this._parseProjectionRHS(bindingPower.Flatten);\n return {type: \"Projection\", children: [leftNode, rightNode]};\n case TOK_EQ:\n case TOK_NE:\n case TOK_GT:\n case TOK_GTE:\n case TOK_LT:\n case TOK_LTE:\n return this._parseComparator(left, tokenName);\n case TOK_LBRACKET:\n var token = this._lookaheadToken(0);\n if (token.type === TOK_NUMBER || token.type === TOK_COLON) {\n right = this._parseIndexExpression();\n return this._projectIfSlice(left, right);\n } else {\n this._match(TOK_STAR);\n this._match(TOK_RBRACKET);\n right = this._parseProjectionRHS(bindingPower.Star);\n return {type: \"Projection\", children: [left, right]};\n }\n break;\n default:\n this._errorToken(this._lookaheadToken(0));\n }\n },\n\n _match: function(tokenType) {\n if (this._lookahead(0) === tokenType) {\n this._advance();\n } else {\n var t = this._lookaheadToken(0);\n var error = new Error(\"Expected \" + tokenType + \", got: \" + t.type);\n error.name = \"ParserError\";\n throw error;\n }\n },\n\n _errorToken: function(token) {\n var error = new Error(\"Invalid token (\" +\n token.type + \"): \\\"\" +\n token.value + \"\\\"\");\n error.name = \"ParserError\";\n throw error;\n },\n\n\n _parseIndexExpression: function() {\n if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) {\n return this._parseSliceExpression();\n } else {\n var node = {\n type: \"Index\",\n value: this._lookaheadToken(0).value};\n this._advance();\n this._match(TOK_RBRACKET);\n return node;\n }\n },\n\n _projectIfSlice: function(left, right) {\n var indexExpr = {type: \"IndexExpression\", children: [left, right]};\n if (right.type === \"Slice\") {\n return {\n type: \"Projection\",\n children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)]\n };\n } else {\n return indexExpr;\n }\n },\n\n _parseSliceExpression: function() {\n // [start:end:step] where each part is optional, as well as the last\n // colon.\n var parts = [null, null, null];\n var index = 0;\n var currentToken = this._lookahead(0);\n while (currentToken !== TOK_RBRACKET && index < 3) {\n if (currentToken === TOK_COLON) {\n index++;\n this._advance();\n } else if (currentToken === TOK_NUMBER) {\n parts[index] = this._lookaheadToken(0).value;\n this._advance();\n } else {\n var t = this._lookahead(0);\n var error = new Error(\"Syntax error, unexpected token: \" +\n t.value + \"(\" + t.type + \")\");\n error.name = \"Parsererror\";\n throw error;\n }\n currentToken = this._lookahead(0);\n }\n this._match(TOK_RBRACKET);\n return {\n type: \"Slice\",\n children: parts\n };\n },\n\n _parseComparator: function(left, comparator) {\n var right = this.expression(bindingPower[comparator]);\n return {type: \"Comparator\", name: comparator, children: [left, right]};\n },\n\n _parseDotRHS: function(rbp) {\n var lookahead = this._lookahead(0);\n var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR];\n if (exprTokens.indexOf(lookahead) >= 0) {\n return this.expression(rbp);\n } else if (lookahead === TOK_LBRACKET) {\n this._match(TOK_LBRACKET);\n return this._parseMultiselectList();\n } else if (lookahead === TOK_LBRACE) {\n this._match(TOK_LBRACE);\n return this._parseMultiselectHash();\n }\n },\n\n _parseProjectionRHS: function(rbp) {\n var right;\n if (bindingPower[this._lookahead(0)] < 10) {\n right = {type: \"Identity\"};\n } else if (this._lookahead(0) === TOK_LBRACKET) {\n right = this.expression(rbp);\n } else if (this._lookahead(0) === TOK_FILTER) {\n right = this.expression(rbp);\n } else if (this._lookahead(0) === TOK_DOT) {\n this._match(TOK_DOT);\n right = this._parseDotRHS(rbp);\n } else {\n var t = this._lookaheadToken(0);\n var error = new Error(\"Sytanx error, unexpected token: \" +\n t.value + \"(\" + t.type + \")\");\n error.name = \"ParserError\";\n throw error;\n }\n return right;\n },\n\n _parseMultiselectList: function() {\n var expressions = [];\n while (this._lookahead(0) !== TOK_RBRACKET) {\n var expression = this.expression(0);\n expressions.push(expression);\n if (this._lookahead(0) === TOK_COMMA) {\n this._match(TOK_COMMA);\n if (this._lookahead(0) === TOK_RBRACKET) {\n throw new Error(\"Unexpected token Rbracket\");\n }\n }\n }\n this._match(TOK_RBRACKET);\n return {type: \"MultiSelectList\", children: expressions};\n },\n\n _parseMultiselectHash: function() {\n var pairs = [];\n var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER];\n var keyToken, keyName, value, node;\n for (;;) {\n keyToken = this._lookaheadToken(0);\n if (identifierTypes.indexOf(keyToken.type) < 0) {\n throw new Error(\"Expecting an identifier token, got: \" +\n keyToken.type);\n }\n keyName = keyToken.value;\n this._advance();\n this._match(TOK_COLON);\n value = this.expression(0);\n node = {type: \"KeyValuePair\", name: keyName, value: value};\n pairs.push(node);\n if (this._lookahead(0) === TOK_COMMA) {\n this._match(TOK_COMMA);\n } else if (this._lookahead(0) === TOK_RBRACE) {\n this._match(TOK_RBRACE);\n break;\n }\n }\n return {type: \"MultiSelectHash\", children: pairs};\n }\n };\n\n\n function TreeInterpreter(runtime) {\n this.runtime = runtime;\n }\n\n TreeInterpreter.prototype = {\n search: function(node, value) {\n return this.visit(node, value);\n },\n\n visit: function(node, value) {\n var matched, current, result, first, second, field, left, right, collected, i;\n switch (node.type) {\n case \"Field\":\n if (value === null ) {\n return null;\n } else if (isObject(value)) {\n field = value[node.name];\n if (field === undefined) {\n return null;\n } else {\n return field;\n }\n } else {\n return null;\n }\n break;\n case \"Subexpression\":\n result = this.visit(node.children[0], value);\n for (i = 1; i < node.children.length; i++) {\n result = this.visit(node.children[1], result);\n if (result === null) {\n return null;\n }\n }\n return result;\n case \"IndexExpression\":\n left = this.visit(node.children[0], value);\n right = this.visit(node.children[1], left);\n return right;\n case \"Index\":\n if (!isArray(value)) {\n return null;\n }\n var index = node.value;\n if (index < 0) {\n index = value.length + index;\n }\n result = value[index];\n if (result === undefined) {\n result = null;\n }\n return result;\n case \"Slice\":\n if (!isArray(value)) {\n return null;\n }\n var sliceParams = node.children.slice(0);\n var computed = this.computeSliceParams(value.length, sliceParams);\n var start = computed[0];\n var stop = computed[1];\n var step = computed[2];\n result = [];\n if (step > 0) {\n for (i = start; i < stop; i += step) {\n result.push(value[i]);\n }\n } else {\n for (i = start; i > stop; i += step) {\n result.push(value[i]);\n }\n }\n return result;\n case \"Projection\":\n // Evaluate left child.\n var base = this.visit(node.children[0], value);\n if (!isArray(base)) {\n return null;\n }\n collected = [];\n for (i = 0; i < base.length; i++) {\n current = this.visit(node.children[1], base[i]);\n if (current !== null) {\n collected.push(current);\n }\n }\n return collected;\n case \"ValueProjection\":\n // Evaluate left child.\n base = this.visit(node.children[0], value);\n if (!isObject(base)) {\n return null;\n }\n collected = [];\n var values = objValues(base);\n for (i = 0; i < values.length; i++) {\n current = this.visit(node.children[1], values[i]);\n if (current !== null) {\n collected.push(current);\n }\n }\n return collected;\n case \"FilterProjection\":\n base = this.visit(node.children[0], value);\n if (!isArray(base)) {\n return null;\n }\n var filtered = [];\n var finalResults = [];\n for (i = 0; i < base.length; i++) {\n matched = this.visit(node.children[2], base[i]);\n if (!isFalse(matched)) {\n filtered.push(base[i]);\n }\n }\n for (var j = 0; j < filtered.length; j++) {\n current = this.visit(node.children[1], filtered[j]);\n if (current !== null) {\n finalResults.push(current);\n }\n }\n return finalResults;\n case \"Comparator\":\n first = this.visit(node.children[0], value);\n second = this.visit(node.children[1], value);\n switch(node.name) {\n case TOK_EQ:\n result = strictDeepEqual(first, second);\n break;\n case TOK_NE:\n result = !strictDeepEqual(first, second);\n break;\n case TOK_GT:\n result = first > second;\n break;\n case TOK_GTE:\n result = first >= second;\n break;\n case TOK_LT:\n result = first < second;\n break;\n case TOK_LTE:\n result = first <= second;\n break;\n default:\n throw new Error(\"Unknown comparator: \" + node.name);\n }\n return result;\n case TOK_FLATTEN:\n var original = this.visit(node.children[0], value);\n if (!isArray(original)) {\n return null;\n }\n var merged = [];\n for (i = 0; i < original.length; i++) {\n current = original[i];\n if (isArray(current)) {\n merged.push.apply(merged, current);\n } else {\n merged.push(current);\n }\n }\n return merged;\n case \"Identity\":\n return value;\n case \"MultiSelectList\":\n if (value === null) {\n return null;\n }\n collected = [];\n for (i = 0; i < node.children.length; i++) {\n collected.push(this.visit(node.children[i], value));\n }\n return collected;\n case \"MultiSelectHash\":\n if (value === null) {\n return null;\n }\n collected = {};\n var child;\n for (i = 0; i < node.children.length; i++) {\n child = node.children[i];\n collected[child.name] = this.visit(child.value, value);\n }\n return collected;\n case \"OrExpression\":\n matched = this.visit(node.children[0], value);\n if (isFalse(matched)) {\n matched = this.visit(node.children[1], value);\n }\n return matched;\n case \"AndExpression\":\n first = this.visit(node.children[0], value);\n\n if (isFalse(first) === true) {\n return first;\n }\n return this.visit(node.children[1], value);\n case \"NotExpression\":\n first = this.visit(node.children[0], value);\n return isFalse(first);\n case \"Literal\":\n return node.value;\n case TOK_PIPE:\n left = this.visit(node.children[0], value);\n return this.visit(node.children[1], left);\n case TOK_CURRENT:\n return value;\n case \"Function\":\n var resolvedArgs = [];\n for (i = 0; i < node.children.length; i++) {\n resolvedArgs.push(this.visit(node.children[i], value));\n }\n return this.runtime.callFunction(node.name, resolvedArgs);\n case \"ExpressionReference\":\n var refNode = node.children[0];\n // Tag the node with a specific attribute so the type\n // checker verify the type.\n refNode.jmespathType = TOK_EXPREF;\n return refNode;\n default:\n throw new Error(\"Unknown node type: \" + node.type);\n }\n },\n\n computeSliceParams: function(arrayLength, sliceParams) {\n var start = sliceParams[0];\n var stop = sliceParams[1];\n var step = sliceParams[2];\n var computed = [null, null, null];\n if (step === null) {\n step = 1;\n } else if (step === 0) {\n var error = new Error(\"Invalid slice, step cannot be 0\");\n error.name = \"RuntimeError\";\n throw error;\n }\n var stepValueNegative = step < 0 ? true : false;\n\n if (start === null) {\n start = stepValueNegative ? arrayLength - 1 : 0;\n } else {\n start = this.capSliceRange(arrayLength, start, step);\n }\n\n if (stop === null) {\n stop = stepValueNegative ? -1 : arrayLength;\n } else {\n stop = this.capSliceRange(arrayLength, stop, step);\n }\n computed[0] = start;\n computed[1] = stop;\n computed[2] = step;\n return computed;\n },\n\n capSliceRange: function(arrayLength, actualValue, step) {\n if (actualValue < 0) {\n actualValue += arrayLength;\n if (actualValue < 0) {\n actualValue = step < 0 ? -1 : 0;\n }\n } else if (actualValue >= arrayLength) {\n actualValue = step < 0 ? arrayLength - 1 : arrayLength;\n }\n return actualValue;\n }\n\n };\n\n function Runtime(interpreter) {\n this._interpreter = interpreter;\n this.functionTable = {\n // name: [function, ]\n // The can be:\n //\n // {\n // args: [[type1, type2], [type1, type2]],\n // variadic: true|false\n // }\n //\n // Each arg in the arg list is a list of valid types\n // (if the function is overloaded and supports multiple\n // types. If the type is \"any\" then no type checking\n // occurs on the argument. Variadic is optional\n // and if not provided is assumed to be false.\n abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]},\n avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},\n ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]},\n contains: {\n _func: this._functionContains,\n _signature: [{types: [TYPE_STRING, TYPE_ARRAY]},\n {types: [TYPE_ANY]}]},\n \"ends_with\": {\n _func: this._functionEndsWith,\n _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},\n floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]},\n length: {\n _func: this._functionLength,\n _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]},\n map: {\n _func: this._functionMap,\n _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]},\n max: {\n _func: this._functionMax,\n _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},\n \"merge\": {\n _func: this._functionMerge,\n _signature: [{types: [TYPE_OBJECT], variadic: true}]\n },\n \"max_by\": {\n _func: this._functionMaxBy,\n _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]\n },\n sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},\n \"starts_with\": {\n _func: this._functionStartsWith,\n _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},\n min: {\n _func: this._functionMin,\n _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},\n \"min_by\": {\n _func: this._functionMinBy,\n _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]\n },\n type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]},\n keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]},\n values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]},\n sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]},\n \"sort_by\": {\n _func: this._functionSortBy,\n _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]\n },\n join: {\n _func: this._functionJoin,\n _signature: [\n {types: [TYPE_STRING]},\n {types: [TYPE_ARRAY_STRING]}\n ]\n },\n reverse: {\n _func: this._functionReverse,\n _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]},\n \"to_array\": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]},\n \"to_string\": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]},\n \"to_number\": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]},\n \"not_null\": {\n _func: this._functionNotNull,\n _signature: [{types: [TYPE_ANY], variadic: true}]\n }\n };\n }\n\n Runtime.prototype = {\n callFunction: function(name, resolvedArgs) {\n var functionEntry = this.functionTable[name];\n if (functionEntry === undefined) {\n throw new Error(\"Unknown function: \" + name + \"()\");\n }\n this._validateArgs(name, resolvedArgs, functionEntry._signature);\n return functionEntry._func.call(this, resolvedArgs);\n },\n\n _validateArgs: function(name, args, signature) {\n // Validating the args requires validating\n // the correct arity and the correct type of each arg.\n // If the last argument is declared as variadic, then we need\n // a minimum number of args to be required. Otherwise it has to\n // be an exact amount.\n var pluralized;\n if (signature[signature.length - 1].variadic) {\n if (args.length < signature.length) {\n pluralized = signature.length === 1 ? \" argument\" : \" arguments\";\n throw new Error(\"ArgumentError: \" + name + \"() \" +\n \"takes at least\" + signature.length + pluralized +\n \" but received \" + args.length);\n }\n } else if (args.length !== signature.length) {\n pluralized = signature.length === 1 ? \" argument\" : \" arguments\";\n throw new Error(\"ArgumentError: \" + name + \"() \" +\n \"takes \" + signature.length + pluralized +\n \" but received \" + args.length);\n }\n var currentSpec;\n var actualType;\n var typeMatched;\n for (var i = 0; i < signature.length; i++) {\n typeMatched = false;\n currentSpec = signature[i].types;\n actualType = this._getTypeName(args[i]);\n for (var j = 0; j < currentSpec.length; j++) {\n if (this._typeMatches(actualType, currentSpec[j], args[i])) {\n typeMatched = true;\n break;\n }\n }\n if (!typeMatched) {\n throw new Error(\"TypeError: \" + name + \"() \" +\n \"expected argument \" + (i + 1) +\n \" to be type \" + currentSpec +\n \" but received type \" + actualType +\n \" instead.\");\n }\n }\n },\n\n _typeMatches: function(actual, expected, argValue) {\n if (expected === TYPE_ANY) {\n return true;\n }\n if (expected === TYPE_ARRAY_STRING ||\n expected === TYPE_ARRAY_NUMBER ||\n expected === TYPE_ARRAY) {\n // The expected type can either just be array,\n // or it can require a specific subtype (array of numbers).\n //\n // The simplest case is if \"array\" with no subtype is specified.\n if (expected === TYPE_ARRAY) {\n return actual === TYPE_ARRAY;\n } else if (actual === TYPE_ARRAY) {\n // Otherwise we need to check subtypes.\n // I think this has potential to be improved.\n var subtype;\n if (expected === TYPE_ARRAY_NUMBER) {\n subtype = TYPE_NUMBER;\n } else if (expected === TYPE_ARRAY_STRING) {\n subtype = TYPE_STRING;\n }\n for (var i = 0; i < argValue.length; i++) {\n if (!this._typeMatches(\n this._getTypeName(argValue[i]), subtype,\n argValue[i])) {\n return false;\n }\n }\n return true;\n }\n } else {\n return actual === expected;\n }\n },\n _getTypeName: function(obj) {\n switch (Object.prototype.toString.call(obj)) {\n case \"[object String]\":\n return TYPE_STRING;\n case \"[object Number]\":\n return TYPE_NUMBER;\n case \"[object Array]\":\n return TYPE_ARRAY;\n case \"[object Boolean]\":\n return TYPE_BOOLEAN;\n case \"[object Null]\":\n return TYPE_NULL;\n case \"[object Object]\":\n // Check if it's an expref. If it has, it's been\n // tagged with a jmespathType attr of 'Expref';\n if (obj.jmespathType === TOK_EXPREF) {\n return TYPE_EXPREF;\n } else {\n return TYPE_OBJECT;\n }\n }\n },\n\n _functionStartsWith: function(resolvedArgs) {\n return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0;\n },\n\n _functionEndsWith: function(resolvedArgs) {\n var searchStr = resolvedArgs[0];\n var suffix = resolvedArgs[1];\n return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1;\n },\n\n _functionReverse: function(resolvedArgs) {\n var typeName = this._getTypeName(resolvedArgs[0]);\n if (typeName === TYPE_STRING) {\n var originalStr = resolvedArgs[0];\n var reversedStr = \"\";\n for (var i = originalStr.length - 1; i >= 0; i--) {\n reversedStr += originalStr[i];\n }\n return reversedStr;\n } else {\n var reversedArray = resolvedArgs[0].slice(0);\n reversedArray.reverse();\n return reversedArray;\n }\n },\n\n _functionAbs: function(resolvedArgs) {\n return Math.abs(resolvedArgs[0]);\n },\n\n _functionCeil: function(resolvedArgs) {\n return Math.ceil(resolvedArgs[0]);\n },\n\n _functionAvg: function(resolvedArgs) {\n var sum = 0;\n var inputArray = resolvedArgs[0];\n for (var i = 0; i < inputArray.length; i++) {\n sum += inputArray[i];\n }\n return sum / inputArray.length;\n },\n\n _functionContains: function(resolvedArgs) {\n return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0;\n },\n\n _functionFloor: function(resolvedArgs) {\n return Math.floor(resolvedArgs[0]);\n },\n\n _functionLength: function(resolvedArgs) {\n if (!isObject(resolvedArgs[0])) {\n return resolvedArgs[0].length;\n } else {\n // As far as I can tell, there's no way to get the length\n // of an object without O(n) iteration through the object.\n return Object.keys(resolvedArgs[0]).length;\n }\n },\n\n _functionMap: function(resolvedArgs) {\n var mapped = [];\n var interpreter = this._interpreter;\n var exprefNode = resolvedArgs[0];\n var elements = resolvedArgs[1];\n for (var i = 0; i < elements.length; i++) {\n mapped.push(interpreter.visit(exprefNode, elements[i]));\n }\n return mapped;\n },\n\n _functionMerge: function(resolvedArgs) {\n var merged = {};\n for (var i = 0; i < resolvedArgs.length; i++) {\n var current = resolvedArgs[i];\n for (var key in current) {\n merged[key] = current[key];\n }\n }\n return merged;\n },\n\n _functionMax: function(resolvedArgs) {\n if (resolvedArgs[0].length > 0) {\n var typeName = this._getTypeName(resolvedArgs[0][0]);\n if (typeName === TYPE_NUMBER) {\n return Math.max.apply(Math, resolvedArgs[0]);\n } else {\n var elements = resolvedArgs[0];\n var maxElement = elements[0];\n for (var i = 1; i < elements.length; i++) {\n if (maxElement.localeCompare(elements[i]) < 0) {\n maxElement = elements[i];\n }\n }\n return maxElement;\n }\n } else {\n return null;\n }\n },\n\n _functionMin: function(resolvedArgs) {\n if (resolvedArgs[0].length > 0) {\n var typeName = this._getTypeName(resolvedArgs[0][0]);\n if (typeName === TYPE_NUMBER) {\n return Math.min.apply(Math, resolvedArgs[0]);\n } else {\n var elements = resolvedArgs[0];\n var minElement = elements[0];\n for (var i = 1; i < elements.length; i++) {\n if (elements[i].localeCompare(minElement) < 0) {\n minElement = elements[i];\n }\n }\n return minElement;\n }\n } else {\n return null;\n }\n },\n\n _functionSum: function(resolvedArgs) {\n var sum = 0;\n var listToSum = resolvedArgs[0];\n for (var i = 0; i < listToSum.length; i++) {\n sum += listToSum[i];\n }\n return sum;\n },\n\n _functionType: function(resolvedArgs) {\n switch (this._getTypeName(resolvedArgs[0])) {\n case TYPE_NUMBER:\n return \"number\";\n case TYPE_STRING:\n return \"string\";\n case TYPE_ARRAY:\n return \"array\";\n case TYPE_OBJECT:\n return \"object\";\n case TYPE_BOOLEAN:\n return \"boolean\";\n case TYPE_EXPREF:\n return \"expref\";\n case TYPE_NULL:\n return \"null\";\n }\n },\n\n _functionKeys: function(resolvedArgs) {\n return Object.keys(resolvedArgs[0]);\n },\n\n _functionValues: function(resolvedArgs) {\n var obj = resolvedArgs[0];\n var keys = Object.keys(obj);\n var values = [];\n for (var i = 0; i < keys.length; i++) {\n values.push(obj[keys[i]]);\n }\n return values;\n },\n\n _functionJoin: function(resolvedArgs) {\n var joinChar = resolvedArgs[0];\n var listJoin = resolvedArgs[1];\n return listJoin.join(joinChar);\n },\n\n _functionToArray: function(resolvedArgs) {\n if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) {\n return resolvedArgs[0];\n } else {\n return [resolvedArgs[0]];\n }\n },\n\n _functionToString: function(resolvedArgs) {\n if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) {\n return resolvedArgs[0];\n } else {\n return JSON.stringify(resolvedArgs[0]);\n }\n },\n\n _functionToNumber: function(resolvedArgs) {\n var typeName = this._getTypeName(resolvedArgs[0]);\n var convertedValue;\n if (typeName === TYPE_NUMBER) {\n return resolvedArgs[0];\n } else if (typeName === TYPE_STRING) {\n convertedValue = +resolvedArgs[0];\n if (!isNaN(convertedValue)) {\n return convertedValue;\n }\n }\n return null;\n },\n\n _functionNotNull: function(resolvedArgs) {\n for (var i = 0; i < resolvedArgs.length; i++) {\n if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) {\n return resolvedArgs[i];\n }\n }\n return null;\n },\n\n _functionSort: function(resolvedArgs) {\n var sortedArray = resolvedArgs[0].slice(0);\n sortedArray.sort();\n return sortedArray;\n },\n\n _functionSortBy: function(resolvedArgs) {\n var sortedArray = resolvedArgs[0].slice(0);\n if (sortedArray.length === 0) {\n return sortedArray;\n }\n var interpreter = this._interpreter;\n var exprefNode = resolvedArgs[1];\n var requiredType = this._getTypeName(\n interpreter.visit(exprefNode, sortedArray[0]));\n if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) {\n throw new Error(\"TypeError\");\n }\n var that = this;\n // In order to get a stable sort out of an unstable\n // sort algorithm, we decorate/sort/undecorate (DSU)\n // by creating a new list of [index, element] pairs.\n // In the cmp function, if the evaluated elements are\n // equal, then the index will be used as the tiebreaker.\n // After the decorated list has been sorted, it will be\n // undecorated to extract the original elements.\n var decorated = [];\n for (var i = 0; i < sortedArray.length; i++) {\n decorated.push([i, sortedArray[i]]);\n }\n decorated.sort(function(a, b) {\n var exprA = interpreter.visit(exprefNode, a[1]);\n var exprB = interpreter.visit(exprefNode, b[1]);\n if (that._getTypeName(exprA) !== requiredType) {\n throw new Error(\n \"TypeError: expected \" + requiredType + \", received \" +\n that._getTypeName(exprA));\n } else if (that._getTypeName(exprB) !== requiredType) {\n throw new Error(\n \"TypeError: expected \" + requiredType + \", received \" +\n that._getTypeName(exprB));\n }\n if (exprA > exprB) {\n return 1;\n } else if (exprA < exprB) {\n return -1;\n } else {\n // If they're equal compare the items by their\n // order to maintain relative order of equal keys\n // (i.e. to get a stable sort).\n return a[0] - b[0];\n }\n });\n // Undecorate: extract out the original list elements.\n for (var j = 0; j < decorated.length; j++) {\n sortedArray[j] = decorated[j][1];\n }\n return sortedArray;\n },\n\n _functionMaxBy: function(resolvedArgs) {\n var exprefNode = resolvedArgs[1];\n var resolvedArray = resolvedArgs[0];\n var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);\n var maxNumber = -Infinity;\n var maxRecord;\n var current;\n for (var i = 0; i < resolvedArray.length; i++) {\n current = keyFunction(resolvedArray[i]);\n if (current > maxNumber) {\n maxNumber = current;\n maxRecord = resolvedArray[i];\n }\n }\n return maxRecord;\n },\n\n _functionMinBy: function(resolvedArgs) {\n var exprefNode = resolvedArgs[1];\n var resolvedArray = resolvedArgs[0];\n var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);\n var minNumber = Infinity;\n var minRecord;\n var current;\n for (var i = 0; i < resolvedArray.length; i++) {\n current = keyFunction(resolvedArray[i]);\n if (current < minNumber) {\n minNumber = current;\n minRecord = resolvedArray[i];\n }\n }\n return minRecord;\n },\n\n createKeyFunction: function(exprefNode, allowedTypes) {\n var that = this;\n var interpreter = this._interpreter;\n var keyFunc = function(x) {\n var current = interpreter.visit(exprefNode, x);\n if (allowedTypes.indexOf(that._getTypeName(current)) < 0) {\n var msg = \"TypeError: expected one of \" + allowedTypes +\n \", received \" + that._getTypeName(current);\n throw new Error(msg);\n }\n return current;\n };\n return keyFunc;\n }\n\n };\n\n function compile(stream) {\n var parser = new Parser();\n var ast = parser.parse(stream);\n return ast;\n }\n\n function tokenize(stream) {\n var lexer = new Lexer();\n return lexer.tokenize(stream);\n }\n\n function search(data, expression) {\n var parser = new Parser();\n // This needs to be improved. Both the interpreter and runtime depend on\n // each other. The runtime needs the interpreter to support exprefs.\n // There's likely a clean way to avoid the cyclic dependency.\n var runtime = new Runtime();\n var interpreter = new TreeInterpreter(runtime);\n runtime._interpreter = interpreter;\n var node = parser.parse(expression);\n return interpreter.search(node, data);\n }\n\n exports.tokenize = tokenize;\n exports.compile = compile;\n exports.search = search;\n exports.strictDeepEqual = strictDeepEqual;\n})(typeof exports === \"undefined\" ? this.jmespath = {} : exports);\n","module.exports = Pager\n\nfunction Pager (pageSize, opts) {\n if (!(this instanceof Pager)) return new Pager(pageSize, opts)\n\n this.length = 0\n this.updates = []\n this.path = new Uint16Array(4)\n this.pages = new Array(32768)\n this.maxPages = this.pages.length\n this.level = 0\n this.pageSize = pageSize || 1024\n this.deduplicate = opts ? opts.deduplicate : null\n this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null\n}\n\nPager.prototype.updated = function (page) {\n while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) {\n page.deduplicate++\n if (page.deduplicate === this.deduplicate.length) {\n page.deduplicate = 0\n if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate\n break\n }\n }\n if (page.updated || !this.updates) return\n page.updated = true\n this.updates.push(page)\n}\n\nPager.prototype.lastUpdate = function () {\n if (!this.updates || !this.updates.length) return null\n var page = this.updates.pop()\n page.updated = false\n return page\n}\n\nPager.prototype._array = function (i, noAllocate) {\n if (i >= this.maxPages) {\n if (noAllocate) return\n grow(this, i)\n }\n\n factor(i, this.path)\n\n var arr = this.pages\n\n for (var j = this.level; j > 0; j--) {\n var p = this.path[j]\n var next = arr[p]\n\n if (!next) {\n if (noAllocate) return\n next = arr[p] = new Array(32768)\n }\n\n arr = next\n }\n\n return arr\n}\n\nPager.prototype.get = function (i, noAllocate) {\n var arr = this._array(i, noAllocate)\n var first = this.path[0]\n var page = arr && arr[first]\n\n if (!page && !noAllocate) {\n page = arr[first] = new Page(i, alloc(this.pageSize))\n if (i >= this.length) this.length = i + 1\n }\n\n if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) {\n page.buffer = copy(page.buffer)\n page.deduplicate = 0\n }\n\n return page\n}\n\nPager.prototype.set = function (i, buf) {\n var arr = this._array(i, false)\n var first = this.path[0]\n\n if (i >= this.length) this.length = i + 1\n\n if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) {\n arr[first] = undefined\n return\n }\n\n if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) {\n buf = this.deduplicate\n }\n\n var page = arr[first]\n var b = truncate(buf, this.pageSize)\n\n if (page) page.buffer = b\n else arr[first] = new Page(i, b)\n}\n\nPager.prototype.toBuffer = function () {\n var list = new Array(this.length)\n var empty = alloc(this.pageSize)\n var ptr = 0\n\n while (ptr < list.length) {\n var arr = this._array(ptr, true)\n for (var i = 0; i < 32768 && ptr < list.length; i++) {\n list[ptr++] = (arr && arr[i]) ? arr[i].buffer : empty\n }\n }\n\n return Buffer.concat(list)\n}\n\nfunction grow (pager, index) {\n while (pager.maxPages < index) {\n var old = pager.pages\n pager.pages = new Array(32768)\n pager.pages[0] = old\n pager.level++\n pager.maxPages *= 32768\n }\n}\n\nfunction truncate (buf, len) {\n if (buf.length === len) return buf\n if (buf.length > len) return buf.slice(0, len)\n var cpy = alloc(len)\n buf.copy(cpy)\n return cpy\n}\n\nfunction alloc (size) {\n if (Buffer.alloc) return Buffer.alloc(size)\n var buf = new Buffer(size)\n buf.fill(0)\n return buf\n}\n\nfunction copy (buf) {\n var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length)\n buf.copy(cpy)\n return cpy\n}\n\nfunction Page (i, buf) {\n this.offset = i * buf.length\n this.buffer = buf\n this.updated = false\n this.deduplicate = 0\n}\n\nfunction factor (n, out) {\n n = (n - (out[0] = (n & 32767))) / 32768\n n = (n - (out[1] = (n & 32767))) / 32768\n out[3] = ((n - (out[2] = (n & 32767))) / 32768) & 32767\n}\n","'use strict';\n\n// Core module\nconst core = require('./lib/core');\nconst Instrumentation = require('./lib/apm');\n\n// Set up the connect function\nconst connect = require('./lib/mongo_client').connect;\n\n// Expose error class\nconnect.MongoError = core.MongoError;\nconnect.MongoNetworkError = core.MongoNetworkError;\nconnect.MongoTimeoutError = core.MongoTimeoutError;\nconnect.MongoServerSelectionError = core.MongoServerSelectionError;\nconnect.MongoParseError = core.MongoParseError;\nconnect.MongoWriteConcernError = core.MongoWriteConcernError;\nconnect.MongoBulkWriteError = require('./lib/bulk/common').BulkWriteError;\nconnect.BulkWriteError = connect.MongoBulkWriteError;\n\n// Actual driver classes exported\nconnect.Admin = require('./lib/admin');\nconnect.MongoClient = require('./lib/mongo_client');\nconnect.Db = require('./lib/db');\nconnect.Collection = require('./lib/collection');\nconnect.Server = require('./lib/topologies/server');\nconnect.ReplSet = require('./lib/topologies/replset');\nconnect.Mongos = require('./lib/topologies/mongos');\nconnect.ReadPreference = core.ReadPreference;\nconnect.GridStore = require('./lib/gridfs/grid_store');\nconnect.Chunk = require('./lib/gridfs/chunk');\nconnect.Logger = core.Logger;\nconnect.AggregationCursor = require('./lib/aggregation_cursor');\nconnect.CommandCursor = require('./lib/command_cursor');\nconnect.Cursor = require('./lib/cursor');\nconnect.GridFSBucket = require('./lib/gridfs-stream');\n// Exported to be used in tests not to be used anywhere else\nconnect.CoreServer = core.Server;\nconnect.CoreConnection = core.Connection;\n\n// BSON types exported\nconnect.Binary = core.BSON.Binary;\nconnect.Code = core.BSON.Code;\nconnect.Map = core.BSON.Map;\nconnect.DBRef = core.BSON.DBRef;\nconnect.Double = core.BSON.Double;\nconnect.Int32 = core.BSON.Int32;\nconnect.Long = core.BSON.Long;\nconnect.MinKey = core.BSON.MinKey;\nconnect.MaxKey = core.BSON.MaxKey;\nconnect.ObjectID = core.BSON.ObjectID;\nconnect.ObjectId = core.BSON.ObjectID;\nconnect.Symbol = core.BSON.Symbol;\nconnect.Timestamp = core.BSON.Timestamp;\nconnect.BSONRegExp = core.BSON.BSONRegExp;\nconnect.Decimal128 = core.BSON.Decimal128;\n\n// Add connect method\nconnect.connect = connect;\n\n// Set up the instrumentation method\nconnect.instrument = function(options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n const instrumentation = new Instrumentation();\n instrumentation.instrument(connect.MongoClient, callback);\n return instrumentation;\n};\n\n// Set our exports to be the connect function\nmodule.exports = connect;\n","'use strict';\n\nconst applyWriteConcern = require('./utils').applyWriteConcern;\n\nconst AddUserOperation = require('./operations/add_user');\nconst ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command');\nconst RemoveUserOperation = require('./operations/remove_user');\nconst ValidateCollectionOperation = require('./operations/validate_collection');\nconst ListDatabasesOperation = require('./operations/list_databases');\n\nconst executeOperation = require('./operations/execute_operation');\n\n/**\n * @fileOverview The **Admin** class is an internal class that allows convenient access to\n * the admin functionality and commands for MongoDB.\n *\n * **ADMIN Cannot directly be instantiated**\n * @example\n * const MongoClient = require('mongodb').MongoClient;\n * const test = require('assert');\n * // Connection url\n * const url = 'mongodb://localhost:27017';\n * // Database Name\n * const dbName = 'test';\n *\n * // Connect using MongoClient\n * MongoClient.connect(url, function(err, client) {\n * // Use the admin database for the operation\n * const adminDb = client.db(dbName).admin();\n *\n * // List all the available databases\n * adminDb.listDatabases(function(err, dbs) {\n * test.equal(null, err);\n * test.ok(dbs.databases.length > 0);\n * client.close();\n * });\n * });\n */\n\n/**\n * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly)\n * @class\n * @return {Admin} a collection instance.\n */\nfunction Admin(db, topology, promiseLibrary) {\n if (!(this instanceof Admin)) return new Admin(db, topology);\n\n // Internal state\n this.s = {\n db: db,\n topology: topology,\n promiseLibrary: promiseLibrary\n };\n}\n\n/**\n * The callback format for results\n * @callback Admin~resultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {object} result The result object if the command was executed successfully.\n */\n\n/**\n * Execute a command\n * @method\n * @param {object} command The command hash\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.\n * @param {Admin~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nAdmin.prototype.command = function(command, options, callback) {\n const args = Array.prototype.slice.call(arguments, 1);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n options = args.length ? args.shift() : {};\n\n const commandOperation = new ExecuteDbAdminCommandOperation(this.s.db, command, options);\n\n return executeOperation(this.s.db.s.topology, commandOperation, callback);\n};\n\n/**\n * Retrieve the server information for the current\n * instance of the db client\n *\n * @param {Object} [options] optional parameters for this operation\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Admin~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nAdmin.prototype.buildInfo = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const cmd = { buildinfo: 1 };\n\n const buildInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options);\n\n return executeOperation(this.s.db.s.topology, buildInfoOperation, callback);\n};\n\n/**\n * Retrieve the server information for the current\n * instance of the db client\n *\n * @param {Object} [options] optional parameters for this operation\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Admin~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nAdmin.prototype.serverInfo = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const cmd = { buildinfo: 1 };\n\n const serverInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options);\n\n return executeOperation(this.s.db.s.topology, serverInfoOperation, callback);\n};\n\n/**\n * Retrieve this db's server status.\n *\n * @param {Object} [options] optional parameters for this operation\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Admin~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nAdmin.prototype.serverStatus = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const serverStatusOperation = new ExecuteDbAdminCommandOperation(\n this.s.db,\n { serverStatus: 1 },\n options\n );\n\n return executeOperation(this.s.db.s.topology, serverStatusOperation, callback);\n};\n\n/**\n * Ping the MongoDB server and retrieve results\n *\n * @param {Object} [options] optional parameters for this operation\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Admin~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nAdmin.prototype.ping = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const cmd = { ping: 1 };\n\n const pingOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options);\n\n return executeOperation(this.s.db.s.topology, pingOperation, callback);\n};\n\n/**\n * Add a user to the database.\n * @method\n * @param {string} username The username.\n * @param {string} password The password.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.fsync=false] Specify a file sync write concern.\n * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher)\n * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher)\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Admin~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nAdmin.prototype.addUser = function(username, password, options, callback) {\n const args = Array.prototype.slice.call(arguments, 2);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n\n // Special case where there is no password ($external users)\n if (typeof username === 'string' && password != null && typeof password === 'object') {\n options = password;\n password = null;\n }\n\n options = args.length ? args.shift() : {};\n options = Object.assign({}, options);\n // Get the options\n options = applyWriteConcern(options, { db: this.s.db });\n // Set the db name to admin\n options.dbName = 'admin';\n\n const addUserOperation = new AddUserOperation(this.s.db, username, password, options);\n\n return executeOperation(this.s.db.s.topology, addUserOperation, callback);\n};\n\n/**\n * Remove a user from a database\n * @method\n * @param {string} username The username.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.fsync=false] Specify a file sync write concern.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Admin~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nAdmin.prototype.removeUser = function(username, options, callback) {\n const args = Array.prototype.slice.call(arguments, 1);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n\n options = args.length ? args.shift() : {};\n options = Object.assign({}, options);\n // Get the options\n options = applyWriteConcern(options, { db: this.s.db });\n // Set the db name\n options.dbName = 'admin';\n\n const removeUserOperation = new RemoveUserOperation(this.s.db, username, options);\n\n return executeOperation(this.s.db.s.topology, removeUserOperation, callback);\n};\n\n/**\n * Validate an existing collection\n *\n * @param {string} collectionName The name of the collection to validate.\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.background] Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+)\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Admin~resultCallback} [callback] The command result callback.\n * @return {Promise} returns Promise if no callback passed\n */\nAdmin.prototype.validateCollection = function(collectionName, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const validateCollectionOperation = new ValidateCollectionOperation(\n this,\n collectionName,\n options\n );\n\n return executeOperation(this.s.db.s.topology, validateCollectionOperation, callback);\n};\n\n/**\n * List the available databases\n *\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Admin~resultCallback} [callback] The command result callback.\n * @return {Promise} returns Promise if no callback passed\n */\nAdmin.prototype.listDatabases = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeOperation(\n this.s.db.s.topology,\n new ListDatabasesOperation(this.s.db, options),\n callback\n );\n};\n\n/**\n * Get ReplicaSet status\n *\n * @param {Object} [options] optional parameters for this operation\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Admin~resultCallback} [callback] The command result callback.\n * @return {Promise} returns Promise if no callback passed\n */\nAdmin.prototype.replSetGetStatus = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const replSetGetStatusOperation = new ExecuteDbAdminCommandOperation(\n this.s.db,\n { replSetGetStatus: 1 },\n options\n );\n\n return executeOperation(this.s.db.s.topology, replSetGetStatusOperation, callback);\n};\n\nmodule.exports = Admin;\n","'use strict';\n\nconst MongoError = require('./core').MongoError;\nconst Cursor = require('./cursor');\nconst CursorState = require('./core/cursor').CursorState;\nconst deprecate = require('util').deprecate;\n\n/**\n * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB\n * allowing for iteration over the results returned from the underlying query. It supports\n * one by one document iteration, conversion to an array or can be iterated as a Node 4.X\n * or higher stream\n *\n * **AGGREGATIONCURSOR Cannot directly be instantiated**\n * @example\n * const MongoClient = require('mongodb').MongoClient;\n * const test = require('assert');\n * // Connection url\n * const url = 'mongodb://localhost:27017';\n * // Database Name\n * const dbName = 'test';\n * // Connect using MongoClient\n * MongoClient.connect(url, function(err, client) {\n * // Create a collection we want to drop later\n * const col = client.db(dbName).collection('createIndexExample1');\n * // Insert a bunch of documents\n * col.insert([{a:1, b:1}\n * , {a:2, b:2}, {a:3, b:3}\n * , {a:4, b:4}], {w:1}, function(err, result) {\n * test.equal(null, err);\n * // Show that duplicate records got dropped\n * col.aggregation({}, {cursor: {}}).toArray(function(err, items) {\n * test.equal(null, err);\n * test.equal(4, items.length);\n * client.close();\n * });\n * });\n * });\n */\n\n/**\n * Namespace provided by the browser.\n * @external Readable\n */\n\n/**\n * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly)\n * @class AggregationCursor\n * @extends external:Readable\n * @fires AggregationCursor#data\n * @fires AggregationCursor#end\n * @fires AggregationCursor#close\n * @fires AggregationCursor#readable\n * @return {AggregationCursor} an AggregationCursor instance.\n */\nclass AggregationCursor extends Cursor {\n constructor(topology, operation, options) {\n super(topology, operation, options);\n }\n\n /**\n * Set the batch size for the cursor.\n * @method\n * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @throws {MongoError}\n * @return {AggregationCursor}\n */\n batchSize(value) {\n if (this.s.state === CursorState.CLOSED || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n if (typeof value !== 'number') {\n throw MongoError.create({ message: 'batchSize requires an integer', driver: true });\n }\n\n this.operation.options.batchSize = value;\n this.setCursorBatchSize(value);\n return this;\n }\n\n /**\n * Add a geoNear stage to the aggregation pipeline\n * @method\n * @param {object} document The geoNear stage document.\n * @return {AggregationCursor}\n */\n geoNear(document) {\n this.operation.addToPipeline({ $geoNear: document });\n return this;\n }\n\n /**\n * Add a group stage to the aggregation pipeline\n * @method\n * @param {object} document The group stage document.\n * @return {AggregationCursor}\n */\n group(document) {\n this.operation.addToPipeline({ $group: document });\n return this;\n }\n\n /**\n * Add a limit stage to the aggregation pipeline\n * @method\n * @param {number} value The state limit value.\n * @return {AggregationCursor}\n */\n limit(value) {\n this.operation.addToPipeline({ $limit: value });\n return this;\n }\n\n /**\n * Add a match stage to the aggregation pipeline\n * @method\n * @param {object} document The match stage document.\n * @return {AggregationCursor}\n */\n match(document) {\n this.operation.addToPipeline({ $match: document });\n return this;\n }\n\n /**\n * Add a maxTimeMS stage to the aggregation pipeline\n * @method\n * @param {number} value The state maxTimeMS value.\n * @return {AggregationCursor}\n */\n maxTimeMS(value) {\n this.operation.options.maxTimeMS = value;\n return this;\n }\n\n /**\n * Add a out stage to the aggregation pipeline\n * @method\n * @param {number} destination The destination name.\n * @return {AggregationCursor}\n */\n out(destination) {\n this.operation.addToPipeline({ $out: destination });\n return this;\n }\n\n /**\n * Add a project stage to the aggregation pipeline\n * @method\n * @param {object} document The project stage document.\n * @return {AggregationCursor}\n */\n project(document) {\n this.operation.addToPipeline({ $project: document });\n return this;\n }\n\n /**\n * Add a lookup stage to the aggregation pipeline\n * @method\n * @param {object} document The lookup stage document.\n * @return {AggregationCursor}\n */\n lookup(document) {\n this.operation.addToPipeline({ $lookup: document });\n return this;\n }\n\n /**\n * Add a redact stage to the aggregation pipeline\n * @method\n * @param {object} document The redact stage document.\n * @return {AggregationCursor}\n */\n redact(document) {\n this.operation.addToPipeline({ $redact: document });\n return this;\n }\n\n /**\n * Add a skip stage to the aggregation pipeline\n * @method\n * @param {number} value The state skip value.\n * @return {AggregationCursor}\n */\n skip(value) {\n this.operation.addToPipeline({ $skip: value });\n return this;\n }\n\n /**\n * Add a sort stage to the aggregation pipeline\n * @method\n * @param {object} document The sort stage document.\n * @return {AggregationCursor}\n */\n sort(document) {\n this.operation.addToPipeline({ $sort: document });\n return this;\n }\n\n /**\n * Add a unwind stage to the aggregation pipeline\n * @method\n * @param {number} field The unwind field name.\n * @return {AggregationCursor}\n */\n unwind(field) {\n this.operation.addToPipeline({ $unwind: field });\n return this;\n }\n\n /**\n * Return the cursor logger\n * @method\n * @return {Logger} return the cursor logger\n * @ignore\n */\n getLogger() {\n return this.logger;\n }\n}\n\n// aliases\nAggregationCursor.prototype.get = AggregationCursor.prototype.toArray;\n\n// deprecated methods\ndeprecate(\n AggregationCursor.prototype.geoNear,\n 'The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2.'\n);\n\n/**\n * AggregationCursor stream data event, fired for each document in the cursor.\n *\n * @event AggregationCursor#data\n * @type {object}\n */\n\n/**\n * AggregationCursor stream end event\n *\n * @event AggregationCursor#end\n * @type {null}\n */\n\n/**\n * AggregationCursor stream close event\n *\n * @event AggregationCursor#close\n * @type {null}\n */\n\n/**\n * AggregationCursor stream readable event\n *\n * @event AggregationCursor#readable\n * @type {null}\n */\n\n/**\n * Get the next available document from the cursor, returns null if no more documents are available.\n * @function AggregationCursor.prototype.next\n * @param {AggregationCursor~resultCallback} [callback] The result callback.\n * @throws {MongoError}\n * @return {Promise} returns Promise if no callback passed\n */\n\n/**\n * Check if there is any document still available in the cursor\n * @function AggregationCursor.prototype.hasNext\n * @param {AggregationCursor~resultCallback} [callback] The result callback.\n * @throws {MongoError}\n * @return {Promise} returns Promise if no callback passed\n */\n\n/**\n * The callback format for results\n * @callback AggregationCursor~toArrayResultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {object[]} documents All the documents the satisfy the cursor.\n */\n\n/**\n * Returns an array of documents. The caller is responsible for making sure that there\n * is enough memory to store the results. Note that the array only contain partial\n * results when this cursor had been previously accessed. In that case,\n * cursor.rewind() can be used to reset the cursor.\n * @method AggregationCursor.prototype.toArray\n * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback.\n * @throws {MongoError}\n * @return {Promise} returns Promise if no callback passed\n */\n\n/**\n * The callback format for results\n * @callback AggregationCursor~resultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {(object|null)} result The result object if the command was executed successfully.\n */\n\n/**\n * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,\n * not all of the elements will be iterated if this cursor had been previously accessed.\n * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike\n * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements\n * at any given time if batch size is specified. Otherwise, the caller is responsible\n * for making sure that the entire result can fit the memory.\n * @method AggregationCursor.prototype.each\n * @deprecated\n * @param {AggregationCursor~resultCallback} callback The result callback.\n * @throws {MongoError}\n * @return {null}\n */\n\n/**\n * Close the cursor, sending a AggregationCursor command and emitting close.\n * @method AggregationCursor.prototype.close\n * @param {AggregationCursor~resultCallback} [callback] The result callback.\n * @return {Promise} returns Promise if no callback passed\n */\n\n/**\n * Is the cursor closed\n * @method AggregationCursor.prototype.isClosed\n * @return {boolean}\n */\n\n/**\n * Execute the explain for the cursor\n * @method AggregationCursor.prototype.explain\n * @param {AggregationCursor~resultCallback} [callback] The result callback.\n * @return {Promise} returns Promise if no callback passed\n */\n\n/**\n * Clone the cursor\n * @function AggregationCursor.prototype.clone\n * @return {AggregationCursor}\n */\n\n/**\n * Resets the cursor\n * @function AggregationCursor.prototype.rewind\n * @return {AggregationCursor}\n */\n\n/**\n * The callback format for the forEach iterator method\n * @callback AggregationCursor~iteratorCallback\n * @param {Object} doc An emitted document for the iterator\n */\n\n/**\n * The callback error format for the forEach iterator method\n * @callback AggregationCursor~endCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n */\n\n/**\n * Iterates over all the documents for this cursor using the iterator, callback pattern.\n * @method AggregationCursor.prototype.forEach\n * @param {AggregationCursor~iteratorCallback} iterator The iteration callback.\n * @param {AggregationCursor~endCallback} callback The end callback.\n * @throws {MongoError}\n * @return {null}\n */\n\nmodule.exports = AggregationCursor;\n","'use strict';\nconst EventEmitter = require('events').EventEmitter;\n\nclass Instrumentation extends EventEmitter {\n constructor() {\n super();\n }\n\n instrument(MongoClient, callback) {\n // store a reference to the original functions\n this.$MongoClient = MongoClient;\n const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect);\n\n const instrumentation = this;\n MongoClient.prototype.connect = function(callback) {\n this.s.options.monitorCommands = true;\n this.on('commandStarted', event => instrumentation.emit('started', event));\n this.on('commandSucceeded', event => instrumentation.emit('succeeded', event));\n this.on('commandFailed', event => instrumentation.emit('failed', event));\n return $prototypeConnect.call(this, callback);\n };\n\n if (typeof callback === 'function') callback(null, this);\n }\n\n uninstrument() {\n this.$MongoClient.prototype.connect = this.$prototypeConnect;\n }\n}\n\nmodule.exports = Instrumentation;\n","'use strict';\n\n// async function* asyncIterator() {\n// while (true) {\n// const value = await this.next();\n// if (!value) {\n// await this.close();\n// return;\n// }\n\n// yield value;\n// }\n// }\n\n// TODO: change this to the async generator function above\nfunction asyncIterator() {\n const cursor = this;\n\n return {\n next: function() {\n return Promise.resolve()\n .then(() => cursor.next())\n .then(value => {\n if (!value) {\n return cursor.close().then(() => ({ value, done: true }));\n }\n return { value, done: false };\n });\n }\n };\n}\n\nexports.asyncIterator = asyncIterator;\n","'use strict';\n\nconst Long = require('../core').BSON.Long;\nconst MongoError = require('../core').MongoError;\nconst ObjectID = require('../core').BSON.ObjectID;\nconst BSON = require('../core').BSON;\nconst MongoWriteConcernError = require('../core').MongoWriteConcernError;\nconst toError = require('../utils').toError;\nconst handleCallback = require('../utils').handleCallback;\nconst applyRetryableWrites = require('../utils').applyRetryableWrites;\nconst applyWriteConcern = require('../utils').applyWriteConcern;\nconst executeLegacyOperation = require('../utils').executeLegacyOperation;\nconst isPromiseLike = require('../utils').isPromiseLike;\nconst hasAtomicOperators = require('../utils').hasAtomicOperators;\nconst maxWireVersion = require('../core/utils').maxWireVersion;\n\n// Error codes\nconst WRITE_CONCERN_ERROR = 64;\n\n// Insert types\nconst INSERT = 1;\nconst UPDATE = 2;\nconst REMOVE = 3;\n\nconst bson = new BSON([\n BSON.Binary,\n BSON.Code,\n BSON.DBRef,\n BSON.Decimal128,\n BSON.Double,\n BSON.Int32,\n BSON.Long,\n BSON.Map,\n BSON.MaxKey,\n BSON.MinKey,\n BSON.ObjectId,\n BSON.BSONRegExp,\n BSON.Symbol,\n BSON.Timestamp\n]);\n\n/**\n * Keeps the state of a unordered batch so we can rewrite the results\n * correctly after command execution\n * @ignore\n */\nclass Batch {\n constructor(batchType, originalZeroIndex) {\n this.originalZeroIndex = originalZeroIndex;\n this.currentIndex = 0;\n this.originalIndexes = [];\n this.batchType = batchType;\n this.operations = [];\n this.size = 0;\n this.sizeBytes = 0;\n }\n}\n\n/**\n * @classdesc\n * The result of a bulk write.\n */\nclass BulkWriteResult {\n /**\n * Create a new BulkWriteResult instance\n *\n * **NOTE:** Internal Type, do not instantiate directly\n */\n constructor(bulkResult) {\n this.result = bulkResult;\n }\n\n /**\n * Evaluates to true if the bulk operation correctly executes\n * @type {boolean}\n */\n get ok() {\n return this.result.ok;\n }\n\n /**\n * The number of inserted documents\n * @type {number}\n */\n get nInserted() {\n return this.result.nInserted;\n }\n\n /**\n * Number of upserted documents\n * @type {number}\n */\n get nUpserted() {\n return this.result.nUpserted;\n }\n\n /**\n * Number of matched documents\n * @type {number}\n */\n get nMatched() {\n return this.result.nMatched;\n }\n\n /**\n * Number of documents updated physically on disk\n * @type {number}\n */\n get nModified() {\n return this.result.nModified;\n }\n\n /**\n * Number of removed documents\n * @type {number}\n */\n get nRemoved() {\n return this.result.nRemoved;\n }\n\n /**\n * Returns an array of all inserted ids\n *\n * @return {object[]}\n */\n getInsertedIds() {\n return this.result.insertedIds;\n }\n\n /**\n * Returns an array of all upserted ids\n *\n * @return {object[]}\n */\n getUpsertedIds() {\n return this.result.upserted;\n }\n\n /**\n * Returns the upserted id at the given index\n *\n * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index\n * @return {object}\n */\n getUpsertedIdAt(index) {\n return this.result.upserted[index];\n }\n\n /**\n * Returns raw internal result\n *\n * @return {object}\n */\n getRawResponse() {\n return this.result;\n }\n\n /**\n * Returns true if the bulk operation contains a write error\n *\n * @return {boolean}\n */\n hasWriteErrors() {\n return this.result.writeErrors.length > 0;\n }\n\n /**\n * Returns the number of write errors off the bulk operation\n *\n * @return {number}\n */\n getWriteErrorCount() {\n return this.result.writeErrors.length;\n }\n\n /**\n * Returns a specific write error object\n *\n * @param {number} index of the write error to return, returns null if there is no result for passed in index\n * @return {WriteError}\n */\n getWriteErrorAt(index) {\n if (index < this.result.writeErrors.length) {\n return this.result.writeErrors[index];\n }\n return null;\n }\n\n /**\n * Retrieve all write errors\n *\n * @return {WriteError[]}\n */\n getWriteErrors() {\n return this.result.writeErrors;\n }\n\n /**\n * Retrieve lastOp if available\n *\n * @return {object}\n */\n getLastOp() {\n return this.result.lastOp;\n }\n\n /**\n * Retrieve the write concern error if any\n *\n * @return {WriteConcernError}\n */\n getWriteConcernError() {\n if (this.result.writeConcernErrors.length === 0) {\n return null;\n } else if (this.result.writeConcernErrors.length === 1) {\n // Return the error\n return this.result.writeConcernErrors[0];\n } else {\n // Combine the errors\n let errmsg = '';\n for (let i = 0; i < this.result.writeConcernErrors.length; i++) {\n const err = this.result.writeConcernErrors[i];\n errmsg = errmsg + err.errmsg;\n\n // TODO: Something better\n if (i === 0) errmsg = errmsg + ' and ';\n }\n\n return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR });\n }\n }\n\n /**\n * @return {object}\n */\n toJSON() {\n return this.result;\n }\n\n /**\n * @return {string}\n */\n toString() {\n return `BulkWriteResult(${this.toJSON(this.result)})`;\n }\n\n /**\n * @return {boolean}\n */\n isOk() {\n return this.result.ok === 1;\n }\n}\n\n/**\n * @classdesc An error representing a failure by the server to apply the requested write concern to the bulk operation.\n */\nclass WriteConcernError {\n /**\n * Create a new WriteConcernError instance\n *\n * **NOTE:** Internal Type, do not instantiate directly\n */\n constructor(err) {\n this.err = err;\n }\n\n /**\n * Write concern error code.\n * @type {number}\n */\n get code() {\n return this.err.code;\n }\n\n /**\n * Write concern error message.\n * @type {string}\n */\n get errmsg() {\n return this.err.errmsg;\n }\n\n /**\n * @return {object}\n */\n toJSON() {\n return { code: this.err.code, errmsg: this.err.errmsg };\n }\n\n /**\n * @return {string}\n */\n toString() {\n return `WriteConcernError(${this.err.errmsg})`;\n }\n}\n\n/**\n * @classdesc An error that occurred during a BulkWrite on the server.\n */\nclass WriteError {\n /**\n * Create a new WriteError instance\n *\n * **NOTE:** Internal Type, do not instantiate directly\n */\n constructor(err) {\n this.err = err;\n }\n\n /**\n * WriteError code.\n * @type {number}\n */\n get code() {\n return this.err.code;\n }\n\n /**\n * WriteError original bulk operation index.\n * @type {number}\n */\n get index() {\n return this.err.index;\n }\n\n /**\n * WriteError message.\n * @type {string}\n */\n get errmsg() {\n return this.err.errmsg;\n }\n\n /**\n * Returns the underlying operation that caused the error\n * @return {object}\n */\n getOperation() {\n return this.err.op;\n }\n\n /**\n * @return {object}\n */\n toJSON() {\n return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op };\n }\n\n /**\n * @return {string}\n */\n toString() {\n return `WriteError(${JSON.stringify(this.toJSON())})`;\n }\n}\n\n/**\n * Merges results into shared data structure\n * @ignore\n */\nfunction mergeBatchResults(batch, bulkResult, err, result) {\n // If we have an error set the result to be the err object\n if (err) {\n result = err;\n } else if (result && result.result) {\n result = result.result;\n } else if (result == null) {\n return;\n }\n\n // Do we have a top level error stop processing and return\n if (result.ok === 0 && bulkResult.ok === 1) {\n bulkResult.ok = 0;\n\n const writeError = {\n index: 0,\n code: result.code || 0,\n errmsg: result.message,\n op: batch.operations[0]\n };\n\n bulkResult.writeErrors.push(new WriteError(writeError));\n return;\n } else if (result.ok === 0 && bulkResult.ok === 0) {\n return;\n }\n\n // Deal with opTime if available\n if (result.opTime || result.lastOp) {\n const opTime = result.lastOp || result.opTime;\n let lastOpTS = null;\n let lastOpT = null;\n\n // We have a time stamp\n if (opTime && opTime._bsontype === 'Timestamp') {\n if (bulkResult.lastOp == null) {\n bulkResult.lastOp = opTime;\n } else if (opTime.greaterThan(bulkResult.lastOp)) {\n bulkResult.lastOp = opTime;\n }\n } else {\n // Existing TS\n if (bulkResult.lastOp) {\n lastOpTS =\n typeof bulkResult.lastOp.ts === 'number'\n ? Long.fromNumber(bulkResult.lastOp.ts)\n : bulkResult.lastOp.ts;\n lastOpT =\n typeof bulkResult.lastOp.t === 'number'\n ? Long.fromNumber(bulkResult.lastOp.t)\n : bulkResult.lastOp.t;\n }\n\n // Current OpTime TS\n const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts;\n const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t;\n\n // Compare the opTime's\n if (bulkResult.lastOp == null) {\n bulkResult.lastOp = opTime;\n } else if (opTimeTS.greaterThan(lastOpTS)) {\n bulkResult.lastOp = opTime;\n } else if (opTimeTS.equals(lastOpTS)) {\n if (opTimeT.greaterThan(lastOpT)) {\n bulkResult.lastOp = opTime;\n }\n }\n }\n }\n\n // If we have an insert Batch type\n if (batch.batchType === INSERT && result.n) {\n bulkResult.nInserted = bulkResult.nInserted + result.n;\n }\n\n // If we have an insert Batch type\n if (batch.batchType === REMOVE && result.n) {\n bulkResult.nRemoved = bulkResult.nRemoved + result.n;\n }\n\n let nUpserted = 0;\n\n // We have an array of upserted values, we need to rewrite the indexes\n if (Array.isArray(result.upserted)) {\n nUpserted = result.upserted.length;\n\n for (let i = 0; i < result.upserted.length; i++) {\n bulkResult.upserted.push({\n index: result.upserted[i].index + batch.originalZeroIndex,\n _id: result.upserted[i]._id\n });\n }\n } else if (result.upserted) {\n nUpserted = 1;\n\n bulkResult.upserted.push({\n index: batch.originalZeroIndex,\n _id: result.upserted\n });\n }\n\n // If we have an update Batch type\n if (batch.batchType === UPDATE && result.n) {\n const nModified = result.nModified;\n bulkResult.nUpserted = bulkResult.nUpserted + nUpserted;\n bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted);\n\n if (typeof nModified === 'number') {\n bulkResult.nModified = bulkResult.nModified + nModified;\n } else {\n bulkResult.nModified = null;\n }\n }\n\n if (Array.isArray(result.writeErrors)) {\n for (let i = 0; i < result.writeErrors.length; i++) {\n const writeError = {\n index: batch.originalIndexes[result.writeErrors[i].index],\n code: result.writeErrors[i].code,\n errmsg: result.writeErrors[i].errmsg,\n op: batch.operations[result.writeErrors[i].index]\n };\n\n bulkResult.writeErrors.push(new WriteError(writeError));\n }\n }\n\n if (result.writeConcernError) {\n bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError));\n }\n}\n\nfunction executeCommands(bulkOperation, options, callback) {\n if (bulkOperation.s.batches.length === 0) {\n return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult));\n }\n\n const batch = bulkOperation.s.batches.shift();\n\n function resultHandler(err, result) {\n // Error is a driver related error not a bulk op error, terminate\n if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {\n return handleCallback(callback, err);\n }\n\n // If we have and error\n if (err) err.ok = 0;\n if (err instanceof MongoWriteConcernError) {\n return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback);\n }\n\n // Merge the results together\n const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult);\n const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result);\n if (mergeResult != null) {\n return handleCallback(callback, null, writeResult);\n }\n\n if (bulkOperation.handleWriteError(callback, writeResult)) return;\n\n // Execute the next command in line\n executeCommands(bulkOperation, options, callback);\n }\n\n bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);\n}\n\n/**\n * handles write concern error\n *\n * @ignore\n * @param {object} batch\n * @param {object} bulkResult\n * @param {boolean} ordered\n * @param {WriteConcernError} err\n * @param {function} callback\n */\nfunction handleMongoWriteConcernError(batch, bulkResult, err, callback) {\n mergeBatchResults(batch, bulkResult, null, err.result);\n\n const wrappedWriteConcernError = new WriteConcernError({\n errmsg: err.result.writeConcernError.errmsg,\n code: err.result.writeConcernError.result\n });\n return handleCallback(\n callback,\n new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)),\n null\n );\n}\n\n/**\n * @classdesc An error indicating an unsuccessful Bulk Write\n */\nclass BulkWriteError extends MongoError {\n /**\n * Creates a new BulkWriteError\n *\n * @param {Error|string|object} message The error message\n * @param {BulkWriteResult} result The result of the bulk write operation\n * @extends {MongoError}\n */\n constructor(error, result) {\n const message = error.err || error.errmsg || error.errMessage || error;\n super(message);\n\n Object.assign(this, error);\n\n this.name = 'BulkWriteError';\n this.result = result;\n }\n}\n\n/**\n * @classdesc A builder object that is returned from {@link BulkOperationBase#find}.\n * Is used to build a write operation that involves a query filter.\n */\nclass FindOperators {\n /**\n * Creates a new FindOperators object.\n *\n * **NOTE:** Internal Type, do not instantiate directly\n * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation\n */\n constructor(bulkOperation) {\n this.s = bulkOperation.s;\n }\n\n /**\n * Add a multiple update operation to the bulk operation\n *\n * @method\n * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation}\n * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.\n * @throws {MongoError} If operation cannot be added to bulk write\n * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation\n */\n update(updateDocument) {\n // Perform upsert\n const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;\n\n // Establish the update command\n const document = {\n q: this.s.currentOp.selector,\n u: updateDocument,\n multi: true,\n upsert: upsert\n };\n\n if (updateDocument.hint) {\n document.hint = updateDocument.hint;\n }\n\n // Clear out current Op\n this.s.currentOp = null;\n return this.s.options.addToOperationsList(this, UPDATE, document);\n }\n\n /**\n * Add a single update operation to the bulk operation\n *\n * @method\n * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation}\n * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.\n * @throws {MongoError} If operation cannot be added to bulk write\n * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation\n */\n updateOne(updateDocument) {\n // Perform upsert\n const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;\n\n // Establish the update command\n const document = {\n q: this.s.currentOp.selector,\n u: updateDocument,\n multi: false,\n upsert: upsert\n };\n\n if (updateDocument.hint) {\n document.hint = updateDocument.hint;\n }\n\n if (!hasAtomicOperators(updateDocument)) {\n throw new TypeError('Update document requires atomic operators');\n }\n\n // Clear out current Op\n this.s.currentOp = null;\n return this.s.options.addToOperationsList(this, UPDATE, document);\n }\n\n /**\n * Add a replace one operation to the bulk operation\n *\n * @method\n * @param {object} replacement the new document to replace the existing one with\n * @throws {MongoError} If operation cannot be added to bulk write\n * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation\n */\n replaceOne(replacement) {\n // Perform upsert\n const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;\n\n // Establish the update command\n const document = {\n q: this.s.currentOp.selector,\n u: replacement,\n multi: false,\n upsert: upsert\n };\n\n if (replacement.hint) {\n document.hint = replacement.hint;\n }\n\n if (hasAtomicOperators(replacement)) {\n throw new TypeError('Replacement document must not use atomic operators');\n }\n\n // Clear out current Op\n this.s.currentOp = null;\n return this.s.options.addToOperationsList(this, UPDATE, document);\n }\n\n /**\n * Upsert modifier for update bulk operation, noting that this operation is an upsert.\n *\n * @method\n * @throws {MongoError} If operation cannot be added to bulk write\n * @return {FindOperators} reference to self\n */\n upsert() {\n this.s.currentOp.upsert = true;\n return this;\n }\n\n /**\n * Add a delete one operation to the bulk operation\n *\n * @method\n * @throws {MongoError} If operation cannot be added to bulk write\n * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation\n */\n deleteOne() {\n // Establish the update command\n const document = {\n q: this.s.currentOp.selector,\n limit: 1\n };\n\n // Clear out current Op\n this.s.currentOp = null;\n return this.s.options.addToOperationsList(this, REMOVE, document);\n }\n\n /**\n * Add a delete many operation to the bulk operation\n *\n * @method\n * @throws {MongoError} If operation cannot be added to bulk write\n * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation\n */\n delete() {\n // Establish the update command\n const document = {\n q: this.s.currentOp.selector,\n limit: 0\n };\n\n // Clear out current Op\n this.s.currentOp = null;\n return this.s.options.addToOperationsList(this, REMOVE, document);\n }\n\n /**\n * backwards compatability for deleteOne\n */\n removeOne() {\n return this.deleteOne();\n }\n\n /**\n * backwards compatability for delete\n */\n remove() {\n return this.delete();\n }\n}\n\n/**\n * @classdesc Parent class to OrderedBulkOperation and UnorderedBulkOperation\n *\n * **NOTE:** Internal Type, do not instantiate directly\n */\nclass BulkOperationBase {\n /**\n * Create a new OrderedBulkOperation or UnorderedBulkOperation instance\n * @property {number} length Get the number of operations in the bulk.\n */\n constructor(topology, collection, options, isOrdered) {\n // determine whether bulkOperation is ordered or unordered\n this.isOrdered = isOrdered;\n\n options = options == null ? {} : options;\n // TODO Bring from driver information in isMaster\n // Get the namespace for the write operations\n const namespace = collection.s.namespace;\n // Used to mark operation as executed\n const executed = false;\n\n // Current item\n const currentOp = null;\n\n // Handle to the bson serializer, used to calculate running sizes\n const bson = topology.bson;\n // Set max byte size\n const isMaster = topology.lastIsMaster();\n\n // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents\n // over 2mb are still allowed\n const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter);\n const maxBsonObjectSize =\n isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16;\n const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize;\n const maxWriteBatchSize =\n isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000;\n\n // Calculates the largest possible size of an Array key, represented as a BSON string\n // element. This calculation:\n // 1 byte for BSON type\n // # of bytes = length of (string representation of (maxWriteBatchSize - 1))\n // + 1 bytes for null terminator\n const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2;\n\n // Final options for retryable writes and write concern\n let finalOptions = Object.assign({}, options);\n finalOptions = applyRetryableWrites(finalOptions, collection.s.db);\n finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options);\n const writeConcern = finalOptions.writeConcern;\n\n // Get the promiseLibrary\n const promiseLibrary = options.promiseLibrary || Promise;\n\n // Final results\n const bulkResult = {\n ok: 1,\n writeErrors: [],\n writeConcernErrors: [],\n insertedIds: [],\n nInserted: 0,\n nUpserted: 0,\n nMatched: 0,\n nModified: 0,\n nRemoved: 0,\n upserted: []\n };\n\n // Internal state\n this.s = {\n // Final result\n bulkResult: bulkResult,\n // Current batch state\n currentBatch: null,\n currentIndex: 0,\n // ordered specific\n currentBatchSize: 0,\n currentBatchSizeBytes: 0,\n // unordered specific\n currentInsertBatch: null,\n currentUpdateBatch: null,\n currentRemoveBatch: null,\n batches: [],\n // Write concern\n writeConcern: writeConcern,\n // Max batch size options\n maxBsonObjectSize,\n maxBatchSizeBytes,\n maxWriteBatchSize,\n maxKeySize,\n // Namespace\n namespace: namespace,\n // BSON\n bson: bson,\n // Topology\n topology: topology,\n // Options\n options: finalOptions,\n // Current operation\n currentOp: currentOp,\n // Executed\n executed: executed,\n // Collection\n collection: collection,\n // Promise Library\n promiseLibrary: promiseLibrary,\n // Fundamental error\n err: null,\n // check keys\n checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true\n };\n\n // bypass Validation\n if (options.bypassDocumentValidation === true) {\n this.s.bypassDocumentValidation = true;\n }\n }\n\n /**\n * Add a single insert document to the bulk operation\n *\n * @param {object} document the document to insert\n * @throws {MongoError}\n * @return {BulkOperationBase} A reference to self\n *\n * @example\n * const bulkOp = collection.initializeOrderedBulkOp();\n * // Adds three inserts to the bulkOp.\n * bulkOp\n * .insert({ a: 1 })\n * .insert({ b: 2 })\n * .insert({ c: 3 });\n * await bulkOp.execute();\n */\n insert(document) {\n if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null)\n document._id = new ObjectID();\n return this.s.options.addToOperationsList(this, INSERT, document);\n }\n\n /**\n * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.\n * Returns a builder object used to complete the definition of the operation.\n *\n * @method\n * @param {object} selector The selector for the bulk operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-q q documentation}\n * @throws {MongoError} if a selector is not specified\n * @return {FindOperators} A helper object with which the write operation can be defined.\n *\n * @example\n * const bulkOp = collection.initializeOrderedBulkOp();\n *\n * // Add an updateOne to the bulkOp\n * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });\n *\n * // Add an updateMany to the bulkOp\n * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });\n *\n * // Add an upsert\n * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });\n *\n * // Add a deletion\n * bulkOp.find({ g: 7 }).deleteOne();\n *\n * // Add a multi deletion\n * bulkOp.find({ h: 8 }).delete();\n *\n * // Add a replaceOne\n * bulkOp.find({ i: 9 }).replaceOne({ j: 10 });\n *\n * // Update using a pipeline (requires Mongodb 4.2 or higher)\n * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([\n * { $set: { total: { $sum: [ '$y', '$z' ] } } }\n * ]);\n *\n * // All of the ops will now be executed\n * await bulkOp.execute();\n */\n find(selector) {\n if (!selector) {\n throw toError('Bulk find operation must specify a selector');\n }\n\n // Save a current selector\n this.s.currentOp = {\n selector: selector\n };\n\n return new FindOperators(this);\n }\n\n /**\n * Specifies a raw operation to perform in the bulk write.\n *\n * @method\n * @param {object} op The raw operation to perform.\n * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.\n * @return {BulkOperationBase} A reference to self\n */\n raw(op) {\n const key = Object.keys(op)[0];\n\n // Set up the force server object id\n const forceServerObjectId =\n typeof this.s.options.forceServerObjectId === 'boolean'\n ? this.s.options.forceServerObjectId\n : this.s.collection.s.db.options.forceServerObjectId;\n\n // Update operations\n if (\n (op.updateOne && op.updateOne.q) ||\n (op.updateMany && op.updateMany.q) ||\n (op.replaceOne && op.replaceOne.q)\n ) {\n op[key].multi = op.updateOne || op.replaceOne ? false : true;\n return this.s.options.addToOperationsList(this, UPDATE, op[key]);\n }\n\n // Crud spec update format\n if (op.updateOne || op.updateMany || op.replaceOne) {\n if (op.replaceOne && hasAtomicOperators(op[key].replacement)) {\n throw new TypeError('Replacement document must not use atomic operators');\n } else if ((op.updateOne || op.updateMany) && !hasAtomicOperators(op[key].update)) {\n throw new TypeError('Update document requires atomic operators');\n }\n\n const multi = op.updateOne || op.replaceOne ? false : true;\n const operation = {\n q: op[key].filter,\n u: op[key].update || op[key].replacement,\n multi: multi\n };\n\n if (op[key].hint) {\n operation.hint = op[key].hint;\n }\n\n if (this.isOrdered) {\n operation.upsert = op[key].upsert ? true : false;\n if (op.collation) operation.collation = op.collation;\n } else {\n if (op[key].upsert) operation.upsert = true;\n }\n if (op[key].arrayFilters) {\n // TODO: this check should be done at command construction against a connection, not a topology\n if (maxWireVersion(this.s.topology) < 6) {\n throw new TypeError('arrayFilters are only supported on MongoDB 3.6+');\n }\n\n operation.arrayFilters = op[key].arrayFilters;\n }\n\n return this.s.options.addToOperationsList(this, UPDATE, operation);\n }\n\n // Remove operations\n if (\n op.removeOne ||\n op.removeMany ||\n (op.deleteOne && op.deleteOne.q) ||\n (op.deleteMany && op.deleteMany.q)\n ) {\n op[key].limit = op.removeOne ? 1 : 0;\n return this.s.options.addToOperationsList(this, REMOVE, op[key]);\n }\n\n // Crud spec delete operations, less efficient\n if (op.deleteOne || op.deleteMany) {\n const limit = op.deleteOne ? 1 : 0;\n const operation = { q: op[key].filter, limit: limit };\n if (op[key].hint) {\n operation.hint = op[key].hint;\n }\n if (this.isOrdered) {\n if (op.collation) operation.collation = op.collation;\n }\n return this.s.options.addToOperationsList(this, REMOVE, operation);\n }\n\n // Insert operations\n if (op.insertOne && op.insertOne.document == null) {\n if (forceServerObjectId !== true && op.insertOne._id == null)\n op.insertOne._id = new ObjectID();\n return this.s.options.addToOperationsList(this, INSERT, op.insertOne);\n } else if (op.insertOne && op.insertOne.document) {\n if (forceServerObjectId !== true && op.insertOne.document._id == null)\n op.insertOne.document._id = new ObjectID();\n return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document);\n }\n\n if (op.insertMany) {\n for (let i = 0; i < op.insertMany.length; i++) {\n if (forceServerObjectId !== true && op.insertMany[i]._id == null)\n op.insertMany[i]._id = new ObjectID();\n this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]);\n }\n\n return;\n }\n\n // No valid type of operation\n throw toError(\n 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany'\n );\n }\n\n /**\n * helper function to assist with promiseOrCallback behavior\n * @ignore\n * @param {*} err\n * @param {*} callback\n */\n _handleEarlyError(err, callback) {\n if (typeof callback === 'function') {\n callback(err, null);\n return;\n }\n\n return this.s.promiseLibrary.reject(err);\n }\n\n /**\n * An internal helper method. Do not invoke directly. Will be going away in the future\n *\n * @ignore\n * @method\n * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation\n * @param {object} writeConcern\n * @param {object} options\n * @param {function} callback\n */\n bulkExecute(_writeConcern, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n if (typeof _writeConcern === 'function') {\n callback = _writeConcern;\n } else if (_writeConcern && typeof _writeConcern === 'object') {\n this.s.writeConcern = _writeConcern;\n }\n\n if (this.s.executed) {\n const executedError = toError('batch cannot be re-executed');\n return this._handleEarlyError(executedError, callback);\n }\n\n // If we have current batch\n if (this.isOrdered) {\n if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch);\n } else {\n if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch);\n if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch);\n if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch);\n }\n // If we have no operations in the bulk raise an error\n if (this.s.batches.length === 0) {\n const emptyBatchError = toError('Invalid Operation, no operations specified');\n return this._handleEarlyError(emptyBatchError, callback);\n }\n return { options, callback };\n }\n\n /**\n * The callback format for results\n * @callback BulkOperationBase~resultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {BulkWriteResult} result The bulk write result.\n */\n\n /**\n * Execute the bulk operation\n *\n * @method\n * @param {WriteConcern} [_writeConcern] Optional write concern. Can also be specified through options.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.fsync=false] Specify a file sync write concern.\n * @param {BulkOperationBase~resultCallback} [callback] A callback that will be invoked when bulkWrite finishes/errors\n * @throws {MongoError} Throws error if the bulk object has already been executed\n * @throws {MongoError} Throws error if the bulk object does not have any operations\n * @return {Promise|void} returns Promise if no callback passed\n */\n execute(_writeConcern, options, callback) {\n const ret = this.bulkExecute(_writeConcern, options, callback);\n if (!ret || isPromiseLike(ret)) {\n return ret;\n }\n\n options = ret.options;\n callback = ret.callback;\n\n return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]);\n }\n\n /**\n * Handles final options before executing command\n *\n * An internal method. Do not invoke. Will not be accessible in the future\n *\n * @ignore\n * @param {object} config\n * @param {object} config.options\n * @param {number} config.batch\n * @param {function} config.resultHandler\n * @param {function} callback\n */\n finalOptionsHandler(config, callback) {\n const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options);\n if (this.s.writeConcern != null) {\n finalOptions.writeConcern = this.s.writeConcern;\n }\n\n if (finalOptions.bypassDocumentValidation !== true) {\n delete finalOptions.bypassDocumentValidation;\n }\n\n // Set an operationIf if provided\n if (this.operationId) {\n config.resultHandler.operationId = this.operationId;\n }\n\n // Serialize functions\n if (this.s.options.serializeFunctions) {\n finalOptions.serializeFunctions = true;\n }\n\n // Ignore undefined\n if (this.s.options.ignoreUndefined) {\n finalOptions.ignoreUndefined = true;\n }\n\n // Is the bypassDocumentValidation options specific\n if (this.s.bypassDocumentValidation === true) {\n finalOptions.bypassDocumentValidation = true;\n }\n\n // Is the checkKeys option disabled\n if (this.s.checkKeys === false) {\n finalOptions.checkKeys = false;\n }\n\n if (finalOptions.retryWrites) {\n if (config.batch.batchType === UPDATE) {\n finalOptions.retryWrites =\n finalOptions.retryWrites && !config.batch.operations.some(op => op.multi);\n }\n\n if (config.batch.batchType === REMOVE) {\n finalOptions.retryWrites =\n finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0);\n }\n }\n\n try {\n if (config.batch.batchType === INSERT) {\n this.s.topology.insert(\n this.s.namespace,\n config.batch.operations,\n finalOptions,\n config.resultHandler\n );\n } else if (config.batch.batchType === UPDATE) {\n this.s.topology.update(\n this.s.namespace,\n config.batch.operations,\n finalOptions,\n config.resultHandler\n );\n } else if (config.batch.batchType === REMOVE) {\n this.s.topology.remove(\n this.s.namespace,\n config.batch.operations,\n finalOptions,\n config.resultHandler\n );\n }\n } catch (err) {\n // Force top level error\n err.ok = 0;\n // Merge top level error and return\n handleCallback(callback, null, mergeBatchResults(config.batch, this.s.bulkResult, err, null));\n }\n }\n\n /**\n * Handles the write error before executing commands\n *\n * An internal helper method. Do not invoke directly. Will be going away in the future\n *\n * @ignore\n * @param {function} callback\n * @param {BulkWriteResult} writeResult\n * @param {class} self either OrderedBulkOperation or UnorderedBulkOperation\n */\n handleWriteError(callback, writeResult) {\n if (this.s.bulkResult.writeErrors.length > 0) {\n const msg = this.s.bulkResult.writeErrors[0].errmsg\n ? this.s.bulkResult.writeErrors[0].errmsg\n : 'write operation failed';\n\n handleCallback(\n callback,\n new BulkWriteError(\n toError({\n message: msg,\n code: this.s.bulkResult.writeErrors[0].code,\n writeErrors: this.s.bulkResult.writeErrors\n }),\n writeResult\n ),\n null\n );\n return true;\n }\n\n if (writeResult.getWriteConcernError()) {\n handleCallback(\n callback,\n new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult),\n null\n );\n return true;\n }\n }\n}\n\nObject.defineProperty(BulkOperationBase.prototype, 'length', {\n enumerable: true,\n get: function() {\n return this.s.currentIndex;\n }\n});\n\n// Exports symbols\nmodule.exports = {\n Batch,\n BulkOperationBase,\n bson,\n INSERT: INSERT,\n UPDATE: UPDATE,\n REMOVE: REMOVE,\n BulkWriteError\n};\n","'use strict';\n\nconst common = require('./common');\nconst BulkOperationBase = common.BulkOperationBase;\nconst Batch = common.Batch;\nconst bson = common.bson;\nconst utils = require('../utils');\nconst toError = utils.toError;\n\n/**\n * Add to internal list of Operations\n *\n * @ignore\n * @param {OrderedBulkOperation} bulkOperation\n * @param {number} docType number indicating the document type\n * @param {object} document\n * @return {OrderedBulkOperation}\n */\nfunction addToOperationsList(bulkOperation, docType, document) {\n // Get the bsonSize\n const bsonSize = bson.calculateObjectSize(document, {\n checkKeys: false,\n\n // Since we don't know what the user selected for BSON options here,\n // err on the safe side, and check the size with ignoreUndefined: false.\n ignoreUndefined: false\n });\n\n // Throw error if the doc is bigger than the max BSON size\n if (bsonSize >= bulkOperation.s.maxBsonObjectSize)\n throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBsonObjectSize);\n\n // Create a new batch object if we don't have a current one\n if (bulkOperation.s.currentBatch == null)\n bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);\n\n const maxKeySize = bulkOperation.s.maxKeySize;\n\n // Check if we need to create a new batch\n if (\n // New batch if we exceed the max batch op size\n bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize ||\n // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc,\n // since we can't sent an empty batch\n (bulkOperation.s.currentBatchSize > 0 &&\n bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >=\n bulkOperation.s.maxBatchSizeBytes) ||\n // New batch if the new op does not have the same op type as the current batch\n bulkOperation.s.currentBatch.batchType !== docType\n ) {\n // Save the batch to the execution stack\n bulkOperation.s.batches.push(bulkOperation.s.currentBatch);\n\n // Create a new batch\n bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);\n\n // Reset the current size trackers\n bulkOperation.s.currentBatchSize = 0;\n bulkOperation.s.currentBatchSizeBytes = 0;\n }\n\n if (docType === common.INSERT) {\n bulkOperation.s.bulkResult.insertedIds.push({\n index: bulkOperation.s.currentIndex,\n _id: document._id\n });\n }\n\n // We have an array of documents\n if (Array.isArray(document)) {\n throw toError('operation passed in cannot be an Array');\n }\n\n bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex);\n bulkOperation.s.currentBatch.operations.push(document);\n bulkOperation.s.currentBatchSize += 1;\n bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize;\n bulkOperation.s.currentIndex += 1;\n\n // Return bulkOperation\n return bulkOperation;\n}\n\n/**\n * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)\n * @class\n * @extends BulkOperationBase\n * @property {number} length Get the number of operations in the bulk.\n * @return {OrderedBulkOperation} a OrderedBulkOperation instance.\n */\nclass OrderedBulkOperation extends BulkOperationBase {\n constructor(topology, collection, options) {\n options = options || {};\n options = Object.assign(options, { addToOperationsList });\n\n super(topology, collection, options, true);\n }\n}\n\n/**\n * Returns an unordered batch object\n * @ignore\n */\nfunction initializeOrderedBulkOp(topology, collection, options) {\n return new OrderedBulkOperation(topology, collection, options);\n}\n\ninitializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation;\nmodule.exports = initializeOrderedBulkOp;\nmodule.exports.Bulk = OrderedBulkOperation;\n","'use strict';\n\nconst common = require('./common');\nconst BulkOperationBase = common.BulkOperationBase;\nconst Batch = common.Batch;\nconst bson = common.bson;\nconst utils = require('../utils');\nconst toError = utils.toError;\n\n/**\n * Add to internal list of Operations\n *\n * @ignore\n * @param {UnorderedBulkOperation} bulkOperation\n * @param {number} docType number indicating the document type\n * @param {object} document\n * @return {UnorderedBulkOperation}\n */\nfunction addToOperationsList(bulkOperation, docType, document) {\n // Get the bsonSize\n const bsonSize = bson.calculateObjectSize(document, {\n checkKeys: false,\n\n // Since we don't know what the user selected for BSON options here,\n // err on the safe side, and check the size with ignoreUndefined: false.\n ignoreUndefined: false\n });\n // Throw error if the doc is bigger than the max BSON size\n if (bsonSize >= bulkOperation.s.maxBsonObjectSize)\n throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBsonObjectSize);\n // Holds the current batch\n bulkOperation.s.currentBatch = null;\n // Get the right type of batch\n if (docType === common.INSERT) {\n bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch;\n } else if (docType === common.UPDATE) {\n bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch;\n } else if (docType === common.REMOVE) {\n bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch;\n }\n\n const maxKeySize = bulkOperation.s.maxKeySize;\n\n // Create a new batch object if we don't have a current one\n if (bulkOperation.s.currentBatch == null)\n bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);\n\n // Check if we need to create a new batch\n if (\n // New batch if we exceed the max batch op size\n bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize ||\n // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc,\n // since we can't sent an empty batch\n (bulkOperation.s.currentBatch.size > 0 &&\n bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >=\n bulkOperation.s.maxBatchSizeBytes) ||\n // New batch if the new op does not have the same op type as the current batch\n bulkOperation.s.currentBatch.batchType !== docType\n ) {\n // Save the batch to the execution stack\n bulkOperation.s.batches.push(bulkOperation.s.currentBatch);\n\n // Create a new batch\n bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);\n }\n\n // We have an array of documents\n if (Array.isArray(document)) {\n throw toError('operation passed in cannot be an Array');\n }\n\n bulkOperation.s.currentBatch.operations.push(document);\n bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex);\n bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1;\n\n // Save back the current Batch to the right type\n if (docType === common.INSERT) {\n bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch;\n bulkOperation.s.bulkResult.insertedIds.push({\n index: bulkOperation.s.bulkResult.insertedIds.length,\n _id: document._id\n });\n } else if (docType === common.UPDATE) {\n bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch;\n } else if (docType === common.REMOVE) {\n bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch;\n }\n\n // Update current batch size\n bulkOperation.s.currentBatch.size += 1;\n bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize;\n\n // Return bulkOperation\n return bulkOperation;\n}\n\n/**\n * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)\n * @class\n * @extends BulkOperationBase\n * @property {number} length Get the number of operations in the bulk.\n * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance.\n */\nclass UnorderedBulkOperation extends BulkOperationBase {\n constructor(topology, collection, options) {\n options = options || {};\n options = Object.assign(options, { addToOperationsList });\n\n super(topology, collection, options, false);\n }\n\n handleWriteError(callback, writeResult) {\n if (this.s.batches.length) {\n return false;\n }\n\n return super.handleWriteError(callback, writeResult);\n }\n}\n\n/**\n * Returns an unordered batch object\n * @ignore\n */\nfunction initializeUnorderedBulkOp(topology, collection, options) {\n return new UnorderedBulkOperation(topology, collection, options);\n}\n\ninitializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation;\nmodule.exports = initializeUnorderedBulkOp;\nmodule.exports.Bulk = UnorderedBulkOperation;\n","'use strict';\n\nconst Denque = require('denque');\nconst EventEmitter = require('events');\nconst isResumableError = require('./error').isResumableError;\nconst MongoError = require('./core').MongoError;\nconst Cursor = require('./cursor');\nconst relayEvents = require('./core/utils').relayEvents;\nconst maxWireVersion = require('./core/utils').maxWireVersion;\nconst maybePromise = require('./utils').maybePromise;\nconst now = require('./utils').now;\nconst calculateDurationInMs = require('./utils').calculateDurationInMs;\nconst AggregateOperation = require('./operations/aggregate');\n\nconst kResumeQueue = Symbol('resumeQueue');\n\nconst CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument'];\nconst CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat(\n CHANGE_STREAM_OPTIONS\n);\n\nconst CHANGE_DOMAIN_TYPES = {\n COLLECTION: Symbol('Collection'),\n DATABASE: Symbol('Database'),\n CLUSTER: Symbol('Cluster')\n};\n\n/**\n * @typedef ResumeToken\n * @description Represents the logical starting point for a new or resuming {@link ChangeStream} on the server.\n * @see https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token\n */\n\n/**\n * @typedef OperationTime\n * @description Represents a specific point in time on a server. Can be retrieved by using {@link Db#command}\n * @see https://docs.mongodb.com/manual/reference/method/db.runCommand/#response\n */\n\n/**\n * @typedef ChangeStreamOptions\n * @description Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified.\n * @property {string} [fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.\n * @property {number} [maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query.\n * @property {ResumeToken} [resumeAfter] Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}.\n * @property {ResumeToken} [startAfter] Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}.\n * @property {OperationTime} [startAtOperationTime] Will start the changeStream after the specified operationTime.\n * @property {number} [batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @property {object} [collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @property {ReadPreference} [readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.\n */\n\n/**\n * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}.\n * @class ChangeStream\n * @since 3.0.0\n * @param {(MongoClient|Db|Collection)} parent The parent object that created this change stream\n * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents\n * @param {ChangeStreamOptions} [options] Optional settings\n * @fires ChangeStream#close\n * @fires ChangeStream#change\n * @fires ChangeStream#end\n * @fires ChangeStream#error\n * @fires ChangeStream#resumeTokenChanged\n * @return {ChangeStream} a ChangeStream instance.\n */\nclass ChangeStream extends EventEmitter {\n constructor(parent, pipeline, options) {\n super();\n const Collection = require('./collection');\n const Db = require('./db');\n const MongoClient = require('./mongo_client');\n\n this.pipeline = pipeline || [];\n this.options = options || {};\n\n this.parent = parent;\n this.namespace = parent.s.namespace;\n if (parent instanceof Collection) {\n this.type = CHANGE_DOMAIN_TYPES.COLLECTION;\n this.topology = parent.s.db.serverConfig;\n } else if (parent instanceof Db) {\n this.type = CHANGE_DOMAIN_TYPES.DATABASE;\n this.topology = parent.serverConfig;\n } else if (parent instanceof MongoClient) {\n this.type = CHANGE_DOMAIN_TYPES.CLUSTER;\n this.topology = parent.topology;\n } else {\n throw new TypeError(\n 'parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient'\n );\n }\n\n this.promiseLibrary = parent.s.promiseLibrary;\n if (!this.options.readPreference && parent.s.readPreference) {\n this.options.readPreference = parent.s.readPreference;\n }\n\n this[kResumeQueue] = new Denque();\n\n // Create contained Change Stream cursor\n this.cursor = createChangeStreamCursor(this, options);\n\n this.closed = false;\n\n // Listen for any `change` listeners being added to ChangeStream\n this.on('newListener', eventName => {\n if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) {\n this.cursor.on('data', change => processNewChange(this, change));\n }\n });\n\n // Listen for all `change` listeners being removed from ChangeStream\n this.on('removeListener', eventName => {\n if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) {\n this.cursor.removeAllListeners('data');\n }\n });\n }\n\n /**\n * @property {ResumeToken} resumeToken\n * The cached resume token that will be used to resume\n * after the most recently returned change.\n */\n get resumeToken() {\n return this.cursor.resumeToken;\n }\n\n /**\n * Check if there is any document still available in the Change Stream\n * @function ChangeStream.prototype.hasNext\n * @param {ChangeStream~resultCallback} [callback] The result callback.\n * @throws {MongoError}\n * @returns {Promise|void} returns Promise if no callback passed\n */\n hasNext(callback) {\n return maybePromise(this.parent, callback, cb => {\n getCursor(this, (err, cursor) => {\n if (err) return cb(err); // failed to resume, raise an error\n cursor.hasNext(cb);\n });\n });\n }\n\n /**\n * Get the next available document from the Change Stream, returns null if no more documents are available.\n * @function ChangeStream.prototype.next\n * @param {ChangeStream~resultCallback} [callback] The result callback.\n * @throws {MongoError}\n * @returns {Promise|void} returns Promise if no callback passed\n */\n next(callback) {\n return maybePromise(this.parent, callback, cb => {\n getCursor(this, (err, cursor) => {\n if (err) return cb(err); // failed to resume, raise an error\n cursor.next((error, change) => {\n if (error) {\n this[kResumeQueue].push(() => this.next(cb));\n processError(this, error, cb);\n return;\n }\n processNewChange(this, change, cb);\n });\n });\n });\n }\n\n /**\n * Is the change stream closed\n * @method ChangeStream.prototype.isClosed\n * @return {boolean}\n */\n isClosed() {\n return this.closed || (this.cursor && this.cursor.isClosed());\n }\n\n /**\n * Close the Change Stream\n * @method ChangeStream.prototype.close\n * @param {ChangeStream~resultCallback} [callback] The result callback.\n * @return {Promise} returns Promise if no callback passed\n */\n close(callback) {\n return maybePromise(this.parent, callback, cb => {\n if (this.closed) return cb();\n\n // flag the change stream as explicitly closed\n this.closed = true;\n\n if (!this.cursor) return cb();\n\n // Tidy up the existing cursor\n const cursor = this.cursor;\n\n return cursor.close(err => {\n ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event));\n this.cursor = undefined;\n\n return cb(err);\n });\n });\n }\n\n /**\n * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.\n * @method\n * @param {Writable} destination The destination for writing data\n * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options}\n * @return {null}\n */\n pipe(destination, options) {\n if (!this.pipeDestinations) {\n this.pipeDestinations = [];\n }\n this.pipeDestinations.push(destination);\n return this.cursor.pipe(destination, options);\n }\n\n /**\n * This method will remove the hooks set up for a previous pipe() call.\n * @param {Writable} [destination] The destination for writing data\n * @return {null}\n */\n unpipe(destination) {\n if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) {\n this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1);\n }\n return this.cursor.unpipe(destination);\n }\n\n /**\n * Return a modified Readable stream including a possible transform method.\n * @method\n * @param {object} [options] Optional settings.\n * @param {function} [options.transform] A transformation method applied to each document emitted by the stream.\n * @return {Cursor}\n */\n stream(options) {\n this.streamOptions = options;\n return this.cursor.stream(options);\n }\n\n /**\n * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.\n * @return {null}\n */\n pause() {\n return this.cursor.pause();\n }\n\n /**\n * This method will cause the readable stream to resume emitting data events.\n * @return {null}\n */\n resume() {\n return this.cursor.resume();\n }\n}\n\nclass ChangeStreamCursor extends Cursor {\n constructor(topology, operation, options) {\n super(topology, operation, options);\n\n options = options || {};\n this._resumeToken = null;\n this.startAtOperationTime = options.startAtOperationTime;\n\n if (options.startAfter) {\n this.resumeToken = options.startAfter;\n } else if (options.resumeAfter) {\n this.resumeToken = options.resumeAfter;\n }\n }\n\n set resumeToken(token) {\n this._resumeToken = token;\n this.emit('resumeTokenChanged', token);\n }\n\n get resumeToken() {\n return this._resumeToken;\n }\n\n get resumeOptions() {\n const result = {};\n for (const optionName of CURSOR_OPTIONS) {\n if (this.options[optionName]) result[optionName] = this.options[optionName];\n }\n\n if (this.resumeToken || this.startAtOperationTime) {\n ['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => delete result[key]);\n\n if (this.resumeToken) {\n const resumeKey =\n this.options.startAfter && !this.hasReceived ? 'startAfter' : 'resumeAfter';\n result[resumeKey] = this.resumeToken;\n } else if (this.startAtOperationTime && maxWireVersion(this.server) >= 7) {\n result.startAtOperationTime = this.startAtOperationTime;\n }\n }\n\n return result;\n }\n\n cacheResumeToken(resumeToken) {\n if (this.bufferedCount() === 0 && this.cursorState.postBatchResumeToken) {\n this.resumeToken = this.cursorState.postBatchResumeToken;\n } else {\n this.resumeToken = resumeToken;\n }\n this.hasReceived = true;\n }\n\n _processBatch(batchName, response) {\n const cursor = response.cursor;\n if (cursor.postBatchResumeToken) {\n this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken;\n\n if (cursor[batchName].length === 0) {\n this.resumeToken = cursor.postBatchResumeToken;\n }\n }\n }\n\n _initializeCursor(callback) {\n super._initializeCursor((err, result) => {\n if (err || result == null) {\n callback(err, result);\n return;\n }\n\n const response = result.documents[0];\n\n if (\n this.startAtOperationTime == null &&\n this.resumeAfter == null &&\n this.startAfter == null &&\n maxWireVersion(this.server) >= 7\n ) {\n this.startAtOperationTime = response.operationTime;\n }\n\n this._processBatch('firstBatch', response);\n\n this.emit('init', result);\n this.emit('response');\n callback(err, result);\n });\n }\n\n _getMore(callback) {\n super._getMore((err, response) => {\n if (err) {\n callback(err);\n return;\n }\n\n this._processBatch('nextBatch', response);\n\n this.emit('more', response);\n this.emit('response');\n callback(err, response);\n });\n }\n}\n\n/**\n * @event ChangeStreamCursor#response\n * internal event DO NOT USE\n * @ignore\n */\n\n// Create a new change stream cursor based on self's configuration\nfunction createChangeStreamCursor(self, options) {\n const changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' };\n applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS);\n if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) {\n changeStreamStageOptions.allChangesForCluster = true;\n }\n\n const pipeline = [{ $changeStream: changeStreamStageOptions }].concat(self.pipeline);\n const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS);\n\n const changeStreamCursor = new ChangeStreamCursor(\n self.topology,\n new AggregateOperation(self.parent, pipeline, options),\n cursorOptions\n );\n\n relayEvents(changeStreamCursor, self, ['resumeTokenChanged', 'end', 'close']);\n\n /**\n * Fired for each new matching change in the specified namespace. Attaching a `change`\n * event listener to a Change Stream will switch the stream into flowing mode. Data will\n * then be passed as soon as it is available.\n *\n * @event ChangeStream#change\n * @type {object}\n */\n if (self.listenerCount('change') > 0) {\n changeStreamCursor.on('data', function(change) {\n processNewChange(self, change);\n });\n }\n\n /**\n * Change stream close event\n *\n * @event ChangeStream#close\n * @type {null}\n */\n\n /**\n * Change stream end event\n *\n * @event ChangeStream#end\n * @type {null}\n */\n\n /**\n * Emitted each time the change stream stores a new resume token.\n *\n * @event ChangeStream#resumeTokenChanged\n * @type {ResumeToken}\n */\n\n /**\n * Fired when the stream encounters an error.\n *\n * @event ChangeStream#error\n * @type {Error}\n */\n changeStreamCursor.on('error', function(error) {\n processError(self, error);\n });\n\n if (self.pipeDestinations) {\n const cursorStream = changeStreamCursor.stream(self.streamOptions);\n for (let pipeDestination in self.pipeDestinations) {\n cursorStream.pipe(pipeDestination);\n }\n }\n\n return changeStreamCursor;\n}\n\nfunction applyKnownOptions(target, source, optionNames) {\n optionNames.forEach(name => {\n if (source[name]) {\n target[name] = source[name];\n }\n });\n\n return target;\n}\n\n// This method performs a basic server selection loop, satisfying the requirements of\n// ChangeStream resumability until the new SDAM layer can be used.\nconst SELECTION_TIMEOUT = 30000;\nfunction waitForTopologyConnected(topology, options, callback) {\n setTimeout(() => {\n if (options && options.start == null) {\n options.start = now();\n }\n\n const start = options.start || now();\n const timeout = options.timeout || SELECTION_TIMEOUT;\n const readPreference = options.readPreference;\n if (topology.isConnected({ readPreference })) {\n return callback();\n }\n\n if (calculateDurationInMs(start) > timeout) {\n return callback(new MongoError('Timed out waiting for connection'));\n }\n\n waitForTopologyConnected(topology, options, callback);\n }, 500); // this is an arbitrary wait time to allow SDAM to transition\n}\n\nfunction processNewChange(changeStream, change, callback) {\n const cursor = changeStream.cursor;\n\n // a null change means the cursor has been notified, implicitly closing the change stream\n if (change == null) {\n changeStream.closed = true;\n }\n\n if (changeStream.closed) {\n if (callback) callback(new MongoError('ChangeStream is closed'));\n return;\n }\n\n if (change && !change._id) {\n const noResumeTokenError = new Error(\n 'A change stream document has been received that lacks a resume token (_id).'\n );\n\n if (!callback) return changeStream.emit('error', noResumeTokenError);\n return callback(noResumeTokenError);\n }\n\n // cache the resume token\n cursor.cacheResumeToken(change._id);\n\n // wipe the startAtOperationTime if there was one so that there won't be a conflict\n // between resumeToken and startAtOperationTime if we need to reconnect the cursor\n changeStream.options.startAtOperationTime = undefined;\n\n // Return the change\n if (!callback) return changeStream.emit('change', change);\n return callback(undefined, change);\n}\n\nfunction processError(changeStream, error, callback) {\n const topology = changeStream.topology;\n const cursor = changeStream.cursor;\n\n // If the change stream has been closed explictly, do not process error.\n if (changeStream.closed) {\n if (callback) callback(new MongoError('ChangeStream is closed'));\n return;\n }\n\n // if the resume succeeds, continue with the new cursor\n function resumeWithCursor(newCursor) {\n changeStream.cursor = newCursor;\n processResumeQueue(changeStream);\n }\n\n // otherwise, raise an error and close the change stream\n function unresumableError(err) {\n if (!callback) {\n changeStream.emit('error', err);\n changeStream.emit('close');\n }\n processResumeQueue(changeStream, err);\n changeStream.closed = true;\n }\n\n if (cursor && isResumableError(error, maxWireVersion(cursor.server))) {\n changeStream.cursor = undefined;\n\n // stop listening to all events from old cursor\n ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event));\n\n // close internal cursor, ignore errors\n cursor.close();\n\n waitForTopologyConnected(topology, { readPreference: cursor.options.readPreference }, err => {\n // if the topology can't reconnect, close the stream\n if (err) return unresumableError(err);\n\n // create a new cursor, preserving the old cursor's options\n const newCursor = createChangeStreamCursor(changeStream, cursor.resumeOptions);\n\n // attempt to continue in emitter mode\n if (!callback) return resumeWithCursor(newCursor);\n\n // attempt to continue in iterator mode\n newCursor.hasNext(err => {\n // if there's an error immediately after resuming, close the stream\n if (err) return unresumableError(err);\n resumeWithCursor(newCursor);\n });\n });\n return;\n }\n\n if (!callback) return changeStream.emit('error', error);\n return callback(error);\n}\n\n/**\n * Safely provides a cursor across resume attempts\n *\n * @param {ChangeStream} changeStream the parent ChangeStream\n * @param {function} callback gets the cursor or error\n * @param {ChangeStreamCursor} [oldCursor] when resuming from an error, carry over options from previous cursor\n */\nfunction getCursor(changeStream, callback) {\n if (changeStream.isClosed()) {\n callback(new MongoError('ChangeStream is closed.'));\n return;\n }\n\n // if a cursor exists and it is open, return it\n if (changeStream.cursor) {\n callback(undefined, changeStream.cursor);\n return;\n }\n\n // no cursor, queue callback until topology reconnects\n changeStream[kResumeQueue].push(callback);\n}\n\n/**\n * Drain the resume queue when a new has become available\n *\n * @param {ChangeStream} changeStream the parent ChangeStream\n * @param {ChangeStreamCursor?} changeStream.cursor the new cursor\n * @param {Error} [err] error getting a new cursor\n */\nfunction processResumeQueue(changeStream, err) {\n while (changeStream[kResumeQueue].length) {\n const request = changeStream[kResumeQueue].pop();\n if (changeStream.isClosed() && !err) {\n request(new MongoError('Change Stream is not open.'));\n return;\n }\n request(err, changeStream.cursor);\n }\n}\n\n/**\n * The callback format for results\n * @callback ChangeStream~resultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {(object|null)} result The result object if the command was executed successfully.\n */\n\nmodule.exports = ChangeStream;\n","'use strict';\n\nconst EventEmitter = require('events');\nconst MessageStream = require('./message_stream');\nconst MongoError = require('../core/error').MongoError;\nconst MongoNetworkError = require('../core/error').MongoNetworkError;\nconst MongoNetworkTimeoutError = require('../core/error').MongoNetworkTimeoutError;\nconst MongoWriteConcernError = require('../core/error').MongoWriteConcernError;\nconst CommandResult = require('../core/connection/command_result');\nconst StreamDescription = require('./stream_description').StreamDescription;\nconst wp = require('../core/wireprotocol');\nconst apm = require('../core/connection/apm');\nconst updateSessionFromResponse = require('../core/sessions').updateSessionFromResponse;\nconst uuidV4 = require('../core/utils').uuidV4;\nconst now = require('../utils').now;\nconst calculateDurationInMs = require('../utils').calculateDurationInMs;\n\nconst kStream = Symbol('stream');\nconst kQueue = Symbol('queue');\nconst kMessageStream = Symbol('messageStream');\nconst kGeneration = Symbol('generation');\nconst kLastUseTime = Symbol('lastUseTime');\nconst kClusterTime = Symbol('clusterTime');\nconst kDescription = Symbol('description');\nconst kIsMaster = Symbol('ismaster');\nconst kAutoEncrypter = Symbol('autoEncrypter');\n\nclass Connection extends EventEmitter {\n constructor(stream, options) {\n super(options);\n\n this.id = options.id;\n this.address = streamIdentifier(stream);\n this.bson = options.bson;\n this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000;\n this.host = options.host || 'localhost';\n this.port = options.port || 27017;\n this.monitorCommands =\n typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false;\n this.closed = false;\n this.destroyed = false;\n\n this[kDescription] = new StreamDescription(this.address, options);\n this[kGeneration] = options.generation;\n this[kLastUseTime] = now();\n\n // retain a reference to an `AutoEncrypter` if present\n if (options.autoEncrypter) {\n this[kAutoEncrypter] = options.autoEncrypter;\n }\n\n // setup parser stream and message handling\n this[kQueue] = new Map();\n this[kMessageStream] = new MessageStream(options);\n this[kMessageStream].on('message', messageHandler(this));\n this[kStream] = stream;\n stream.on('error', () => {\n /* ignore errors, listen to `close` instead */\n });\n\n stream.on('close', () => {\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n this[kQueue].forEach(op =>\n op.cb(new MongoNetworkError(`connection ${this.id} to ${this.address} closed`))\n );\n this[kQueue].clear();\n\n this.emit('close');\n });\n\n stream.on('timeout', () => {\n if (this.closed) {\n return;\n }\n\n stream.destroy();\n this.closed = true;\n this[kQueue].forEach(op =>\n op.cb(\n new MongoNetworkTimeoutError(`connection ${this.id} to ${this.address} timed out`, {\n beforeHandshake: this[kIsMaster] == null\n })\n )\n );\n\n this[kQueue].clear();\n this.emit('close');\n });\n\n // hook the message stream up to the passed in stream\n stream.pipe(this[kMessageStream]);\n this[kMessageStream].pipe(stream);\n }\n\n get description() {\n return this[kDescription];\n }\n\n get ismaster() {\n return this[kIsMaster];\n }\n\n // the `connect` method stores the result of the handshake ismaster on the connection\n set ismaster(response) {\n this[kDescription].receiveResponse(response);\n\n // TODO: remove this, and only use the `StreamDescription` in the future\n this[kIsMaster] = response;\n }\n\n get generation() {\n return this[kGeneration] || 0;\n }\n\n get idleTime() {\n return calculateDurationInMs(this[kLastUseTime]);\n }\n\n get clusterTime() {\n return this[kClusterTime];\n }\n\n get stream() {\n return this[kStream];\n }\n\n markAvailable() {\n this[kLastUseTime] = now();\n }\n\n destroy(options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n options = Object.assign({ force: false }, options);\n if (this[kStream] == null || this.destroyed) {\n this.destroyed = true;\n if (typeof callback === 'function') {\n callback();\n }\n\n return;\n }\n\n if (options.force) {\n this[kStream].destroy();\n this.destroyed = true;\n if (typeof callback === 'function') {\n callback();\n }\n\n return;\n }\n\n this[kStream].end(err => {\n this.destroyed = true;\n if (typeof callback === 'function') {\n callback(err);\n }\n });\n }\n\n // Wire protocol methods\n command(ns, cmd, options, callback) {\n wp.command(makeServerTrampoline(this), ns, cmd, options, callback);\n }\n\n query(ns, cmd, cursorState, options, callback) {\n wp.query(makeServerTrampoline(this), ns, cmd, cursorState, options, callback);\n }\n\n getMore(ns, cursorState, batchSize, options, callback) {\n wp.getMore(makeServerTrampoline(this), ns, cursorState, batchSize, options, callback);\n }\n\n killCursors(ns, cursorState, callback) {\n wp.killCursors(makeServerTrampoline(this), ns, cursorState, callback);\n }\n\n insert(ns, ops, options, callback) {\n wp.insert(makeServerTrampoline(this), ns, ops, options, callback);\n }\n\n update(ns, ops, options, callback) {\n wp.update(makeServerTrampoline(this), ns, ops, options, callback);\n }\n\n remove(ns, ops, options, callback) {\n wp.remove(makeServerTrampoline(this), ns, ops, options, callback);\n }\n}\n\n/// This lets us emulate a legacy `Server` instance so we can work with the existing wire\n/// protocol methods. Eventually, the operation executor will return a `Connection` to execute\n/// against.\nfunction makeServerTrampoline(connection) {\n const server = {\n description: connection.description,\n clusterTime: connection[kClusterTime],\n s: {\n bson: connection.bson,\n pool: { write: write.bind(connection), isConnected: () => true }\n }\n };\n\n if (connection[kAutoEncrypter]) {\n server.autoEncrypter = connection[kAutoEncrypter];\n }\n\n return server;\n}\n\nfunction messageHandler(conn) {\n return function messageHandler(message) {\n // always emit the message, in case we are streaming\n conn.emit('message', message);\n if (!conn[kQueue].has(message.responseTo)) {\n return;\n }\n\n const operationDescription = conn[kQueue].get(message.responseTo);\n const callback = operationDescription.cb;\n\n // SERVER-45775: For exhaust responses we should be able to use the same requestId to\n // track response, however the server currently synthetically produces remote requests\n // making the `responseTo` change on each response\n conn[kQueue].delete(message.responseTo);\n if (message.moreToCome) {\n // requeue the callback for next synthetic request\n conn[kQueue].set(message.requestId, operationDescription);\n } else if (operationDescription.socketTimeoutOverride) {\n conn[kStream].setTimeout(conn.socketTimeout);\n }\n\n try {\n // Pass in the entire description because it has BSON parsing options\n message.parse(operationDescription);\n } catch (err) {\n callback(new MongoError(err));\n return;\n }\n\n if (message.documents[0]) {\n const document = message.documents[0];\n const session = operationDescription.session;\n if (session) {\n updateSessionFromResponse(session, document);\n }\n\n if (document.$clusterTime) {\n conn[kClusterTime] = document.$clusterTime;\n conn.emit('clusterTimeReceived', document.$clusterTime);\n }\n\n if (operationDescription.command) {\n if (document.writeConcernError) {\n callback(new MongoWriteConcernError(document.writeConcernError, document));\n return;\n }\n\n if (document.ok === 0 || document.$err || document.errmsg || document.code) {\n callback(new MongoError(document));\n return;\n }\n }\n }\n\n // NODE-2382: reenable in our glorious non-leaky abstraction future\n // callback(null, operationDescription.fullResult ? message : message.documents[0]);\n\n callback(\n undefined,\n new CommandResult(\n operationDescription.fullResult ? message : message.documents[0],\n conn,\n message\n )\n );\n };\n}\n\nfunction streamIdentifier(stream) {\n if (typeof stream.address === 'function') {\n return `${stream.remoteAddress}:${stream.remotePort}`;\n }\n\n return uuidV4().toString('hex');\n}\n\n// Not meant to be called directly, the wire protocol methods call this assuming it is a `Pool` instance\nfunction write(command, options, callback) {\n if (typeof options === 'function') {\n callback = options;\n }\n\n options = options || {};\n const operationDescription = {\n requestId: command.requestId,\n cb: callback,\n session: options.session,\n fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false,\n noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false,\n documentsReturnedIn: options.documentsReturnedIn,\n command: !!options.command,\n\n // for BSON parsing\n promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true,\n promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true,\n promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false,\n raw: typeof options.raw === 'boolean' ? options.raw : false\n };\n\n if (this[kDescription] && this[kDescription].compressor) {\n operationDescription.agreedCompressor = this[kDescription].compressor;\n\n if (this[kDescription].zlibCompressionLevel) {\n operationDescription.zlibCompressionLevel = this[kDescription].zlibCompressionLevel;\n }\n }\n\n if (typeof options.socketTimeout === 'number') {\n operationDescription.socketTimeoutOverride = true;\n this[kStream].setTimeout(options.socketTimeout);\n }\n\n // if command monitoring is enabled we need to modify the callback here\n if (this.monitorCommands) {\n this.emit('commandStarted', new apm.CommandStartedEvent(this, command));\n\n operationDescription.started = now();\n operationDescription.cb = (err, reply) => {\n if (err) {\n this.emit(\n 'commandFailed',\n new apm.CommandFailedEvent(this, command, err, operationDescription.started)\n );\n } else {\n if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) {\n this.emit(\n 'commandFailed',\n new apm.CommandFailedEvent(this, command, reply.result, operationDescription.started)\n );\n } else {\n this.emit(\n 'commandSucceeded',\n new apm.CommandSucceededEvent(this, command, reply, operationDescription.started)\n );\n }\n }\n\n if (typeof callback === 'function') {\n callback(err, reply);\n }\n };\n }\n\n if (!operationDescription.noResponse) {\n this[kQueue].set(operationDescription.requestId, operationDescription);\n }\n\n try {\n this[kMessageStream].writeCommand(command, operationDescription);\n } catch (e) {\n if (!operationDescription.noResponse) {\n this[kQueue].delete(operationDescription.requestId);\n operationDescription.cb(e);\n return;\n }\n }\n\n if (operationDescription.noResponse) {\n operationDescription.cb();\n }\n}\n\nmodule.exports = {\n Connection\n};\n","'use strict';\n\nconst Denque = require('denque');\nconst EventEmitter = require('events').EventEmitter;\nconst Logger = require('../core/connection/logger');\nconst makeCounter = require('../utils').makeCounter;\nconst MongoError = require('../core/error').MongoError;\nconst Connection = require('./connection').Connection;\nconst eachAsync = require('../core/utils').eachAsync;\nconst connect = require('../core/connection/connect');\nconst relayEvents = require('../core/utils').relayEvents;\n\nconst errors = require('./errors');\nconst PoolClosedError = errors.PoolClosedError;\nconst WaitQueueTimeoutError = errors.WaitQueueTimeoutError;\n\nconst events = require('./events');\nconst ConnectionPoolCreatedEvent = events.ConnectionPoolCreatedEvent;\nconst ConnectionPoolClosedEvent = events.ConnectionPoolClosedEvent;\nconst ConnectionCreatedEvent = events.ConnectionCreatedEvent;\nconst ConnectionReadyEvent = events.ConnectionReadyEvent;\nconst ConnectionClosedEvent = events.ConnectionClosedEvent;\nconst ConnectionCheckOutStartedEvent = events.ConnectionCheckOutStartedEvent;\nconst ConnectionCheckOutFailedEvent = events.ConnectionCheckOutFailedEvent;\nconst ConnectionCheckedOutEvent = events.ConnectionCheckedOutEvent;\nconst ConnectionCheckedInEvent = events.ConnectionCheckedInEvent;\nconst ConnectionPoolClearedEvent = events.ConnectionPoolClearedEvent;\n\nconst kLogger = Symbol('logger');\nconst kConnections = Symbol('connections');\nconst kPermits = Symbol('permits');\nconst kMinPoolSizeTimer = Symbol('minPoolSizeTimer');\nconst kGeneration = Symbol('generation');\nconst kConnectionCounter = Symbol('connectionCounter');\nconst kCancellationToken = Symbol('cancellationToken');\nconst kWaitQueue = Symbol('waitQueue');\nconst kCancelled = Symbol('cancelled');\n\nconst VALID_POOL_OPTIONS = new Set([\n // `connect` options\n 'ssl',\n 'bson',\n 'connectionType',\n 'monitorCommands',\n 'socketTimeout',\n 'credentials',\n 'compression',\n\n // node Net options\n 'host',\n 'port',\n 'localAddress',\n 'localPort',\n 'family',\n 'hints',\n 'lookup',\n 'path',\n\n // node TLS options\n 'ca',\n 'cert',\n 'sigalgs',\n 'ciphers',\n 'clientCertEngine',\n 'crl',\n 'dhparam',\n 'ecdhCurve',\n 'honorCipherOrder',\n 'key',\n 'privateKeyEngine',\n 'privateKeyIdentifier',\n 'maxVersion',\n 'minVersion',\n 'passphrase',\n 'pfx',\n 'secureOptions',\n 'secureProtocol',\n 'sessionIdContext',\n 'allowHalfOpen',\n 'rejectUnauthorized',\n 'pskCallback',\n 'ALPNProtocols',\n 'servername',\n 'checkServerIdentity',\n 'session',\n 'minDHSize',\n 'secureContext',\n\n // spec options\n 'maxPoolSize',\n 'minPoolSize',\n 'maxIdleTimeMS',\n 'waitQueueTimeoutMS'\n]);\n\nfunction resolveOptions(options, defaults) {\n const newOptions = Array.from(VALID_POOL_OPTIONS).reduce((obj, key) => {\n if (options.hasOwnProperty(key)) {\n obj[key] = options[key];\n }\n\n return obj;\n }, {});\n\n return Object.freeze(Object.assign({}, defaults, newOptions));\n}\n\n/**\n * Configuration options for drivers wrapping the node driver.\n *\n * @typedef {Object} ConnectionPoolOptions\n * @property\n * @property {string} [host] The host to connect to\n * @property {number} [port] The port to connect to\n * @property {bson} [bson] The BSON instance to use for new connections\n * @property {number} [maxPoolSize=100] The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections.\n * @property {number} [minPoolSize=0] The minimum number of connections that MUST exist at any moment in a single connection pool.\n * @property {number} [maxIdleTimeMS] The maximum amount of time a connection should remain idle in the connection pool before being marked idle.\n * @property {number} [waitQueueTimeoutMS=0] The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit.\n */\n\n/**\n * A pool of connections which dynamically resizes, and emit events related to pool activity\n *\n * @property {number} generation An integer representing the SDAM generation of the pool\n * @property {number} totalConnectionCount An integer expressing how many total connections (active + in use) the pool currently has\n * @property {number} availableConnectionCount An integer expressing how many connections are currently available in the pool.\n * @property {string} address The address of the endpoint the pool is connected to\n *\n * @emits ConnectionPool#connectionPoolCreated\n * @emits ConnectionPool#connectionPoolClosed\n * @emits ConnectionPool#connectionCreated\n * @emits ConnectionPool#connectionReady\n * @emits ConnectionPool#connectionClosed\n * @emits ConnectionPool#connectionCheckOutStarted\n * @emits ConnectionPool#connectionCheckOutFailed\n * @emits ConnectionPool#connectionCheckedOut\n * @emits ConnectionPool#connectionCheckedIn\n * @emits ConnectionPool#connectionPoolCleared\n */\nclass ConnectionPool extends EventEmitter {\n /**\n * Create a new Connection Pool\n *\n * @param {ConnectionPoolOptions} options\n */\n constructor(options) {\n super();\n options = options || {};\n\n this.closed = false;\n this.options = resolveOptions(options, {\n connectionType: Connection,\n maxPoolSize: typeof options.maxPoolSize === 'number' ? options.maxPoolSize : 100,\n minPoolSize: typeof options.minPoolSize === 'number' ? options.minPoolSize : 0,\n maxIdleTimeMS: typeof options.maxIdleTimeMS === 'number' ? options.maxIdleTimeMS : 0,\n waitQueueTimeoutMS:\n typeof options.waitQueueTimeoutMS === 'number' ? options.waitQueueTimeoutMS : 0,\n autoEncrypter: options.autoEncrypter,\n metadata: options.metadata\n });\n\n if (options.minSize > options.maxSize) {\n throw new TypeError(\n 'Connection pool minimum size must not be greater than maxiumum pool size'\n );\n }\n\n this[kLogger] = Logger('ConnectionPool', options);\n this[kConnections] = new Denque();\n this[kPermits] = this.options.maxPoolSize;\n this[kMinPoolSizeTimer] = undefined;\n this[kGeneration] = 0;\n this[kConnectionCounter] = makeCounter(1);\n this[kCancellationToken] = new EventEmitter();\n this[kCancellationToken].setMaxListeners(Infinity);\n this[kWaitQueue] = new Denque();\n\n process.nextTick(() => {\n this.emit('connectionPoolCreated', new ConnectionPoolCreatedEvent(this));\n ensureMinPoolSize(this);\n });\n }\n\n get address() {\n return `${this.options.host}:${this.options.port}`;\n }\n\n get generation() {\n return this[kGeneration];\n }\n\n get totalConnectionCount() {\n return this[kConnections].length + (this.options.maxPoolSize - this[kPermits]);\n }\n\n get availableConnectionCount() {\n return this[kConnections].length;\n }\n\n get waitQueueSize() {\n return this[kWaitQueue].length;\n }\n\n /**\n * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it\n * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or\n * explicitly destroyed by the new owner.\n *\n * @param {ConnectionPool~checkOutCallback} callback\n */\n checkOut(callback) {\n this.emit('connectionCheckOutStarted', new ConnectionCheckOutStartedEvent(this));\n\n if (this.closed) {\n this.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(this, 'poolClosed'));\n callback(new PoolClosedError(this));\n return;\n }\n\n const waitQueueMember = { callback };\n\n const pool = this;\n const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS;\n if (waitQueueTimeoutMS) {\n waitQueueMember.timer = setTimeout(() => {\n waitQueueMember[kCancelled] = true;\n waitQueueMember.timer = undefined;\n\n pool.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(pool, 'timeout'));\n waitQueueMember.callback(new WaitQueueTimeoutError(pool));\n }, waitQueueTimeoutMS);\n }\n\n this[kWaitQueue].push(waitQueueMember);\n setImmediate(() => processWaitQueue(this));\n }\n\n /**\n * Check a connection into the pool.\n *\n * @param {Connection} connection The connection to check in\n */\n checkIn(connection) {\n const poolClosed = this.closed;\n const stale = connectionIsStale(this, connection);\n const willDestroy = !!(poolClosed || stale || connection.closed);\n\n if (!willDestroy) {\n connection.markAvailable();\n this[kConnections].push(connection);\n }\n\n this.emit('connectionCheckedIn', new ConnectionCheckedInEvent(this, connection));\n\n if (willDestroy) {\n const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale';\n destroyConnection(this, connection, reason);\n }\n\n setImmediate(() => processWaitQueue(this));\n }\n\n /**\n * Clear the pool\n *\n * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a\n * previous generation will eventually be pruned during subsequent checkouts.\n */\n clear() {\n this[kGeneration] += 1;\n this.emit('connectionPoolCleared', new ConnectionPoolClearedEvent(this));\n }\n\n /**\n * Close the pool\n *\n * @param {object} [options] Optional settings\n * @param {boolean} [options.force] Force close connections\n * @param {Function} callback\n */\n close(options, callback) {\n if (typeof options === 'function') {\n callback = options;\n }\n\n options = Object.assign({ force: false }, options);\n if (this.closed) {\n return callback();\n }\n\n // immediately cancel any in-flight connections\n this[kCancellationToken].emit('cancel');\n\n // drain the wait queue\n while (this.waitQueueSize) {\n const waitQueueMember = this[kWaitQueue].pop();\n clearTimeout(waitQueueMember.timer);\n if (!waitQueueMember[kCancelled]) {\n waitQueueMember.callback(new MongoError('connection pool closed'));\n }\n }\n\n // clear the min pool size timer\n if (this[kMinPoolSizeTimer]) {\n clearTimeout(this[kMinPoolSizeTimer]);\n }\n\n // end the connection counter\n if (typeof this[kConnectionCounter].return === 'function') {\n this[kConnectionCounter].return();\n }\n\n // mark the pool as closed immediately\n this.closed = true;\n\n eachAsync(\n this[kConnections].toArray(),\n (conn, cb) => {\n this.emit('connectionClosed', new ConnectionClosedEvent(this, conn, 'poolClosed'));\n conn.destroy(options, cb);\n },\n err => {\n this[kConnections].clear();\n this.emit('connectionPoolClosed', new ConnectionPoolClosedEvent(this));\n callback(err);\n }\n );\n }\n\n /**\n * Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda\n * has completed by calling back.\n *\n * NOTE: please note the required signature of `fn`\n *\n * @param {ConnectionPool~withConnectionCallback} fn A function which operates on a managed connection\n * @param {Function} callback The original callback\n * @return {Promise}\n */\n withConnection(fn, callback) {\n this.checkOut((err, conn) => {\n // don't callback with `err` here, we might want to act upon it inside `fn`\n\n fn(err, conn, (fnErr, result) => {\n if (typeof callback === 'function') {\n if (fnErr) {\n callback(fnErr);\n } else {\n callback(undefined, result);\n }\n }\n\n if (conn) {\n this.checkIn(conn);\n }\n });\n });\n }\n}\n\nfunction ensureMinPoolSize(pool) {\n if (pool.closed || pool.options.minPoolSize === 0) {\n return;\n }\n\n const minPoolSize = pool.options.minPoolSize;\n for (let i = pool.totalConnectionCount; i < minPoolSize; ++i) {\n createConnection(pool);\n }\n\n pool[kMinPoolSizeTimer] = setTimeout(() => ensureMinPoolSize(pool), 10);\n}\n\nfunction connectionIsStale(pool, connection) {\n return connection.generation !== pool[kGeneration];\n}\n\nfunction connectionIsIdle(pool, connection) {\n return !!(pool.options.maxIdleTimeMS && connection.idleTime > pool.options.maxIdleTimeMS);\n}\n\nfunction createConnection(pool, callback) {\n const connectOptions = Object.assign(\n {\n id: pool[kConnectionCounter].next().value,\n generation: pool[kGeneration]\n },\n pool.options\n );\n\n pool[kPermits]--;\n connect(connectOptions, pool[kCancellationToken], (err, connection) => {\n if (err) {\n pool[kPermits]++;\n pool[kLogger].debug(`connection attempt failed with error [${JSON.stringify(err)}]`);\n if (typeof callback === 'function') {\n callback(err);\n }\n\n return;\n }\n\n // The pool might have closed since we started trying to create a connection\n if (pool.closed) {\n connection.destroy({ force: true });\n return;\n }\n\n // forward all events from the connection to the pool\n relayEvents(connection, pool, [\n 'commandStarted',\n 'commandFailed',\n 'commandSucceeded',\n 'clusterTimeReceived'\n ]);\n\n pool.emit('connectionCreated', new ConnectionCreatedEvent(pool, connection));\n\n connection.markAvailable();\n pool.emit('connectionReady', new ConnectionReadyEvent(pool, connection));\n\n // if a callback has been provided, check out the connection immediately\n if (typeof callback === 'function') {\n callback(undefined, connection);\n return;\n }\n\n // otherwise add it to the pool for later acquisition, and try to process the wait queue\n pool[kConnections].push(connection);\n setImmediate(() => processWaitQueue(pool));\n });\n}\n\nfunction destroyConnection(pool, connection, reason) {\n pool.emit('connectionClosed', new ConnectionClosedEvent(pool, connection, reason));\n\n // allow more connections to be created\n pool[kPermits]++;\n\n // destroy the connection\n setImmediate(() => connection.destroy());\n}\n\nfunction processWaitQueue(pool) {\n if (pool.closed) {\n return;\n }\n\n while (pool.waitQueueSize) {\n const waitQueueMember = pool[kWaitQueue].peekFront();\n if (waitQueueMember[kCancelled]) {\n pool[kWaitQueue].shift();\n continue;\n }\n\n if (!pool.availableConnectionCount) {\n break;\n }\n\n const connection = pool[kConnections].shift();\n const isStale = connectionIsStale(pool, connection);\n const isIdle = connectionIsIdle(pool, connection);\n if (!isStale && !isIdle && !connection.closed) {\n pool.emit('connectionCheckedOut', new ConnectionCheckedOutEvent(pool, connection));\n clearTimeout(waitQueueMember.timer);\n pool[kWaitQueue].shift();\n waitQueueMember.callback(undefined, connection);\n return;\n }\n\n const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle';\n destroyConnection(pool, connection, reason);\n }\n\n const maxPoolSize = pool.options.maxPoolSize;\n if (pool.waitQueueSize && (maxPoolSize <= 0 || pool.totalConnectionCount < maxPoolSize)) {\n createConnection(pool, (err, connection) => {\n const waitQueueMember = pool[kWaitQueue].shift();\n if (waitQueueMember == null) {\n if (err == null) {\n pool[kConnections].push(connection);\n }\n\n return;\n }\n\n if (waitQueueMember[kCancelled]) {\n return;\n }\n\n if (err) {\n pool.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(pool, err));\n } else {\n pool.emit('connectionCheckedOut', new ConnectionCheckedOutEvent(pool, connection));\n }\n\n clearTimeout(waitQueueMember.timer);\n waitQueueMember.callback(err, connection);\n });\n\n return;\n }\n}\n\n/**\n * A callback provided to `withConnection`\n *\n * @callback ConnectionPool~withConnectionCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {Connection} connection The managed connection which was checked out of the pool.\n * @param {Function} callback A function to call back after connection management is complete\n */\n\n/**\n * A callback provided to `checkOut`\n *\n * @callback ConnectionPool~checkOutCallback\n * @param {MongoError} error An error instance representing the error during checkout\n * @param {Connection} connection A connection from the pool\n */\n\n/**\n * Emitted once when the connection pool is created\n *\n * @event ConnectionPool#connectionPoolCreated\n * @type {PoolCreatedEvent}\n */\n\n/**\n * Emitted once when the connection pool is closed\n *\n * @event ConnectionPool#connectionPoolClosed\n * @type {PoolClosedEvent}\n */\n\n/**\n * Emitted each time a connection is created\n *\n * @event ConnectionPool#connectionCreated\n * @type {ConnectionCreatedEvent}\n */\n\n/**\n * Emitted when a connection becomes established, and is ready to use\n *\n * @event ConnectionPool#connectionReady\n * @type {ConnectionReadyEvent}\n */\n\n/**\n * Emitted when a connection is closed\n *\n * @event ConnectionPool#connectionClosed\n * @type {ConnectionClosedEvent}\n */\n\n/**\n * Emitted when an attempt to check out a connection begins\n *\n * @event ConnectionPool#connectionCheckOutStarted\n * @type {ConnectionCheckOutStartedEvent}\n */\n\n/**\n * Emitted when an attempt to check out a connection fails\n *\n * @event ConnectionPool#connectionCheckOutFailed\n * @type {ConnectionCheckOutFailedEvent}\n */\n\n/**\n * Emitted each time a connection is successfully checked out of the connection pool\n *\n * @event ConnectionPool#connectionCheckedOut\n * @type {ConnectionCheckedOutEvent}\n */\n\n/**\n * Emitted each time a connection is successfully checked into the connection pool\n *\n * @event ConnectionPool#connectionCheckedIn\n * @type {ConnectionCheckedInEvent}\n */\n\n/**\n * Emitted each time the connection pool is cleared and it's generation incremented\n *\n * @event ConnectionPool#connectionPoolCleared\n * @type {PoolClearedEvent}\n */\n\nmodule.exports = {\n ConnectionPool\n};\n","'use strict';\nconst MongoError = require('../core/error').MongoError;\n\n/**\n * An error indicating a connection pool is closed\n *\n * @property {string} address The address of the connection pool\n * @extends MongoError\n */\nclass PoolClosedError extends MongoError {\n constructor(pool) {\n super('Attempted to check out a connection from closed connection pool');\n this.name = 'MongoPoolClosedError';\n this.address = pool.address;\n }\n}\n\n/**\n * An error thrown when a request to check out a connection times out\n *\n * @property {string} address The address of the connection pool\n * @extends MongoError\n */\nclass WaitQueueTimeoutError extends MongoError {\n constructor(pool) {\n super('Timed out while checking out a connection from connection pool');\n this.name = 'MongoWaitQueueTimeoutError';\n this.address = pool.address;\n }\n}\n\nmodule.exports = {\n PoolClosedError,\n WaitQueueTimeoutError\n};\n","'use strict';\n\n/**\n * The base class for all monitoring events published from the connection pool\n *\n * @property {number} time A timestamp when the event was created\n * @property {string} address The address (host/port pair) of the pool\n */\nclass ConnectionPoolMonitoringEvent {\n constructor(pool) {\n this.time = new Date();\n this.address = pool.address;\n }\n}\n\n/**\n * An event published when a connection pool is created\n *\n * @property {Object} options The options used to create this connection pool\n */\nclass ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent {\n constructor(pool) {\n super(pool);\n this.options = pool.options;\n }\n}\n\n/**\n * An event published when a connection pool is closed\n */\nclass ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent {\n constructor(pool) {\n super(pool);\n }\n}\n\n/**\n * An event published when a connection pool creates a new connection\n *\n * @property {number} connectionId A monotonically increasing, per-pool id for the newly created connection\n */\nclass ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent {\n constructor(pool, connection) {\n super(pool);\n this.connectionId = connection.id;\n }\n}\n\n/**\n * An event published when a connection is ready for use\n *\n * @property {number} connectionId The id of the connection\n */\nclass ConnectionReadyEvent extends ConnectionPoolMonitoringEvent {\n constructor(pool, connection) {\n super(pool);\n this.connectionId = connection.id;\n }\n}\n\n/**\n * An event published when a connection is closed\n *\n * @property {number} connectionId The id of the connection\n * @property {string} reason The reason the connection was closed\n */\nclass ConnectionClosedEvent extends ConnectionPoolMonitoringEvent {\n constructor(pool, connection, reason) {\n super(pool);\n this.connectionId = connection.id;\n this.reason = reason || 'unknown';\n }\n}\n\n/**\n * An event published when a request to check a connection out begins\n */\nclass ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent {\n constructor(pool) {\n super(pool);\n }\n}\n\n/**\n * An event published when a request to check a connection out fails\n *\n * @property {string} reason The reason the attempt to check out failed\n */\nclass ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent {\n constructor(pool, reason) {\n super(pool);\n this.reason = reason;\n }\n}\n\n/**\n * An event published when a connection is checked out of the connection pool\n *\n * @property {number} connectionId The id of the connection\n */\nclass ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent {\n constructor(pool, connection) {\n super(pool);\n this.connectionId = connection.id;\n }\n}\n\n/**\n * An event published when a connection is checked into the connection pool\n *\n * @property {number} connectionId The id of the connection\n */\nclass ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent {\n constructor(pool, connection) {\n super(pool);\n this.connectionId = connection.id;\n }\n}\n\n/**\n * An event published when a connection pool is cleared\n */\nclass ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent {\n constructor(pool) {\n super(pool);\n }\n}\n\nconst CMAP_EVENT_NAMES = [\n 'connectionPoolCreated',\n 'connectionPoolClosed',\n 'connectionCreated',\n 'connectionReady',\n 'connectionClosed',\n 'connectionCheckOutStarted',\n 'connectionCheckOutFailed',\n 'connectionCheckedOut',\n 'connectionCheckedIn',\n 'connectionPoolCleared'\n];\n\nmodule.exports = {\n CMAP_EVENT_NAMES,\n ConnectionPoolCreatedEvent,\n ConnectionPoolClosedEvent,\n ConnectionCreatedEvent,\n ConnectionReadyEvent,\n ConnectionClosedEvent,\n ConnectionCheckOutStartedEvent,\n ConnectionCheckOutFailedEvent,\n ConnectionCheckedOutEvent,\n ConnectionCheckedInEvent,\n ConnectionPoolClearedEvent\n};\n","'use strict';\n\nconst Duplex = require('stream').Duplex;\nconst BufferList = require('bl');\nconst MongoParseError = require('../core/error').MongoParseError;\nconst decompress = require('../core/wireprotocol/compression').decompress;\nconst Response = require('../core/connection/commands').Response;\nconst BinMsg = require('../core/connection/msg').BinMsg;\nconst MongoError = require('../core/error').MongoError;\nconst OP_COMPRESSED = require('../core/wireprotocol/shared').opcodes.OP_COMPRESSED;\nconst OP_MSG = require('../core/wireprotocol/shared').opcodes.OP_MSG;\nconst MESSAGE_HEADER_SIZE = require('../core/wireprotocol/shared').MESSAGE_HEADER_SIZE;\nconst COMPRESSION_DETAILS_SIZE = require('../core/wireprotocol/shared').COMPRESSION_DETAILS_SIZE;\nconst opcodes = require('../core/wireprotocol/shared').opcodes;\nconst compress = require('../core/wireprotocol/compression').compress;\nconst compressorIDs = require('../core/wireprotocol/compression').compressorIDs;\nconst uncompressibleCommands = require('../core/wireprotocol/compression').uncompressibleCommands;\nconst Msg = require('../core/connection/msg').Msg;\n\nconst kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4;\nconst kBuffer = Symbol('buffer');\n\n/**\n * A duplex stream that is capable of reading and writing raw wire protocol messages, with\n * support for optional compression\n */\nclass MessageStream extends Duplex {\n constructor(options) {\n options = options || {};\n super(options);\n\n this.bson = options.bson;\n this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize;\n\n this[kBuffer] = new BufferList();\n }\n\n _write(chunk, _, callback) {\n const buffer = this[kBuffer];\n buffer.append(chunk);\n\n processIncomingData(this, callback);\n }\n\n _read(/* size */) {\n // NOTE: This implementation is empty because we explicitly push data to be read\n // when `writeMessage` is called.\n return;\n }\n\n writeCommand(command, operationDescription) {\n // TODO: agreed compressor should live in `StreamDescription`\n const shouldCompress = operationDescription && !!operationDescription.agreedCompressor;\n if (!shouldCompress || !canCompress(command)) {\n const data = command.toBin();\n this.push(Array.isArray(data) ? Buffer.concat(data) : data);\n return;\n }\n\n // otherwise, compress the message\n const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin());\n const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE);\n\n // Extract information needed for OP_COMPRESSED from the uncompressed message\n const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12);\n\n // Compress the message body\n compress({ options: operationDescription }, messageToBeCompressed, (err, compressedMessage) => {\n if (err) {\n operationDescription.cb(err, null);\n return;\n }\n\n // Create the msgHeader of OP_COMPRESSED\n const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE);\n msgHeader.writeInt32LE(\n MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length,\n 0\n ); // messageLength\n msgHeader.writeInt32LE(command.requestId, 4); // requestID\n msgHeader.writeInt32LE(0, 8); // responseTo (zero)\n msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode\n\n // Create the compression details of OP_COMPRESSED\n const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE);\n compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode\n compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader\n compressionDetails.writeUInt8(compressorIDs[operationDescription.agreedCompressor], 8); // compressorID\n\n this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage]));\n });\n }\n}\n\n// Return whether a command contains an uncompressible command term\n// Will return true if command contains no uncompressible command terms\nfunction canCompress(command) {\n const commandDoc = command instanceof Msg ? command.command : command.query;\n const commandName = Object.keys(commandDoc)[0];\n return !uncompressibleCommands.has(commandName);\n}\n\nfunction processIncomingData(stream, callback) {\n const buffer = stream[kBuffer];\n if (buffer.length < 4) {\n callback();\n return;\n }\n\n const sizeOfMessage = buffer.readInt32LE(0);\n if (sizeOfMessage < 0) {\n callback(new MongoParseError(`Invalid message size: ${sizeOfMessage}`));\n return;\n }\n\n if (sizeOfMessage > stream.maxBsonMessageSize) {\n callback(\n new MongoParseError(\n `Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}`\n )\n );\n return;\n }\n\n if (sizeOfMessage > buffer.length) {\n callback();\n return;\n }\n\n const message = buffer.slice(0, sizeOfMessage);\n buffer.consume(sizeOfMessage);\n\n const messageHeader = {\n length: message.readInt32LE(0),\n requestId: message.readInt32LE(4),\n responseTo: message.readInt32LE(8),\n opCode: message.readInt32LE(12)\n };\n\n let ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response;\n const responseOptions = stream.responseOptions;\n if (messageHeader.opCode !== OP_COMPRESSED) {\n const messageBody = message.slice(MESSAGE_HEADER_SIZE);\n stream.emit(\n 'message',\n new ResponseType(stream.bson, message, messageHeader, messageBody, responseOptions)\n );\n\n if (buffer.length >= 4) {\n processIncomingData(stream, callback);\n } else {\n callback();\n }\n\n return;\n }\n\n messageHeader.fromCompressed = true;\n messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE);\n messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4);\n const compressorID = message[MESSAGE_HEADER_SIZE + 8];\n const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9);\n\n // recalculate based on wrapped opcode\n ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response;\n\n decompress(compressorID, compressedBuffer, (err, messageBody) => {\n if (err) {\n callback(err);\n return;\n }\n\n if (messageBody.length !== messageHeader.length) {\n callback(\n new MongoError(\n 'Decompressing a compressed message from the server failed. The message is corrupt.'\n )\n );\n\n return;\n }\n\n stream.emit(\n 'message',\n new ResponseType(stream.bson, message, messageHeader, messageBody, responseOptions)\n );\n\n if (buffer.length >= 4) {\n processIncomingData(stream, callback);\n } else {\n callback();\n }\n });\n}\n\nmodule.exports = MessageStream;\n","'use strict';\nconst parseServerType = require('../core/sdam/server_description').parseServerType;\n\nconst RESPONSE_FIELDS = [\n 'minWireVersion',\n 'maxWireVersion',\n 'maxBsonObjectSize',\n 'maxMessageSizeBytes',\n 'maxWriteBatchSize',\n '__nodejs_mock_server__'\n];\n\nclass StreamDescription {\n constructor(address, options) {\n this.address = address;\n this.type = parseServerType(null);\n this.minWireVersion = undefined;\n this.maxWireVersion = undefined;\n this.maxBsonObjectSize = 16777216;\n this.maxMessageSizeBytes = 48000000;\n this.maxWriteBatchSize = 100000;\n this.compressors =\n options && options.compression && Array.isArray(options.compression.compressors)\n ? options.compression.compressors\n : [];\n }\n\n receiveResponse(response) {\n this.type = parseServerType(response);\n\n RESPONSE_FIELDS.forEach(field => {\n if (typeof response[field] !== 'undefined') {\n this[field] = response[field];\n }\n });\n\n if (response.compression) {\n this.compressor = this.compressors.filter(c => response.compression.indexOf(c) !== -1)[0];\n }\n }\n}\n\nmodule.exports = {\n StreamDescription\n};\n","'use strict';\n\nconst deprecate = require('util').deprecate;\nconst deprecateOptions = require('./utils').deprecateOptions;\nconst checkCollectionName = require('./utils').checkCollectionName;\nconst ObjectID = require('./core').BSON.ObjectID;\nconst MongoError = require('./core').MongoError;\nconst normalizeHintField = require('./utils').normalizeHintField;\nconst decorateCommand = require('./utils').decorateCommand;\nconst decorateWithCollation = require('./utils').decorateWithCollation;\nconst decorateWithReadConcern = require('./utils').decorateWithReadConcern;\nconst formattedOrderClause = require('./utils').formattedOrderClause;\nconst ReadPreference = require('./core').ReadPreference;\nconst unordered = require('./bulk/unordered');\nconst ordered = require('./bulk/ordered');\nconst ChangeStream = require('./change_stream');\nconst executeLegacyOperation = require('./utils').executeLegacyOperation;\nconst WriteConcern = require('./write_concern');\nconst ReadConcern = require('./read_concern');\nconst MongoDBNamespace = require('./utils').MongoDBNamespace;\nconst AggregationCursor = require('./aggregation_cursor');\nconst CommandCursor = require('./command_cursor');\n\n// Operations\nconst ensureIndex = require('./operations/collection_ops').ensureIndex;\nconst group = require('./operations/collection_ops').group;\nconst parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan;\nconst removeDocuments = require('./operations/common_functions').removeDocuments;\nconst save = require('./operations/collection_ops').save;\nconst updateDocuments = require('./operations/common_functions').updateDocuments;\n\nconst AggregateOperation = require('./operations/aggregate');\nconst BulkWriteOperation = require('./operations/bulk_write');\nconst CountDocumentsOperation = require('./operations/count_documents');\nconst CreateIndexesOperation = require('./operations/create_indexes');\nconst DeleteManyOperation = require('./operations/delete_many');\nconst DeleteOneOperation = require('./operations/delete_one');\nconst DistinctOperation = require('./operations/distinct');\nconst DropCollectionOperation = require('./operations/drop').DropCollectionOperation;\nconst DropIndexOperation = require('./operations/drop_index');\nconst DropIndexesOperation = require('./operations/drop_indexes');\nconst EstimatedDocumentCountOperation = require('./operations/estimated_document_count');\nconst FindOperation = require('./operations/find');\nconst FindOneOperation = require('./operations/find_one');\nconst FindAndModifyOperation = require('./operations/find_and_modify');\nconst FindOneAndDeleteOperation = require('./operations/find_one_and_delete');\nconst FindOneAndReplaceOperation = require('./operations/find_one_and_replace');\nconst FindOneAndUpdateOperation = require('./operations/find_one_and_update');\nconst GeoHaystackSearchOperation = require('./operations/geo_haystack_search');\nconst IndexesOperation = require('./operations/indexes');\nconst IndexExistsOperation = require('./operations/index_exists');\nconst IndexInformationOperation = require('./operations/index_information');\nconst InsertManyOperation = require('./operations/insert_many');\nconst InsertOneOperation = require('./operations/insert_one');\nconst IsCappedOperation = require('./operations/is_capped');\nconst ListIndexesOperation = require('./operations/list_indexes');\nconst MapReduceOperation = require('./operations/map_reduce');\nconst OptionsOperation = require('./operations/options_operation');\nconst RenameOperation = require('./operations/rename');\nconst ReIndexOperation = require('./operations/re_index');\nconst ReplaceOneOperation = require('./operations/replace_one');\nconst StatsOperation = require('./operations/stats');\nconst UpdateManyOperation = require('./operations/update_many');\nconst UpdateOneOperation = require('./operations/update_one');\n\nconst executeOperation = require('./operations/execute_operation');\n\n/**\n * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection\n * allowing for insert/update/remove/find and other command operation on that MongoDB collection.\n *\n * **COLLECTION Cannot directly be instantiated**\n * @example\n * const MongoClient = require('mongodb').MongoClient;\n * const test = require('assert');\n * // Connection url\n * const url = 'mongodb://localhost:27017';\n * // Database Name\n * const dbName = 'test';\n * // Connect using MongoClient\n * MongoClient.connect(url, function(err, client) {\n * // Create a collection we want to drop later\n * const col = client.db(dbName).collection('createIndexExample1');\n * // Show that duplicate records got dropped\n * col.find({}).toArray(function(err, items) {\n * test.equal(null, err);\n * test.equal(4, items.length);\n * client.close();\n * });\n * });\n */\n\nconst mergeKeys = ['ignoreUndefined'];\n\n/**\n * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly)\n * @class\n */\nfunction Collection(db, topology, dbName, name, pkFactory, options) {\n checkCollectionName(name);\n\n // Unpack variables\n const internalHint = null;\n const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk;\n const serializeFunctions =\n options == null || options.serializeFunctions == null\n ? db.s.options.serializeFunctions\n : options.serializeFunctions;\n const raw = options == null || options.raw == null ? db.s.options.raw : options.raw;\n const promoteLongs =\n options == null || options.promoteLongs == null\n ? db.s.options.promoteLongs\n : options.promoteLongs;\n const promoteValues =\n options == null || options.promoteValues == null\n ? db.s.options.promoteValues\n : options.promoteValues;\n const promoteBuffers =\n options == null || options.promoteBuffers == null\n ? db.s.options.promoteBuffers\n : options.promoteBuffers;\n const collectionHint = null;\n\n const namespace = new MongoDBNamespace(dbName, name);\n\n // Get the promiseLibrary\n const promiseLibrary = options.promiseLibrary || Promise;\n\n // Set custom primary key factory if provided\n pkFactory = pkFactory == null ? ObjectID : pkFactory;\n\n // Internal state\n this.s = {\n // Set custom primary key factory if provided\n pkFactory: pkFactory,\n // Db\n db: db,\n // Topology\n topology: topology,\n // Options\n options: options,\n // Namespace\n namespace: namespace,\n // Read preference\n readPreference: ReadPreference.fromOptions(options),\n // SlaveOK\n slaveOk: slaveOk,\n // Serialize functions\n serializeFunctions: serializeFunctions,\n // Raw\n raw: raw,\n // promoteLongs\n promoteLongs: promoteLongs,\n // promoteValues\n promoteValues: promoteValues,\n // promoteBuffers\n promoteBuffers: promoteBuffers,\n // internalHint\n internalHint: internalHint,\n // collectionHint\n collectionHint: collectionHint,\n // Promise library\n promiseLibrary: promiseLibrary,\n // Read Concern\n readConcern: ReadConcern.fromOptions(options),\n // Write Concern\n writeConcern: WriteConcern.fromOptions(options)\n };\n}\n\n/**\n * The name of the database this collection belongs to\n * @member {string} dbName\n * @memberof Collection#\n * @readonly\n */\nObject.defineProperty(Collection.prototype, 'dbName', {\n enumerable: true,\n get: function() {\n return this.s.namespace.db;\n }\n});\n\n/**\n * The name of this collection\n * @member {string} collectionName\n * @memberof Collection#\n * @readonly\n */\nObject.defineProperty(Collection.prototype, 'collectionName', {\n enumerable: true,\n get: function() {\n return this.s.namespace.collection;\n }\n});\n\n/**\n * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}`\n * @member {string} namespace\n * @memberof Collection#\n * @readonly\n */\nObject.defineProperty(Collection.prototype, 'namespace', {\n enumerable: true,\n get: function() {\n return this.s.namespace.toString();\n }\n});\n\n/**\n * The current readConcern of the collection. If not explicitly defined for\n * this collection, will be inherited from the parent DB\n * @member {ReadConcern} [readConcern]\n * @memberof Collection#\n * @readonly\n */\nObject.defineProperty(Collection.prototype, 'readConcern', {\n enumerable: true,\n get: function() {\n if (this.s.readConcern == null) {\n return this.s.db.readConcern;\n }\n return this.s.readConcern;\n }\n});\n\n/**\n * The current readPreference of the collection. If not explicitly defined for\n * this collection, will be inherited from the parent DB\n * @member {ReadPreference} [readPreference]\n * @memberof Collection#\n * @readonly\n */\nObject.defineProperty(Collection.prototype, 'readPreference', {\n enumerable: true,\n get: function() {\n if (this.s.readPreference == null) {\n return this.s.db.readPreference;\n }\n\n return this.s.readPreference;\n }\n});\n\n/**\n * The current writeConcern of the collection. If not explicitly defined for\n * this collection, will be inherited from the parent DB\n * @member {WriteConcern} [writeConcern]\n * @memberof Collection#\n * @readonly\n */\nObject.defineProperty(Collection.prototype, 'writeConcern', {\n enumerable: true,\n get: function() {\n if (this.s.writeConcern == null) {\n return this.s.db.writeConcern;\n }\n return this.s.writeConcern;\n }\n});\n\n/**\n * The current index hint for the collection\n * @member {object} [hint]\n * @memberof Collection#\n */\nObject.defineProperty(Collection.prototype, 'hint', {\n enumerable: true,\n get: function() {\n return this.s.collectionHint;\n },\n set: function(v) {\n this.s.collectionHint = normalizeHintField(v);\n }\n});\n\nconst DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot', 'oplogReplay'];\n\n/**\n * Creates a cursor for a query that can be used to iterate over results from MongoDB\n * @method\n * @param {object} [query={}] The cursor query object.\n * @param {object} [options] Optional settings.\n * @param {number} [options.limit=0] Sets the limit of documents returned in the query.\n * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.\n * @param {object} [options.projection] The fields to return in the query. Object of fields to either include or exclude (one of, not both), {'a':1, 'b': 1} **or** {'a': 0, 'b': 0}\n * @param {object} [options.fields] **Deprecated** Use `options.projection` instead\n * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination).\n * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}\n * @param {boolean} [options.explain=false] Explain the query instead of returning the data.\n * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query.\n * @param {boolean} [options.timeout=false] Specify if the cursor can timeout.\n * @param {boolean} [options.tailable=false] Specify if the cursor is tailable.\n * @param {boolean} [options.awaitData=false] Specify if the cursor is a a tailable-await cursor. Requires `tailable` to be true\n * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results.\n * @param {boolean} [options.returnKey=false] Only return the index key.\n * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan.\n * @param {number} [options.min] Set index bounds.\n * @param {number} [options.max] Set index bounds.\n * @param {boolean} [options.showDiskLoc=false] Show disk location of results.\n * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler.\n * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.\n * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.\n * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.\n * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system\n * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.\n * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true\n * @param {boolean} [options.noCursorTimeout] The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {boolean} [options.allowDiskUse] Enables writing to temporary files on the server.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @throws {MongoError}\n * @return {Cursor}\n */\nCollection.prototype.find = deprecateOptions(\n {\n name: 'collection.find',\n deprecatedOptions: DEPRECATED_FIND_OPTIONS,\n optionsIndex: 1\n },\n function(query, options, callback) {\n if (typeof callback === 'object') {\n // TODO(MAJOR): throw in the future\n console.warn('Third parameter to `find()` must be a callback or undefined');\n }\n\n let selector = query;\n // figuring out arguments\n if (typeof callback !== 'function') {\n if (typeof options === 'function') {\n callback = options;\n options = undefined;\n } else if (options == null) {\n callback = typeof selector === 'function' ? selector : undefined;\n selector = typeof selector === 'object' ? selector : undefined;\n }\n }\n\n // Ensure selector is not null\n selector = selector == null ? {} : selector;\n // Validate correctness off the selector\n const object = selector;\n if (Buffer.isBuffer(object)) {\n const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24);\n if (object_size !== object.length) {\n const error = new Error(\n 'query selector raw message size does not match message header size [' +\n object.length +\n '] != [' +\n object_size +\n ']'\n );\n error.name = 'MongoError';\n throw error;\n }\n }\n\n // Check special case where we are using an objectId\n if (selector != null && selector._bsontype === 'ObjectID') {\n selector = { _id: selector };\n }\n\n if (!options) options = {};\n\n let projection = options.projection || options.fields;\n\n if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) {\n projection = projection.length\n ? projection.reduce((result, field) => {\n result[field] = 1;\n return result;\n }, {})\n : { _id: 1 };\n }\n\n // Make a shallow copy of options\n let newOptions = Object.assign({}, options);\n\n // Make a shallow copy of the collection options\n for (let key in this.s.options) {\n if (mergeKeys.indexOf(key) !== -1) {\n newOptions[key] = this.s.options[key];\n }\n }\n\n // Unpack options\n newOptions.skip = options.skip ? options.skip : 0;\n newOptions.limit = options.limit ? options.limit : 0;\n newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw;\n newOptions.hint =\n options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint;\n newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout;\n // // If we have overridden slaveOk otherwise use the default db setting\n newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk;\n\n // Add read preference if needed\n newOptions.readPreference = ReadPreference.resolve(this, newOptions);\n\n // Set slave ok to true if read preference different from primary\n if (\n newOptions.readPreference != null &&\n (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary')\n ) {\n newOptions.slaveOk = true;\n }\n\n // Ensure the query is an object\n if (selector != null && typeof selector !== 'object') {\n throw MongoError.create({ message: 'query selector must be an object', driver: true });\n }\n\n // Build the find command\n const findCommand = {\n find: this.s.namespace.toString(),\n limit: newOptions.limit,\n skip: newOptions.skip,\n query: selector\n };\n\n if (typeof options.allowDiskUse === 'boolean') {\n findCommand.allowDiskUse = options.allowDiskUse;\n }\n\n // Ensure we use the right await data option\n if (typeof newOptions.awaitdata === 'boolean') {\n newOptions.awaitData = newOptions.awaitdata;\n }\n\n // Translate to new command option noCursorTimeout\n if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout;\n\n decorateCommand(findCommand, newOptions, ['session', 'collation']);\n\n if (projection) findCommand.fields = projection;\n\n // Add db object to the new options\n newOptions.db = this.s.db;\n\n // Add the promise library\n newOptions.promiseLibrary = this.s.promiseLibrary;\n\n // Set raw if available at collection level\n if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw;\n // Set promoteLongs if available at collection level\n if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean')\n newOptions.promoteLongs = this.s.promoteLongs;\n if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean')\n newOptions.promoteValues = this.s.promoteValues;\n if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean')\n newOptions.promoteBuffers = this.s.promoteBuffers;\n\n // Sort options\n if (findCommand.sort) {\n findCommand.sort = formattedOrderClause(findCommand.sort);\n }\n\n // Set the readConcern\n decorateWithReadConcern(findCommand, this, options);\n\n // Decorate find command with collation options\n try {\n decorateWithCollation(findCommand, this, options);\n } catch (err) {\n if (typeof callback === 'function') return callback(err, null);\n throw err;\n }\n\n const cursor = this.s.topology.cursor(\n new FindOperation(this, this.s.namespace, findCommand, newOptions),\n newOptions\n );\n\n // TODO: remove this when NODE-2074 is resolved\n if (typeof callback === 'function') {\n callback(null, cursor);\n return;\n }\n\n return cursor;\n }\n);\n\n/**\n * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field,\n * one will be added to each of the documents missing it by the driver, mutating the document. This behavior\n * can be overridden by setting the **forceServerObjectId** flag.\n *\n * @method\n * @param {object} doc Document to insert.\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.insertOne = function(doc, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n // Add ignoreUndefined\n if (this.s.options.ignoreUndefined) {\n options = Object.assign({}, options);\n options.ignoreUndefined = this.s.options.ignoreUndefined;\n }\n\n const insertOneOperation = new InsertOneOperation(this, doc, options);\n\n return executeOperation(this.s.topology, insertOneOperation, callback);\n};\n\n/**\n * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field,\n * one will be added to each of the documents missing it by the driver, mutating the document. This behavior\n * can be overridden by setting the **forceServerObjectId** flag.\n *\n * @method\n * @param {object[]} docs Documents to insert.\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails.\n * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~insertWriteOpCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.insertMany = function(docs, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options ? Object.assign({}, options) : { ordered: true };\n\n const insertManyOperation = new InsertManyOperation(this, docs, options);\n\n return executeOperation(this.s.topology, insertManyOperation, callback);\n};\n\n/**\n * @typedef {Object} Collection~BulkWriteOpResult\n * @property {number} insertedCount Number of documents inserted.\n * @property {number} matchedCount Number of documents matched for update.\n * @property {number} modifiedCount Number of documents modified.\n * @property {number} deletedCount Number of documents deleted.\n * @property {number} upsertedCount Number of documents upserted.\n * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation\n * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation\n * @property {object} result The command result object.\n */\n\n/**\n * The callback format for inserts\n * @callback Collection~bulkWriteOpCallback\n * @param {BulkWriteError} error An error instance representing the error during the execution.\n * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully.\n */\n\n/**\n * Perform a bulkWrite operation without a fluent API\n *\n * Legal operation types are\n *\n * { insertOne: { document: { a: 1 } } }\n *\n * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }\n *\n * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }\n *\n * { updateMany: { filter: {}, update: {$set: {\"a.$[i].x\": 5}}, arrayFilters: [{ \"i.x\": 5 }]} }\n *\n * { deleteOne: { filter: {c:1} } }\n *\n * { deleteMany: { filter: {c:1} } }\n *\n * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}\n *\n * If documents passed in do not contain the **_id** field,\n * one will be added to each of the documents missing it by the driver, mutating the document. This behavior\n * can be overridden by setting the **forceServerObjectId** flag.\n *\n * @method\n * @param {object[]} operations Bulk operations to perform.\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion.\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {object[]} [options.arrayFilters] Determines which array elements to modify for update operation in MongoDB 3.6 or higher.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~bulkWriteOpCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.bulkWrite = function(operations, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || { ordered: true };\n\n if (!Array.isArray(operations)) {\n throw MongoError.create({ message: 'operations must be an array of documents', driver: true });\n }\n\n const bulkWriteOperation = new BulkWriteOperation(this, operations, options);\n\n return executeOperation(this.s.topology, bulkWriteOperation, callback);\n};\n\n/**\n * @typedef {Object} Collection~WriteOpResult\n * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany\n * @property {object} connection The connection object used for the operation.\n * @property {object} result The command result object.\n */\n\n/**\n * The callback format for inserts\n * @callback Collection~writeOpCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {Collection~WriteOpResult} result The result object if the command was executed successfully.\n */\n\n/**\n * @typedef {Object} Collection~insertWriteOpResult\n * @property {number} insertedCount The total amount of documents inserted.\n * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany\n * @property {Object.} insertedIds Map of the index of the inserted document to the id of the inserted document.\n * @property {object} connection The connection object used for the operation.\n * @property {object} result The raw command result object returned from MongoDB (content might vary by server version).\n * @property {number} result.ok Is 1 if the command executed correctly.\n * @property {number} result.n The total count of documents inserted.\n */\n\n/**\n * @typedef {Object} Collection~insertOneWriteOpResult\n * @property {number} insertedCount The total amount of documents inserted.\n * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany\n * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation.\n * @property {object} connection The connection object used for the operation.\n * @property {object} result The raw command result object returned from MongoDB (content might vary by server version).\n * @property {number} result.ok Is 1 if the command executed correctly.\n * @property {number} result.n The total count of documents inserted.\n */\n\n/**\n * The callback format for inserts\n * @callback Collection~insertWriteOpCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully.\n */\n\n/**\n * The callback format for inserts\n * @callback Collection~insertOneWriteOpCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully.\n */\n\n/**\n * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field,\n * one will be added to each of the documents missing it by the driver, mutating the document. This behavior\n * can be overridden by setting the **forceServerObjectId** flag.\n *\n * @method\n * @param {(object|object[])} docs Documents to insert.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~insertWriteOpCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use insertOne, insertMany or bulkWrite\n */\nCollection.prototype.insert = deprecate(function(docs, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || { ordered: false };\n docs = !Array.isArray(docs) ? [docs] : docs;\n\n if (options.keepGoing === true) {\n options.ordered = false;\n }\n\n return this.insertMany(docs, options, callback);\n}, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.');\n\n/**\n * @typedef {Object} Collection~updateWriteOpResult\n * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version.\n * @property {Number} result.ok Is 1 if the command executed correctly.\n * @property {Number} result.n The total count of documents scanned.\n * @property {Number} result.nModified The total count of documents modified.\n * @property {Object} connection The connection object used for the operation.\n * @property {Number} matchedCount The number of documents that matched the filter.\n * @property {Number} modifiedCount The number of documents that were modified.\n * @property {Number} upsertedCount The number of documents upserted.\n * @property {Object} upsertedId The upserted id.\n * @property {ObjectId} upsertedId._id The upserted _id returned from the server.\n * @property {Object} message The raw msg response wrapped in an internal class\n * @property {object[]} [ops] In a response to {@link Collection#replaceOne replaceOne}, contains the new value of the document on the server. This is the same document that was originally passed in, and is only here for legacy purposes.\n */\n\n/**\n * The callback format for inserts\n * @callback Collection~updateWriteOpCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully.\n */\n\n/**\n * Update a single document in a collection\n * @method\n * @param {object} filter The Filter used to select the document to update\n * @param {object} update The update operations to be applied to the document\n * @param {object} [options] Optional settings.\n * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.\n * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query..\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~updateWriteOpCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.updateOne = function(filter, update, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = Object.assign({}, options);\n\n // Add ignoreUndefined\n if (this.s.options.ignoreUndefined) {\n options = Object.assign({}, options);\n options.ignoreUndefined = this.s.options.ignoreUndefined;\n }\n\n return executeOperation(\n this.s.topology,\n new UpdateOneOperation(this, filter, update, options),\n callback\n );\n};\n\n/**\n * Replace a document in a collection with another document\n * @method\n * @param {object} filter The Filter used to select the document to replace\n * @param {object} doc The Document that replaces the matching document\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.\n * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~updateWriteOpCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.replaceOne = function(filter, doc, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = Object.assign({}, options);\n\n // Add ignoreUndefined\n if (this.s.options.ignoreUndefined) {\n options = Object.assign({}, options);\n options.ignoreUndefined = this.s.options.ignoreUndefined;\n }\n\n return executeOperation(\n this.s.topology,\n new ReplaceOneOperation(this, filter, doc, options),\n callback\n );\n};\n\n/**\n * Update multiple documents in a collection\n * @method\n * @param {object} filter The Filter used to select the documents to update\n * @param {object} update The update operations to be applied to the documents\n * @param {object} [options] Optional settings.\n * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.\n * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query..\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~updateWriteOpCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.updateMany = function(filter, update, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = Object.assign({}, options);\n\n // Add ignoreUndefined\n if (this.s.options.ignoreUndefined) {\n options = Object.assign({}, options);\n options.ignoreUndefined = this.s.options.ignoreUndefined;\n }\n\n return executeOperation(\n this.s.topology,\n new UpdateManyOperation(this, filter, update, options),\n callback\n );\n};\n\n/**\n * Updates documents.\n * @method\n * @param {object} selector The selector for the update operation.\n * @param {object} update The update operations to be applied to the documents\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.upsert=false] Update operation is an upsert.\n * @param {boolean} [options.multi=false] Update one/all documents with operation.\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.\n * @param {Collection~writeOpCallback} [callback] The command result callback\n * @throws {MongoError}\n * @return {Promise} returns Promise if no callback passed\n * @deprecated use updateOne, updateMany or bulkWrite\n */\nCollection.prototype.update = deprecate(function(selector, update, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n // Add ignoreUndefined\n if (this.s.options.ignoreUndefined) {\n options = Object.assign({}, options);\n options.ignoreUndefined = this.s.options.ignoreUndefined;\n }\n\n return executeLegacyOperation(this.s.topology, updateDocuments, [\n this,\n selector,\n update,\n options,\n callback\n ]);\n}, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.');\n\n/**\n * @typedef {Object} Collection~deleteWriteOpResult\n * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version.\n * @property {Number} result.ok Is 1 if the command executed correctly.\n * @property {Number} result.n The total count of documents deleted.\n * @property {Object} connection The connection object used for the operation.\n * @property {Number} deletedCount The number of documents deleted.\n */\n\n/**\n * The callback format for deletes\n * @callback Collection~deleteWriteOpCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully.\n */\n\n/**\n * Delete a document from a collection\n * @method\n * @param {object} filter The Filter used to select the document to remove\n * @param {object} [options] Optional settings.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {string|object} [options.hint] optional index hint for optimizing the filter query\n * @param {Collection~deleteWriteOpCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.deleteOne = function(filter, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = Object.assign({}, options);\n\n // Add ignoreUndefined\n if (this.s.options.ignoreUndefined) {\n options = Object.assign({}, options);\n options.ignoreUndefined = this.s.options.ignoreUndefined;\n }\n\n const deleteOneOperation = new DeleteOneOperation(this, filter, options);\n\n return executeOperation(this.s.topology, deleteOneOperation, callback);\n};\n\nCollection.prototype.removeOne = Collection.prototype.deleteOne;\n\n/**\n * Delete multiple documents from a collection\n * @method\n * @param {object} filter The Filter used to select the documents to remove\n * @param {object} [options] Optional settings.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {string|object} [options.hint] optional index hint for optimizing the filter query\n * @param {Collection~deleteWriteOpCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.deleteMany = function(filter, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = Object.assign({}, options);\n\n // Add ignoreUndefined\n if (this.s.options.ignoreUndefined) {\n options = Object.assign({}, options);\n options.ignoreUndefined = this.s.options.ignoreUndefined;\n }\n\n const deleteManyOperation = new DeleteManyOperation(this, filter, options);\n\n return executeOperation(this.s.topology, deleteManyOperation, callback);\n};\n\nCollection.prototype.removeMany = Collection.prototype.deleteMany;\n\n/**\n * Remove documents.\n * @method\n * @param {object} selector The selector for the update operation.\n * @param {object} [options] Optional settings.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.single=false] Removes the first document found.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~writeOpCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n * @deprecated use deleteOne, deleteMany or bulkWrite\n */\nCollection.prototype.remove = deprecate(function(selector, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n // Add ignoreUndefined\n if (this.s.options.ignoreUndefined) {\n options = Object.assign({}, options);\n options.ignoreUndefined = this.s.options.ignoreUndefined;\n }\n\n return executeLegacyOperation(this.s.topology, removeDocuments, [\n this,\n selector,\n options,\n callback\n ]);\n}, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.');\n\n/**\n * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic\n * operators and update instead for more efficient operations.\n * @method\n * @param {object} doc Document to save\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~writeOpCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n * @deprecated use insertOne, insertMany, updateOne or updateMany\n */\nCollection.prototype.save = deprecate(function(doc, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n // Add ignoreUndefined\n if (this.s.options.ignoreUndefined) {\n options = Object.assign({}, options);\n options.ignoreUndefined = this.s.options.ignoreUndefined;\n }\n\n return executeLegacyOperation(this.s.topology, save, [this, doc, options, callback]);\n}, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.');\n\n/**\n * The callback format for results\n * @callback Collection~resultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {object} result The result object if the command was executed successfully.\n */\n\n/**\n * The callback format for an aggregation call\n * @callback Collection~aggregationCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully.\n */\n\n/**\n * Fetches the first document that matches the query\n * @method\n * @param {object} query Query for find Operation\n * @param {object} [options] Optional settings.\n * @param {number} [options.limit=0] Sets the limit of documents returned in the query.\n * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.\n * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1}\n * @param {object} [options.fields] **Deprecated** Use `options.projection` instead\n * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination).\n * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}\n * @param {boolean} [options.explain=false] Explain the query instead of returning the data.\n * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query.\n * @param {boolean} [options.timeout=false] Specify if the cursor can timeout.\n * @param {boolean} [options.tailable=false] Specify if the cursor is tailable.\n * @param {number} [options.batchSize=1] Set the batchSize for the getMoreCommand when iterating over the query results.\n * @param {boolean} [options.returnKey=false] Only return the index key.\n * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan.\n * @param {number} [options.min] Set index bounds.\n * @param {number} [options.max] Set index bounds.\n * @param {boolean} [options.showDiskLoc=false] Show disk location of results.\n * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler.\n * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.\n * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.\n * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.\n * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system\n * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.findOne = deprecateOptions(\n {\n name: 'collection.find',\n deprecatedOptions: DEPRECATED_FIND_OPTIONS,\n optionsIndex: 1\n },\n function(query, options, callback) {\n if (typeof callback === 'object') {\n // TODO(MAJOR): throw in the future\n console.warn('Third parameter to `findOne()` must be a callback or undefined');\n }\n\n if (typeof query === 'function') (callback = query), (query = {}), (options = {});\n if (typeof options === 'function') (callback = options), (options = {});\n query = query || {};\n options = options || {};\n\n const findOneOperation = new FindOneOperation(this, query, options);\n\n return executeOperation(this.s.topology, findOneOperation, callback);\n }\n);\n\n/**\n * The callback format for the collection method, must be used if strict is specified\n * @callback Collection~collectionResultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {Collection} collection The collection instance.\n */\n\n/**\n * Rename the collection.\n *\n * @method\n * @param {string} newName New name of of the collection.\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~collectionResultCallback} [callback] The results callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.rename = function(newName, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY });\n\n const renameOperation = new RenameOperation(this, newName, options);\n\n return executeOperation(this.s.topology, renameOperation, callback);\n};\n\n/**\n * Drop the collection from the database, removing it permanently. New accesses will create a new collection.\n *\n * @method\n * @param {object} [options] Optional settings.\n * @param {WriteConcern} [options.writeConcern] A full WriteConcern object\n * @param {(number|string)} [options.w] The write concern\n * @param {number} [options.wtimeout] The write concern timeout\n * @param {boolean} [options.j] The journal write concern\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The results callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.drop = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const dropCollectionOperation = new DropCollectionOperation(\n this.s.db,\n this.collectionName,\n options\n );\n\n return executeOperation(this.s.topology, dropCollectionOperation, callback);\n};\n\n/**\n * Returns the options of the collection.\n *\n * @method\n * @param {Object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The results callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.options = function(opts, callback) {\n if (typeof opts === 'function') (callback = opts), (opts = {});\n opts = opts || {};\n\n const optionsOperation = new OptionsOperation(this, opts);\n\n return executeOperation(this.s.topology, optionsOperation, callback);\n};\n\n/**\n * Returns if the collection is a capped collection\n *\n * @method\n * @param {Object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The results callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.isCapped = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const isCappedOperation = new IsCappedOperation(this, options);\n\n return executeOperation(this.s.topology, isCappedOperation, callback);\n};\n\n/**\n * Creates an index on the db and collection collection.\n * @method\n * @param {(string|array|object)} fieldOrSpec Defines the index.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.unique=false] Creates an unique index.\n * @param {boolean} [options.sparse=false] Creates a sparse index.\n * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.\n * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value\n * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates.\n * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates.\n * @param {number} [options.v] Specify the format version of the indexes.\n * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)\n * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)\n * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher)\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {(number|string)} [options.commitQuorum] (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the \"w\" field in a write concern plus \"votingMembers\", which indicates all voting data-bearing nodes.\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n * @example\n * const collection = client.db('foo').collection('bar');\n *\n * await collection.createIndex({ a: 1, b: -1 });\n *\n * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes\n * await collection.createIndex([ [c, 1], [d, -1] ]);\n *\n * // Equivalent to { e: 1 }\n * await collection.createIndex('e');\n *\n * // Equivalent to { f: 1, g: 1 }\n * await collection.createIndex(['f', 'g'])\n *\n * // Equivalent to { h: 1, i: -1 }\n * await collection.createIndex([ { h: 1 }, { i: -1 } ]);\n *\n * // Equivalent to { j: 1, k: -1, l: 2d }\n * await collection.createIndex(['j', ['k', -1], { l: '2d' }])\n */\nCollection.prototype.createIndex = function(fieldOrSpec, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const createIndexesOperation = new CreateIndexesOperation(\n this,\n this.collectionName,\n fieldOrSpec,\n options\n );\n\n return executeOperation(this.s.topology, createIndexesOperation, callback);\n};\n\n/**\n * @typedef {object} Collection~IndexDefinition\n * @description A definition for an index. Used by the createIndex command.\n * @see https://docs.mongodb.com/manual/reference/command/createIndexes/\n */\n\n/**\n * Creates multiple indexes in the collection, this method is only supported for\n * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported\n * error.\n *\n * **Note**: Unlike {@link Collection#createIndex createIndex}, this function takes in raw index specifications.\n * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/ here}.\n *\n * @method\n * @param {Collection~IndexDefinition[]} indexSpecs An array of index specifications to be created\n * @param {Object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {(number|string)} [options.commitQuorum] (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the \"w\" field in a write concern plus \"votingMembers\", which indicates all voting data-bearing nodes.\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n * @example\n * const collection = client.db('foo').collection('bar');\n * await collection.createIndexes([\n * // Simple index on field fizz\n * {\n * key: { fizz: 1 },\n * }\n * // wildcard index\n * {\n * key: { '$**': 1 }\n * },\n * // named index on darmok and jalad\n * {\n * key: { darmok: 1, jalad: -1 }\n * name: 'tanagra'\n * }\n * ]);\n */\nCollection.prototype.createIndexes = function(indexSpecs, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n\n options = options ? Object.assign({}, options) : {};\n\n if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS;\n\n const createIndexesOperation = new CreateIndexesOperation(\n this,\n this.collectionName,\n indexSpecs,\n options\n );\n\n return executeOperation(this.s.topology, createIndexesOperation, callback);\n};\n\n/**\n * Drops an index from this collection.\n * @method\n * @param {string} indexName Name of the index to drop.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.dropIndex = function(indexName, options, callback) {\n const args = Array.prototype.slice.call(arguments, 1);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n\n options = args.length ? args.shift() || {} : {};\n // Run only against primary\n options.readPreference = ReadPreference.PRIMARY;\n\n const dropIndexOperation = new DropIndexOperation(this, indexName, options);\n\n return executeOperation(this.s.topology, dropIndexOperation, callback);\n};\n\n/**\n * Drops all indexes from this collection.\n * @method\n * @param {Object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.dropIndexes = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options ? Object.assign({}, options) : {};\n\n if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS;\n\n const dropIndexesOperation = new DropIndexesOperation(this, options);\n\n return executeOperation(this.s.topology, dropIndexesOperation, callback);\n};\n\n/**\n * Drops all indexes from this collection.\n * @method\n * @deprecated use dropIndexes\n * @param {Collection~resultCallback} callback The command result callback\n * @return {Promise} returns Promise if no [callback] passed\n */\nCollection.prototype.dropAllIndexes = deprecate(\n Collection.prototype.dropIndexes,\n 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.'\n);\n\n/**\n * Reindex all indexes on the collection\n * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.\n * @method\n * @deprecated use db.command instead\n * @param {Object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.reIndex = deprecate(function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const reIndexOperation = new ReIndexOperation(this, options);\n\n return executeOperation(this.s.topology, reIndexOperation, callback);\n}, 'collection.reIndex is deprecated. Use db.command instead.');\n\n/**\n * Get the list of all indexes information for the collection.\n *\n * @method\n * @param {object} [options] Optional settings.\n * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @return {CommandCursor}\n */\nCollection.prototype.listIndexes = function(options) {\n const cursor = new CommandCursor(\n this.s.topology,\n new ListIndexesOperation(this, options),\n options\n );\n\n return cursor;\n};\n\n/**\n * Ensures that an index exists, if it does not it creates it\n * @method\n * @deprecated use createIndexes instead\n * @param {(string|object)} fieldOrSpec Defines the index.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.unique=false] Creates an unique index.\n * @param {boolean} [options.sparse=false] Creates a sparse index.\n * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.\n * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value\n * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates.\n * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates.\n * @param {number} [options.v] Specify the format version of the indexes.\n * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)\n * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeLegacyOperation(this.s.topology, ensureIndex, [\n this,\n fieldOrSpec,\n options,\n callback\n ]);\n}, 'collection.ensureIndex is deprecated. Use createIndexes instead.');\n\n/**\n * Checks if one or more indexes exist on the collection, fails on first non-existing index\n * @method\n * @param {(string|array)} indexes One or more index names to check.\n * @param {Object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.indexExists = function(indexes, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const indexExistsOperation = new IndexExistsOperation(this, indexes, options);\n\n return executeOperation(this.s.topology, indexExistsOperation, callback);\n};\n\n/**\n * Retrieves this collections index info.\n * @method\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.full=false] Returns the full raw index information.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.indexInformation = function(options, callback) {\n const args = Array.prototype.slice.call(arguments, 0);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n options = args.length ? args.shift() || {} : {};\n\n const indexInformationOperation = new IndexInformationOperation(\n this.s.db,\n this.collectionName,\n options\n );\n\n return executeOperation(this.s.topology, indexInformationOperation, callback);\n};\n\n/**\n * The callback format for results\n * @callback Collection~countCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {number} result The count of documents that matched the query.\n */\n\n/**\n * An estimated count of matching documents in the db to a query.\n *\n * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents\n * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments countDocuments}.\n * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount estimatedDocumentCount}.\n *\n * @method\n * @param {object} [query={}] The query for the count.\n * @param {object} [options] Optional settings.\n * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @param {boolean} [options.limit] The limit of documents to count.\n * @param {boolean} [options.skip] The number of documents to skip for the count.\n * @param {string} [options.hint] An index name hint for the query.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~countCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead\n */\nCollection.prototype.count = deprecate(function(query, options, callback) {\n const args = Array.prototype.slice.call(arguments, 0);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n query = args.length ? args.shift() || {} : {};\n options = args.length ? args.shift() || {} : {};\n\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeOperation(\n this.s.topology,\n new EstimatedDocumentCountOperation(this, query, options),\n callback\n );\n}, 'collection.count is deprecated, and will be removed in a future version.' +\n ' Use Collection.countDocuments or Collection.estimatedDocumentCount instead');\n\n/**\n * Gets an estimate of the count of documents in a collection using collection metadata.\n *\n * @method\n * @param {object} [options] Optional settings.\n * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run.\n * @param {Collection~countCallback} [callback] The command result callback.\n * @return {Promise} returns Promise if no callback passed.\n */\nCollection.prototype.estimatedDocumentCount = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const estimatedDocumentCountOperation = new EstimatedDocumentCountOperation(this, options);\n\n return executeOperation(this.s.topology, estimatedDocumentCountOperation, callback);\n};\n\n/**\n * Gets the number of documents matching the filter.\n * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount estimatedDocumentCount}.\n * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments}\n * the following query operators must be replaced:\n *\n * | Operator | Replacement |\n * | -------- | ----------- |\n * | `$where` | [`$expr`][1] |\n * | `$near` | [`$geoWithin`][2] with [`$center`][3] |\n * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] |\n *\n * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/\n * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/\n * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center\n * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere\n *\n * @param {object} [query] the query for the count\n * @param {object} [options] Optional settings.\n * @param {object} [options.collation] Specifies a collation.\n * @param {string|object} [options.hint] The index to use.\n * @param {number} [options.limit] The maximum number of document to count.\n * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run.\n * @param {number} [options.skip] The number of documents to skip before counting.\n * @param {Collection~countCallback} [callback] The command result callback.\n * @return {Promise} returns Promise if no callback passed.\n * @see https://docs.mongodb.com/manual/reference/operator/query/expr/\n * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/\n * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center\n * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere\n */\n\nCollection.prototype.countDocuments = function(query, options, callback) {\n const args = Array.prototype.slice.call(arguments, 0);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n query = args.length ? args.shift() || {} : {};\n options = args.length ? args.shift() || {} : {};\n\n const countDocumentsOperation = new CountDocumentsOperation(this, query, options);\n\n return executeOperation(this.s.topology, countDocumentsOperation, callback);\n};\n\n/**\n * The distinct command returns a list of distinct values for the given key across a collection.\n * @method\n * @param {string} key Field of the document to find distinct values for.\n * @param {object} [query] The query for filtering the set of documents to which we apply the distinct filter.\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.\n * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.distinct = function(key, query, options, callback) {\n const args = Array.prototype.slice.call(arguments, 1);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n const queryOption = args.length ? args.shift() || {} : {};\n const optionsOption = args.length ? args.shift() || {} : {};\n\n const distinctOperation = new DistinctOperation(this, key, queryOption, optionsOption);\n\n return executeOperation(this.s.topology, distinctOperation, callback);\n};\n\n/**\n * Retrieve all the indexes on the collection.\n * @method\n * @param {Object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.indexes = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const indexesOperation = new IndexesOperation(this, options);\n\n return executeOperation(this.s.topology, indexesOperation, callback);\n};\n\n/**\n * Get all the collection statistics.\n *\n * @method\n * @param {object} [options] Optional settings.\n * @param {number} [options.scale] Divide the returned sizes by scale value.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The collection result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.stats = function(options, callback) {\n const args = Array.prototype.slice.call(arguments, 0);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n options = args.length ? args.shift() || {} : {};\n\n const statsOperation = new StatsOperation(this, options);\n\n return executeOperation(this.s.topology, statsOperation, callback);\n};\n\n/**\n * @typedef {Object} Collection~findAndModifyWriteOpResult\n * @property {object} value Document returned from the `findAndModify` command. If no documents were found, `value` will be `null` by default (`returnOriginal: true`), even if a document was upserted; if `returnOriginal` was false, the upserted document will be returned in that case.\n * @property {object} lastErrorObject The raw lastErrorObject returned from the command. See {@link https://docs.mongodb.com/manual/reference/command/findAndModify/index.html#lasterrorobject|findAndModify command documentation}.\n * @property {Number} ok Is 1 if the command executed correctly.\n */\n\n/**\n * The callback format for inserts\n * @callback Collection~findAndModifyCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully.\n */\n\n/**\n * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation.\n *\n * @method\n * @param {object} filter The Filter used to select the document to remove\n * @param {object} [options] Optional settings.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {object} [options.projection] Limits the fields to return for all matching documents.\n * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents.\n * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run.\n * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~findAndModifyCallback} [callback] The collection result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.findOneAndDelete = function(filter, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeOperation(\n this.s.topology,\n new FindOneAndDeleteOperation(this, filter, options),\n callback\n );\n};\n\n/**\n * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation.\n *\n * @method\n * @param {object} filter The Filter used to select the document to replace\n * @param {object} replacement The Document that replaces the matching document\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {string|object} [options.hint] An optional index to use for this operation\n * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run.\n * @param {object} [options.projection] Limits the fields to return for all matching documents.\n * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents.\n * @param {boolean} [options.upsert=false] Upsert the document if it does not exist.\n * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true.\n * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~findAndModifyCallback} [callback] The collection result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.findOneAndReplace = function(filter, replacement, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeOperation(\n this.s.topology,\n new FindOneAndReplaceOperation(this, filter, replacement, options),\n callback\n );\n};\n\n/**\n * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.\n *\n * @method\n * @param {object} filter The Filter used to select the document to update\n * @param {object} update Update operations to be performed on the document\n * @param {object} [options] Optional settings.\n * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {string|object} [options.hint] An optional index to use for this operation\n * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run.\n * @param {object} [options.projection] Limits the fields to return for all matching documents.\n * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents.\n * @param {boolean} [options.upsert=false] Upsert the document if it does not exist.\n * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true.\n * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] An ptional session to use for this operation\n * @param {Collection~findAndModifyCallback} [callback] The collection result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.findOneAndUpdate = function(filter, update, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeOperation(\n this.s.topology,\n new FindOneAndUpdateOperation(this, filter, update, options),\n callback\n );\n};\n\n/**\n * Find and update a document.\n * @method\n * @param {object} query Query object to locate the object to modify.\n * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate.\n * @param {object} doc The fields/vals to be updated.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.remove=false] Set to true to remove the object before returning.\n * @param {boolean} [options.upsert=false] Perform an upsert operation.\n * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove.\n * @param {object} [options.projection] Object containing the field projection for the result returned from the operation.\n * @param {object} [options.fields] **Deprecated** Use `options.projection` instead\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators\n * @param {Collection~findAndModifyCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead\n */\nCollection.prototype.findAndModify = deprecate(\n _findAndModify,\n 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.'\n);\n\n/**\n * @ignore\n */\n\nCollection.prototype._findAndModify = _findAndModify;\n\nfunction _findAndModify(query, sort, doc, options, callback) {\n const args = Array.prototype.slice.call(arguments, 1);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n sort = args.length ? args.shift() || [] : [];\n doc = args.length ? args.shift() : null;\n options = args.length ? args.shift() || {} : {};\n\n // Clone options\n options = Object.assign({}, options);\n // Force read preference primary\n options.readPreference = ReadPreference.PRIMARY;\n\n return executeOperation(\n this.s.topology,\n new FindAndModifyOperation(this, query, sort, doc, options),\n callback\n );\n}\n\n/**\n * Find and remove a document.\n * @method\n * @param {object} query Query object to locate the object to modify.\n * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n * @deprecated use findOneAndDelete instead\n */\nCollection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) {\n const args = Array.prototype.slice.call(arguments, 1);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n sort = args.length ? args.shift() || [] : [];\n options = args.length ? args.shift() || {} : {};\n\n // Add the remove option\n options.remove = true;\n\n return executeOperation(\n this.s.topology,\n new FindAndModifyOperation(this, query, sort, null, options),\n callback\n );\n}, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.');\n\n/**\n * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2\n * @method\n * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution.\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.\n * @param {number} [options.cursor.batchSize=1000] Deprecated. Use `options.batchSize`\n * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >).\n * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).\n * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.\n * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query.\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.\n * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.\n * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.\n * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.\n * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @param {string} [options.comment] Add a comment to an aggregation command\n * @param {string|object} [options.hint] Add an index selection hint to an aggregation command\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~aggregationCallback} callback The command result callback\n * @return {(null|AggregationCursor)}\n */\nCollection.prototype.aggregate = function(pipeline, options, callback) {\n if (Array.isArray(pipeline)) {\n // Set up callback if one is provided\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n // If we have no options or callback we are doing\n // a cursor based aggregation\n if (options == null && callback == null) {\n options = {};\n }\n } else {\n // Aggregation pipeline passed as arguments on the method\n const args = Array.prototype.slice.call(arguments, 0);\n // Get the callback\n callback = args.pop();\n // Get the possible options object\n const opts = args[args.length - 1];\n // If it contains any of the admissible options pop it of the args\n options =\n opts &&\n (opts.readPreference ||\n opts.explain ||\n opts.cursor ||\n opts.out ||\n opts.maxTimeMS ||\n opts.hint ||\n opts.allowDiskUse)\n ? args.pop()\n : {};\n // Left over arguments is the pipeline\n pipeline = args;\n }\n\n const cursor = new AggregationCursor(\n this.s.topology,\n new AggregateOperation(this, pipeline, options),\n options\n );\n\n // TODO: remove this when NODE-2074 is resolved\n if (typeof callback === 'function') {\n callback(null, cursor);\n return;\n }\n\n return cursor;\n};\n\n/**\n * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.\n * @method\n * @since 3.0.0\n * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.\n * @param {object} [options] Optional settings\n * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.\n * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.\n * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query\n * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.\n * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @return {ChangeStream} a ChangeStream instance.\n */\nCollection.prototype.watch = function(pipeline, options) {\n pipeline = pipeline || [];\n options = options || {};\n\n // Allow optionally not specifying a pipeline\n if (!Array.isArray(pipeline)) {\n options = pipeline;\n pipeline = [];\n }\n\n return new ChangeStream(this, pipeline, options);\n};\n\n/**\n * The callback format for results\n * @callback Collection~parallelCollectionScanCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection.\n */\n\n/**\n * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are\n * no ordering guarantees for returned results.\n * @method\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results.\n * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors)\n * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents.\n * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.parallelCollectionScan = deprecate(function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = { numCursors: 1 });\n // Set number of cursors to 1\n options.numCursors = options.numCursors || 1;\n options.batchSize = options.batchSize || 1000;\n\n options = Object.assign({}, options);\n // Ensure we have the right read preference inheritance\n options.readPreference = ReadPreference.resolve(this, options);\n\n // Add a promiseLibrary\n options.promiseLibrary = this.s.promiseLibrary;\n\n if (options.session) {\n options.session = undefined;\n }\n\n return executeLegacyOperation(\n this.s.topology,\n parallelCollectionScan,\n [this, options, callback],\n { skipSessions: true }\n );\n}, 'parallelCollectionScan is deprecated in MongoDB v4.1');\n\n/**\n * Execute a geo search using a geo haystack index on a collection.\n *\n * @method\n * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order.\n * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order.\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {number} [options.maxDistance] Include results up to maxDistance from the point.\n * @param {object} [options.search] Filter the results by a query.\n * @param {number} [options.limit=false] Max number of results to return.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n * @deprecated See {@link https://docs.mongodb.com/manual/geospatial-queries/|geospatial queries docs} for current geospatial support\n */\nCollection.prototype.geoHaystackSearch = deprecate(function(x, y, options, callback) {\n const args = Array.prototype.slice.call(arguments, 2);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n options = args.length ? args.shift() || {} : {};\n\n const geoHaystackSearchOperation = new GeoHaystackSearchOperation(this, x, y, options);\n\n return executeOperation(this.s.topology, geoHaystackSearchOperation, callback);\n}, 'geoHaystackSearch is deprecated, and will be removed in a future version.');\n\n/**\n * Run a group command across a collection\n *\n * @method\n * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by.\n * @param {object} condition An optional condition that must be true for a row to be considered.\n * @param {object} initial Initial value of the aggregation counter object.\n * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated\n * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned.\n * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true.\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.\n */\nCollection.prototype.group = deprecate(function(\n keys,\n condition,\n initial,\n reduce,\n finalize,\n command,\n options,\n callback\n) {\n const args = Array.prototype.slice.call(arguments, 3);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n reduce = args.length ? args.shift() : null;\n finalize = args.length ? args.shift() : null;\n command = args.length ? args.shift() : null;\n options = args.length ? args.shift() || {} : {};\n\n // Make sure we are backward compatible\n if (!(typeof finalize === 'function')) {\n command = finalize;\n finalize = null;\n }\n\n if (\n !Array.isArray(keys) &&\n keys instanceof Object &&\n typeof keys !== 'function' &&\n !(keys._bsontype === 'Code')\n ) {\n keys = Object.keys(keys);\n }\n\n if (typeof reduce === 'function') {\n reduce = reduce.toString();\n }\n\n if (typeof finalize === 'function') {\n finalize = finalize.toString();\n }\n\n // Set up the command as default\n command = command == null ? true : command;\n\n return executeLegacyOperation(this.s.topology, group, [\n this,\n keys,\n condition,\n initial,\n reduce,\n finalize,\n command,\n options,\n callback\n ]);\n},\n'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.');\n\n/**\n * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection.\n *\n * @method\n * @param {(function|string)} map The mapping function.\n * @param {(function|string)} reduce The reduce function.\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}*\n * @param {object} [options.query] Query filter object.\n * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces.\n * @param {number} [options.limit] Number of objects to return from collection.\n * @param {boolean} [options.keeptemp=false] Keep temporary data.\n * @param {(function|string)} [options.finalize] Finalize function.\n * @param {object} [options.scope] Can pass in variables that can be access from map/reduce/finalize.\n * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X.\n * @param {boolean} [options.verbose=false] Provide statistics on job execution time.\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Collection~resultCallback} [callback] The command result callback\n * @throws {MongoError}\n * @return {Promise} returns Promise if no callback passed\n */\nCollection.prototype.mapReduce = function(map, reduce, options, callback) {\n if ('function' === typeof options) (callback = options), (options = {});\n // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers)\n if (null == options.out) {\n throw new Error(\n 'the out option parameter must be defined, see mongodb docs for possible values'\n );\n }\n\n if ('function' === typeof map) {\n map = map.toString();\n }\n\n if ('function' === typeof reduce) {\n reduce = reduce.toString();\n }\n\n if ('function' === typeof options.finalize) {\n options.finalize = options.finalize.toString();\n }\n const mapReduceOperation = new MapReduceOperation(this, map, reduce, options);\n\n return executeOperation(this.s.topology, mapReduceOperation, callback);\n};\n\n/**\n * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.\n *\n * @method\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @return {UnorderedBulkOperation}\n */\nCollection.prototype.initializeUnorderedBulkOp = function(options) {\n options = options || {};\n // Give function's options precedence over session options.\n if (options.ignoreUndefined == null) {\n options.ignoreUndefined = this.s.options.ignoreUndefined;\n }\n\n options.promiseLibrary = this.s.promiseLibrary;\n return unordered(this.s.topology, this, options);\n};\n\n/**\n * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types.\n *\n * @method\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {OrderedBulkOperation} callback The command result callback\n * @return {null}\n */\nCollection.prototype.initializeOrderedBulkOp = function(options) {\n options = options || {};\n // Give function's options precedence over session's options.\n if (options.ignoreUndefined == null) {\n options.ignoreUndefined = this.s.options.ignoreUndefined;\n }\n options.promiseLibrary = this.s.promiseLibrary;\n return ordered(this.s.topology, this, options);\n};\n\n/**\n * Return the db logger\n * @method\n * @return {Logger} return the db logger\n * @ignore\n */\nCollection.prototype.getLogger = function() {\n return this.s.db.s.logger;\n};\n\nmodule.exports = Collection;\n","'use strict';\n\nconst ReadPreference = require('./core').ReadPreference;\nconst MongoError = require('./core').MongoError;\nconst Cursor = require('./cursor');\nconst CursorState = require('./core/cursor').CursorState;\n\n/**\n * @fileOverview The **CommandCursor** class is an internal class that embodies a\n * generalized cursor based on a MongoDB command allowing for iteration over the\n * results returned. It supports one by one document iteration, conversion to an\n * array or can be iterated as a Node 0.10.X or higher stream\n *\n * **CommandCursor Cannot directly be instantiated**\n * @example\n * const MongoClient = require('mongodb').MongoClient;\n * const test = require('assert');\n * // Connection url\n * const url = 'mongodb://localhost:27017';\n * // Database Name\n * const dbName = 'test';\n * // Connect using MongoClient\n * MongoClient.connect(url, function(err, client) {\n * // Create a collection we want to drop later\n * const col = client.db(dbName).collection('listCollectionsExample1');\n * // Insert a bunch of documents\n * col.insert([{a:1, b:1}\n * , {a:2, b:2}, {a:3, b:3}\n * , {a:4, b:4}], {w:1}, function(err, result) {\n * test.equal(null, err);\n * // List the database collections available\n * db.listCollections().toArray(function(err, items) {\n * test.equal(null, err);\n * client.close();\n * });\n * });\n * });\n */\n\n/**\n * Namespace provided by the browser.\n * @external Readable\n */\n\n/**\n * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly)\n * @class CommandCursor\n * @extends external:Readable\n * @fires CommandCursor#data\n * @fires CommandCursor#end\n * @fires CommandCursor#close\n * @fires CommandCursor#readable\n * @return {CommandCursor} an CommandCursor instance.\n */\nclass CommandCursor extends Cursor {\n constructor(topology, ns, cmd, options) {\n super(topology, ns, cmd, options);\n }\n\n /**\n * Set the ReadPreference for the cursor.\n * @method\n * @param {(string|ReadPreference)} readPreference The new read preference for the cursor.\n * @throws {MongoError}\n * @return {Cursor}\n */\n setReadPreference(readPreference) {\n if (this.s.state === CursorState.CLOSED || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n if (this.s.state !== CursorState.INIT) {\n throw MongoError.create({\n message: 'cannot change cursor readPreference after cursor has been accessed',\n driver: true\n });\n }\n\n if (readPreference instanceof ReadPreference) {\n this.options.readPreference = readPreference;\n } else if (typeof readPreference === 'string') {\n this.options.readPreference = new ReadPreference(readPreference);\n } else {\n throw new TypeError('Invalid read preference: ' + readPreference);\n }\n\n return this;\n }\n\n /**\n * Set the batch size for the cursor.\n * @method\n * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}.\n * @throws {MongoError}\n * @return {CommandCursor}\n */\n batchSize(value) {\n if (this.s.state === CursorState.CLOSED || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n if (typeof value !== 'number') {\n throw MongoError.create({ message: 'batchSize requires an integer', driver: true });\n }\n\n if (this.cmd.cursor) {\n this.cmd.cursor.batchSize = value;\n }\n\n this.setCursorBatchSize(value);\n return this;\n }\n\n /**\n * Add a maxTimeMS stage to the aggregation pipeline\n * @method\n * @param {number} value The state maxTimeMS value.\n * @return {CommandCursor}\n */\n maxTimeMS(value) {\n if (this.topology.lastIsMaster().minWireVersion > 2) {\n this.cmd.maxTimeMS = value;\n }\n\n return this;\n }\n\n /**\n * Return the cursor logger\n * @method\n * @return {Logger} return the cursor logger\n * @ignore\n */\n getLogger() {\n return this.logger;\n }\n}\n\n// aliases\nCommandCursor.prototype.get = CommandCursor.prototype.toArray;\n\n/**\n * CommandCursor stream data event, fired for each document in the cursor.\n *\n * @event CommandCursor#data\n * @type {object}\n */\n\n/**\n * CommandCursor stream end event\n *\n * @event CommandCursor#end\n * @type {null}\n */\n\n/**\n * CommandCursor stream close event\n *\n * @event CommandCursor#close\n * @type {null}\n */\n\n/**\n * CommandCursor stream readable event\n *\n * @event CommandCursor#readable\n * @type {null}\n */\n\n/**\n * Get the next available document from the cursor, returns null if no more documents are available.\n * @function CommandCursor.prototype.next\n * @param {CommandCursor~resultCallback} [callback] The result callback.\n * @throws {MongoError}\n * @return {Promise} returns Promise if no callback passed\n */\n\n/**\n * Check if there is any document still available in the cursor\n * @function CommandCursor.prototype.hasNext\n * @param {CommandCursor~resultCallback} [callback] The result callback.\n * @throws {MongoError}\n * @return {Promise} returns Promise if no callback passed\n */\n\n/**\n * The callback format for results\n * @callback CommandCursor~toArrayResultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {object[]} documents All the documents the satisfy the cursor.\n */\n\n/**\n * Returns an array of documents. The caller is responsible for making sure that there\n * is enough memory to store the results. Note that the array only contain partial\n * results when this cursor had been previously accessed.\n * @method CommandCursor.prototype.toArray\n * @param {CommandCursor~toArrayResultCallback} [callback] The result callback.\n * @throws {MongoError}\n * @return {Promise} returns Promise if no callback passed\n */\n\n/**\n * The callback format for results\n * @callback CommandCursor~resultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {(object|null)} result The result object if the command was executed successfully.\n */\n\n/**\n * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,\n * not all of the elements will be iterated if this cursor had been previously accessed.\n * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike\n * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements\n * at any given time if batch size is specified. Otherwise, the caller is responsible\n * for making sure that the entire result can fit the memory.\n * @method CommandCursor.prototype.each\n * @param {CommandCursor~resultCallback} callback The result callback.\n * @throws {MongoError}\n * @return {null}\n */\n\n/**\n * Close the cursor, sending a KillCursor command and emitting close.\n * @method CommandCursor.prototype.close\n * @param {CommandCursor~resultCallback} [callback] The result callback.\n * @return {Promise} returns Promise if no callback passed\n */\n\n/**\n * Is the cursor closed\n * @method CommandCursor.prototype.isClosed\n * @return {boolean}\n */\n\n/**\n * Clone the cursor\n * @function CommandCursor.prototype.clone\n * @return {CommandCursor}\n */\n\n/**\n * Resets the cursor\n * @function CommandCursor.prototype.rewind\n * @return {CommandCursor}\n */\n\n/**\n * The callback format for the forEach iterator method\n * @callback CommandCursor~iteratorCallback\n * @param {Object} doc An emitted document for the iterator\n */\n\n/**\n * The callback error format for the forEach iterator method\n * @callback CommandCursor~endCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n */\n\n/*\n * Iterates over all the documents for this cursor using the iterator, callback pattern.\n * @method CommandCursor.prototype.forEach\n * @param {CommandCursor~iteratorCallback} iterator The iteration callback.\n * @param {CommandCursor~endCallback} callback The end callback.\n * @throws {MongoError}\n * @return {null}\n */\n\nmodule.exports = CommandCursor;\n","'use strict';\n\nmodule.exports = {\n SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces',\n SYSTEM_INDEX_COLLECTION: 'system.indexes',\n SYSTEM_PROFILE_COLLECTION: 'system.profile',\n SYSTEM_USER_COLLECTION: 'system.users',\n SYSTEM_COMMAND_COLLECTION: '$cmd',\n SYSTEM_JS_COLLECTION: 'system.js'\n};\n","'use strict';\n\n/**\n * Context used during authentication\n *\n * @property {Connection} connection The connection to authenticate\n * @property {MongoCredentials} credentials The credentials to use for authentication\n * @property {object} options The options passed to the `connect` method\n * @property {object?} response The response of the initial handshake\n * @property {Buffer?} nonce A random nonce generated for use in an authentication conversation\n */\nclass AuthContext {\n constructor(connection, credentials, options) {\n this.connection = connection;\n this.credentials = credentials;\n this.options = options;\n }\n}\n\nclass AuthProvider {\n constructor(bson) {\n this.bson = bson;\n }\n\n /**\n * Prepare the handshake document before the initial handshake.\n *\n * @param {object} handshakeDoc The document used for the initial handshake on a connection\n * @param {AuthContext} authContext Context for authentication flow\n * @param {function} callback\n */\n prepare(handshakeDoc, context, callback) {\n callback(undefined, handshakeDoc);\n }\n\n /**\n * Authenticate\n *\n * @param {AuthContext} context A shared context for authentication flow\n * @param {authResultCallback} callback The callback to return the result from the authentication\n */\n auth(context, callback) {\n callback(new TypeError('`auth` method must be overridden by subclass'));\n }\n}\n\n/**\n * This is a result from an authentication provider\n *\n * @callback authResultCallback\n * @param {error} error An error object. Set to null if no error present\n * @param {boolean} result The result of the authentication process\n */\n\nmodule.exports = { AuthContext, AuthProvider };\n","'use strict';\n\nconst MongoCR = require('./mongocr');\nconst X509 = require('./x509');\nconst Plain = require('./plain');\nconst GSSAPI = require('./gssapi');\nconst ScramSHA1 = require('./scram').ScramSHA1;\nconst ScramSHA256 = require('./scram').ScramSHA256;\nconst MongoDBAWS = require('./mongodb_aws');\n\n/**\n * Returns the default authentication providers.\n *\n * @param {BSON} bson Bson definition\n * @returns {Object} a mapping of auth names to auth types\n */\nfunction defaultAuthProviders(bson) {\n return {\n 'mongodb-aws': new MongoDBAWS(bson),\n mongocr: new MongoCR(bson),\n x509: new X509(bson),\n plain: new Plain(bson),\n gssapi: new GSSAPI(bson),\n 'scram-sha-1': new ScramSHA1(bson),\n 'scram-sha-256': new ScramSHA256(bson)\n };\n}\n\nmodule.exports = { defaultAuthProviders };\n","'use strict';\nconst dns = require('dns');\n\nconst AuthProvider = require('./auth_provider').AuthProvider;\nconst retrieveKerberos = require('../utils').retrieveKerberos;\nconst MongoError = require('../error').MongoError;\n\nconst kGssapiClient = Symbol('GSSAPI_CLIENT');\nlet kerberos;\n\nclass GSSAPI extends AuthProvider {\n prepare(handshakeDoc, authContext, callback) {\n const host = authContext.options.host;\n const port = authContext.options.port;\n const credentials = authContext.credentials;\n if (!host || !port || !credentials) {\n return callback(\n new MongoError(\n `Connection must specify: ${host ? 'host' : ''}, ${port ? 'port' : ''}, ${\n credentials ? 'host' : 'credentials'\n }.`\n )\n );\n }\n if (kerberos == null) {\n try {\n kerberos = retrieveKerberos();\n } catch (e) {\n return callback(e);\n }\n }\n const username = credentials.username;\n const password = credentials.password;\n const mechanismProperties = credentials.mechanismProperties;\n const serviceName =\n mechanismProperties['gssapiservicename'] ||\n mechanismProperties['gssapiServiceName'] ||\n 'mongodb';\n performGssapiCanonicalizeHostName(host, mechanismProperties, (err, host) => {\n if (err) return callback(err);\n const initOptions = {};\n if (password != null) {\n Object.assign(initOptions, { user: username, password: password });\n }\n kerberos.initializeClient(\n `${serviceName}${process.platform === 'win32' ? '/' : '@'}${host}`,\n initOptions,\n (err, client) => {\n if (err) return callback(new MongoError(err));\n if (client == null) return callback();\n this[kGssapiClient] = client;\n callback(undefined, handshakeDoc);\n }\n );\n });\n }\n auth(authContext, callback) {\n const connection = authContext.connection;\n const credentials = authContext.credentials;\n if (credentials == null) return callback(new MongoError('credentials required'));\n const username = credentials.username;\n const client = this[kGssapiClient];\n if (client == null) return callback(new MongoError('gssapi client missing'));\n function externalCommand(command, cb) {\n return connection.command('$external.$cmd', command, cb);\n }\n client.step('', (err, payload) => {\n if (err) return callback(err);\n externalCommand(saslStart(payload), (err, response) => {\n const result = response.result;\n if (err) return callback(err);\n negotiate(client, 10, result.payload, (err, payload) => {\n if (err) return callback(err);\n externalCommand(saslContinue(payload, result.conversationId), (err, response) => {\n const result = response.result;\n if (err) return callback(err);\n finalize(client, username, result.payload, (err, payload) => {\n if (err) return callback(err);\n externalCommand(\n {\n saslContinue: 1,\n conversationId: result.conversationId,\n payload\n },\n (err, result) => {\n if (err) return callback(err);\n callback(undefined, result);\n }\n );\n });\n });\n });\n });\n });\n }\n}\nmodule.exports = GSSAPI;\n\nfunction saslStart(payload) {\n return {\n saslStart: 1,\n mechanism: 'GSSAPI',\n payload,\n autoAuthorize: 1\n };\n}\nfunction saslContinue(payload, conversationId) {\n return {\n saslContinue: 1,\n conversationId,\n payload\n };\n}\nfunction negotiate(client, retries, payload, callback) {\n client.step(payload, (err, response) => {\n // Retries exhausted, raise error\n if (err && retries === 0) return callback(err);\n // Adjust number of retries and call step again\n if (err) return negotiate(client, retries - 1, payload, callback);\n // Return the payload\n callback(undefined, response || '');\n });\n}\nfunction finalize(client, user, payload, callback) {\n // GSS Client Unwrap\n client.unwrap(payload, (err, response) => {\n if (err) return callback(err);\n // Wrap the response\n client.wrap(response || '', { user }, (err, wrapped) => {\n if (err) return callback(err);\n // Return the payload\n callback(undefined, wrapped);\n });\n });\n}\nfunction performGssapiCanonicalizeHostName(host, mechanismProperties, callback) {\n const canonicalizeHostName =\n typeof mechanismProperties.gssapiCanonicalizeHostName === 'boolean'\n ? mechanismProperties.gssapiCanonicalizeHostName\n : false;\n if (!canonicalizeHostName) return callback(undefined, host);\n // Attempt to resolve the host name\n dns.resolveCname(host, (err, r) => {\n if (err) return callback(err);\n // Get the first resolve host id\n if (Array.isArray(r) && r.length > 0) {\n return callback(undefined, r[0]);\n }\n callback(undefined, host);\n });\n}\n","'use strict';\n\n// Resolves the default auth mechanism according to\n// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst\nfunction getDefaultAuthMechanism(ismaster) {\n if (ismaster) {\n // If ismaster contains saslSupportedMechs, use scram-sha-256\n // if it is available, else scram-sha-1\n if (Array.isArray(ismaster.saslSupportedMechs)) {\n return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0\n ? 'scram-sha-256'\n : 'scram-sha-1';\n }\n\n // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1\n if (ismaster.maxWireVersion >= 3) {\n return 'scram-sha-1';\n }\n }\n\n // Default for wireprotocol < 3\n return 'mongocr';\n}\n\n/**\n * A representation of the credentials used by MongoDB\n * @class\n * @property {string} mechanism The method used to authenticate\n * @property {string} [username] The username used for authentication\n * @property {string} [password] The password used for authentication\n * @property {string} [source] The database that the user should authenticate against\n * @property {object} [mechanismProperties] Special properties used by some types of auth mechanisms\n */\nclass MongoCredentials {\n /**\n * Creates a new MongoCredentials object\n * @param {object} [options]\n * @param {string} [options.username] The username used for authentication\n * @param {string} [options.password] The password used for authentication\n * @param {string} [options.source] The database that the user should authenticate against\n * @param {string} [options.mechanism] The method used to authenticate\n * @param {object} [options.mechanismProperties] Special properties used by some types of auth mechanisms\n */\n constructor(options) {\n options = options || {};\n this.username = options.username;\n this.password = options.password;\n this.source = options.source || options.db;\n this.mechanism = options.mechanism || 'default';\n this.mechanismProperties = options.mechanismProperties || {};\n\n if (this.mechanism.match(/MONGODB-AWS/i)) {\n if (this.username == null && process.env.AWS_ACCESS_KEY_ID) {\n this.username = process.env.AWS_ACCESS_KEY_ID;\n }\n\n if (this.password == null && process.env.AWS_SECRET_ACCESS_KEY) {\n this.password = process.env.AWS_SECRET_ACCESS_KEY;\n }\n\n if (this.mechanismProperties.AWS_SESSION_TOKEN == null && process.env.AWS_SESSION_TOKEN) {\n this.mechanismProperties.AWS_SESSION_TOKEN = process.env.AWS_SESSION_TOKEN;\n }\n }\n\n Object.freeze(this.mechanismProperties);\n Object.freeze(this);\n }\n\n /**\n * Determines if two MongoCredentials objects are equivalent\n * @param {MongoCredentials} other another MongoCredentials object\n * @returns {boolean} true if the two objects are equal.\n */\n equals(other) {\n return (\n this.mechanism === other.mechanism &&\n this.username === other.username &&\n this.password === other.password &&\n this.source === other.source\n );\n }\n\n /**\n * If the authentication mechanism is set to \"default\", resolves the authMechanism\n * based on the server version and server supported sasl mechanisms.\n *\n * @param {Object} [ismaster] An ismaster response from the server\n * @returns {MongoCredentials}\n */\n resolveAuthMechanism(ismaster) {\n // If the mechanism is not \"default\", then it does not need to be resolved\n if (this.mechanism.match(/DEFAULT/i)) {\n return new MongoCredentials({\n username: this.username,\n password: this.password,\n source: this.source,\n mechanism: getDefaultAuthMechanism(ismaster),\n mechanismProperties: this.mechanismProperties\n });\n }\n\n return this;\n }\n}\n\nmodule.exports = { MongoCredentials };\n","'use strict';\n\nconst crypto = require('crypto');\nconst AuthProvider = require('./auth_provider').AuthProvider;\n\nclass MongoCR extends AuthProvider {\n auth(authContext, callback) {\n const connection = authContext.connection;\n const credentials = authContext.credentials;\n const username = credentials.username;\n const password = credentials.password;\n const source = credentials.source;\n\n connection.command(`${source}.$cmd`, { getnonce: 1 }, (err, result) => {\n let nonce = null;\n let key = null;\n\n // Get nonce\n if (err == null) {\n const r = result.result;\n nonce = r.nonce;\n // Use node md5 generator\n let md5 = crypto.createHash('md5');\n // Generate keys used for authentication\n md5.update(username + ':mongo:' + password, 'utf8');\n const hash_password = md5.digest('hex');\n // Final key\n md5 = crypto.createHash('md5');\n md5.update(nonce + username + hash_password, 'utf8');\n key = md5.digest('hex');\n }\n\n const authenticateCommand = {\n authenticate: 1,\n user: username,\n nonce,\n key\n };\n\n connection.command(`${source}.$cmd`, authenticateCommand, callback);\n });\n }\n}\n\nmodule.exports = MongoCR;\n","'use strict';\nconst AuthProvider = require('./auth_provider').AuthProvider;\nconst MongoCredentials = require('./mongo_credentials').MongoCredentials;\nconst MongoError = require('../error').MongoError;\nconst crypto = require('crypto');\nconst http = require('http');\nconst maxWireVersion = require('../utils').maxWireVersion;\nconst url = require('url');\n\nlet aws4;\ntry {\n aws4 = require('aws4');\n} catch (e) {\n // don't do anything;\n}\n\nconst ASCII_N = 110;\nconst AWS_RELATIVE_URI = 'http://169.254.170.2';\nconst AWS_EC2_URI = 'http://169.254.169.254';\nconst AWS_EC2_PATH = '/latest/meta-data/iam/security-credentials';\n\nclass MongoDBAWS extends AuthProvider {\n auth(authContext, callback) {\n const connection = authContext.connection;\n const credentials = authContext.credentials;\n\n if (maxWireVersion(connection) < 9) {\n callback(new MongoError('MONGODB-AWS authentication requires MongoDB version 4.4 or later'));\n return;\n }\n\n if (aws4 == null) {\n callback(\n new MongoError(\n 'MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project'\n )\n );\n\n return;\n }\n\n if (credentials.username == null) {\n makeTempCredentials(credentials, (err, tempCredentials) => {\n if (err) return callback(err);\n\n authContext.credentials = tempCredentials;\n this.auth(authContext, callback);\n });\n\n return;\n }\n\n const username = credentials.username;\n const password = credentials.password;\n const db = credentials.source;\n const token = credentials.mechanismProperties.AWS_SESSION_TOKEN;\n const bson = this.bson;\n\n crypto.randomBytes(32, (err, nonce) => {\n if (err) {\n callback(err);\n return;\n }\n\n const saslStart = {\n saslStart: 1,\n mechanism: 'MONGODB-AWS',\n payload: bson.serialize({ r: nonce, p: ASCII_N })\n };\n\n connection.command(`${db}.$cmd`, saslStart, (err, result) => {\n if (err) return callback(err);\n\n const res = result.result;\n const serverResponse = bson.deserialize(res.payload.buffer);\n const host = serverResponse.h;\n const serverNonce = serverResponse.s.buffer;\n if (serverNonce.length !== 64) {\n callback(\n new MongoError(`Invalid server nonce length ${serverNonce.length}, expected 64`)\n );\n return;\n }\n\n if (serverNonce.compare(nonce, 0, nonce.length, 0, nonce.length) !== 0) {\n callback(new MongoError('Server nonce does not begin with client nonce'));\n return;\n }\n\n if (host.length < 1 || host.length > 255 || host.indexOf('..') !== -1) {\n callback(new MongoError(`Server returned an invalid host: \"${host}\"`));\n return;\n }\n\n const body = 'Action=GetCallerIdentity&Version=2011-06-15';\n const options = aws4.sign(\n {\n method: 'POST',\n host,\n region: deriveRegion(serverResponse.h),\n service: 'sts',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Content-Length': body.length,\n 'X-MongoDB-Server-Nonce': serverNonce.toString('base64'),\n 'X-MongoDB-GS2-CB-Flag': 'n'\n },\n path: '/',\n body\n },\n {\n accessKeyId: username,\n secretAccessKey: password,\n token\n }\n );\n\n const authorization = options.headers.Authorization;\n const date = options.headers['X-Amz-Date'];\n const payload = { a: authorization, d: date };\n if (token) {\n payload.t = token;\n }\n\n const saslContinue = {\n saslContinue: 1,\n conversationId: 1,\n payload: bson.serialize(payload)\n };\n\n connection.command(`${db}.$cmd`, saslContinue, err => {\n if (err) return callback(err);\n callback();\n });\n });\n });\n }\n}\n\nfunction makeTempCredentials(credentials, callback) {\n function done(creds) {\n if (creds.AccessKeyId == null || creds.SecretAccessKey == null || creds.Token == null) {\n callback(new MongoError('Could not obtain temporary MONGODB-AWS credentials'));\n return;\n }\n\n callback(\n undefined,\n new MongoCredentials({\n username: creds.AccessKeyId,\n password: creds.SecretAccessKey,\n source: credentials.source,\n mechanism: 'MONGODB-AWS',\n mechanismProperties: {\n AWS_SESSION_TOKEN: creds.Token\n }\n })\n );\n }\n\n // If the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\n // is set then drivers MUST assume that it was set by an AWS ECS agent\n if (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) {\n request(\n `${AWS_RELATIVE_URI}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`,\n (err, res) => {\n if (err) return callback(err);\n done(res);\n }\n );\n\n return;\n }\n\n // Otherwise assume we are on an EC2 instance\n\n // get a token\n\n request(\n `${AWS_EC2_URI}/latest/api/token`,\n { method: 'PUT', json: false, headers: { 'X-aws-ec2-metadata-token-ttl-seconds': 30 } },\n (err, token) => {\n if (err) return callback(err);\n\n // get role name\n request(\n `${AWS_EC2_URI}/${AWS_EC2_PATH}`,\n { json: false, headers: { 'X-aws-ec2-metadata-token': token } },\n (err, roleName) => {\n if (err) return callback(err);\n\n // get temp credentials\n request(\n `${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`,\n { headers: { 'X-aws-ec2-metadata-token': token } },\n (err, creds) => {\n if (err) return callback(err);\n done(creds);\n }\n );\n }\n );\n }\n );\n}\n\nfunction deriveRegion(host) {\n const parts = host.split('.');\n if (parts.length === 1 || parts[1] === 'amazonaws') {\n return 'us-east-1';\n }\n\n return parts[1];\n}\n\nfunction request(uri, options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n options = Object.assign(\n {\n method: 'GET',\n timeout: 10000,\n json: true\n },\n url.parse(uri),\n options\n );\n\n const req = http.request(options, res => {\n res.setEncoding('utf8');\n\n let data = '';\n res.on('data', d => (data += d));\n res.on('end', () => {\n if (options.json === false) {\n callback(undefined, data);\n return;\n }\n\n try {\n const parsed = JSON.parse(data);\n callback(undefined, parsed);\n } catch (err) {\n callback(new MongoError(`Invalid JSON response: \"${data}\"`));\n }\n });\n });\n\n req.on('error', err => callback(err));\n req.end();\n}\n\nmodule.exports = MongoDBAWS;\n","'use strict';\nconst retrieveBSON = require('../connection/utils').retrieveBSON;\nconst AuthProvider = require('./auth_provider').AuthProvider;\n\n// TODO: can we get the Binary type from this.bson instead?\nconst BSON = retrieveBSON();\nconst Binary = BSON.Binary;\n\nclass Plain extends AuthProvider {\n auth(authContext, callback) {\n const connection = authContext.connection;\n const credentials = authContext.credentials;\n const username = credentials.username;\n const password = credentials.password;\n\n const payload = new Binary(`\\x00${username}\\x00${password}`);\n const command = {\n saslStart: 1,\n mechanism: 'PLAIN',\n payload: payload,\n autoAuthorize: 1\n };\n\n connection.command('$external.$cmd', command, callback);\n }\n}\n\nmodule.exports = Plain;\n","'use strict';\nconst crypto = require('crypto');\nconst Buffer = require('safe-buffer').Buffer;\nconst retrieveBSON = require('../connection/utils').retrieveBSON;\nconst MongoError = require('../error').MongoError;\nconst AuthProvider = require('./auth_provider').AuthProvider;\n\nconst BSON = retrieveBSON();\nconst Binary = BSON.Binary;\n\nlet saslprep;\ntry {\n saslprep = require('saslprep');\n} catch (e) {\n // don't do anything;\n}\n\nclass ScramSHA extends AuthProvider {\n constructor(bson, cryptoMethod) {\n super(bson);\n this.cryptoMethod = cryptoMethod || 'sha1';\n }\n\n prepare(handshakeDoc, authContext, callback) {\n const cryptoMethod = this.cryptoMethod;\n if (cryptoMethod === 'sha256' && saslprep == null) {\n console.warn('Warning: no saslprep library specified. Passwords will not be sanitized');\n }\n\n crypto.randomBytes(24, (err, nonce) => {\n if (err) {\n return callback(err);\n }\n\n // store the nonce for later use\n Object.assign(authContext, { nonce });\n\n const credentials = authContext.credentials;\n const request = Object.assign({}, handshakeDoc, {\n speculativeAuthenticate: Object.assign(makeFirstMessage(cryptoMethod, credentials, nonce), {\n db: credentials.source\n })\n });\n\n callback(undefined, request);\n });\n }\n\n auth(authContext, callback) {\n const response = authContext.response;\n if (response && response.speculativeAuthenticate) {\n continueScramConversation(\n this.cryptoMethod,\n response.speculativeAuthenticate,\n authContext,\n callback\n );\n\n return;\n }\n\n executeScram(this.cryptoMethod, authContext, callback);\n }\n}\n\nfunction cleanUsername(username) {\n return username.replace('=', '=3D').replace(',', '=2C');\n}\n\nfunction clientFirstMessageBare(username, nonce) {\n // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8.\n // Since the username is not sasl-prep-d, we need to do this here.\n return Buffer.concat([\n Buffer.from('n=', 'utf8'),\n Buffer.from(username, 'utf8'),\n Buffer.from(',r=', 'utf8'),\n Buffer.from(nonce.toString('base64'), 'utf8')\n ]);\n}\n\nfunction makeFirstMessage(cryptoMethod, credentials, nonce) {\n const username = cleanUsername(credentials.username);\n const mechanism = cryptoMethod === 'sha1' ? 'SCRAM-SHA-1' : 'SCRAM-SHA-256';\n\n // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8.\n // Since the username is not sasl-prep-d, we need to do this here.\n return {\n saslStart: 1,\n mechanism,\n payload: new Binary(\n Buffer.concat([Buffer.from('n,,', 'utf8'), clientFirstMessageBare(username, nonce)])\n ),\n autoAuthorize: 1,\n options: { skipEmptyExchange: true }\n };\n}\n\nfunction executeScram(cryptoMethod, authContext, callback) {\n const connection = authContext.connection;\n const credentials = authContext.credentials;\n const nonce = authContext.nonce;\n const db = credentials.source;\n\n const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce);\n connection.command(`${db}.$cmd`, saslStartCmd, (_err, result) => {\n const err = resolveError(_err, result);\n if (err) {\n return callback(err);\n }\n\n continueScramConversation(cryptoMethod, result.result, authContext, callback);\n });\n}\n\nfunction continueScramConversation(cryptoMethod, response, authContext, callback) {\n const connection = authContext.connection;\n const credentials = authContext.credentials;\n const nonce = authContext.nonce;\n\n const db = credentials.source;\n const username = cleanUsername(credentials.username);\n const password = credentials.password;\n\n let processedPassword;\n if (cryptoMethod === 'sha256') {\n processedPassword = saslprep ? saslprep(password) : password;\n } else {\n try {\n processedPassword = passwordDigest(username, password);\n } catch (e) {\n return callback(e);\n }\n }\n\n const payload = Buffer.isBuffer(response.payload)\n ? new Binary(response.payload)\n : response.payload;\n const dict = parsePayload(payload.value());\n\n const iterations = parseInt(dict.i, 10);\n if (iterations && iterations < 4096) {\n callback(new MongoError(`Server returned an invalid iteration count ${iterations}`), false);\n return;\n }\n\n const salt = dict.s;\n const rnonce = dict.r;\n if (rnonce.startsWith('nonce')) {\n callback(new MongoError(`Server returned an invalid nonce: ${rnonce}`), false);\n return;\n }\n\n // Set up start of proof\n const withoutProof = `c=biws,r=${rnonce}`;\n const saltedPassword = HI(\n processedPassword,\n Buffer.from(salt, 'base64'),\n iterations,\n cryptoMethod\n );\n\n const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key');\n const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key');\n const storedKey = H(cryptoMethod, clientKey);\n const authMessage = [\n clientFirstMessageBare(username, nonce),\n payload.value().toString('base64'),\n withoutProof\n ].join(',');\n\n const clientSignature = HMAC(cryptoMethod, storedKey, authMessage);\n const clientProof = `p=${xor(clientKey, clientSignature)}`;\n const clientFinal = [withoutProof, clientProof].join(',');\n\n const serverSignature = HMAC(cryptoMethod, serverKey, authMessage);\n const saslContinueCmd = {\n saslContinue: 1,\n conversationId: response.conversationId,\n payload: new Binary(Buffer.from(clientFinal))\n };\n\n connection.command(`${db}.$cmd`, saslContinueCmd, (_err, result) => {\n const err = resolveError(_err, result);\n if (err) {\n return callback(err);\n }\n\n const r = result.result;\n const parsedResponse = parsePayload(r.payload.value());\n if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) {\n callback(new MongoError('Server returned an invalid signature'));\n return;\n }\n\n if (!r || r.done !== false) {\n return callback(err, r);\n }\n\n const retrySaslContinueCmd = {\n saslContinue: 1,\n conversationId: r.conversationId,\n payload: Buffer.alloc(0)\n };\n\n connection.command(`${db}.$cmd`, retrySaslContinueCmd, callback);\n });\n}\n\nfunction parsePayload(payload) {\n const dict = {};\n const parts = payload.split(',');\n for (let i = 0; i < parts.length; i++) {\n const valueParts = parts[i].split('=');\n dict[valueParts[0]] = valueParts[1];\n }\n\n return dict;\n}\n\nfunction passwordDigest(username, password) {\n if (typeof username !== 'string') {\n throw new MongoError('username must be a string');\n }\n\n if (typeof password !== 'string') {\n throw new MongoError('password must be a string');\n }\n\n if (password.length === 0) {\n throw new MongoError('password cannot be empty');\n }\n\n const md5 = crypto.createHash('md5');\n md5.update(`${username}:mongo:${password}`, 'utf8');\n return md5.digest('hex');\n}\n\n// XOR two buffers\nfunction xor(a, b) {\n if (!Buffer.isBuffer(a)) {\n a = Buffer.from(a);\n }\n\n if (!Buffer.isBuffer(b)) {\n b = Buffer.from(b);\n }\n\n const length = Math.max(a.length, b.length);\n const res = [];\n\n for (let i = 0; i < length; i += 1) {\n res.push(a[i] ^ b[i]);\n }\n\n return Buffer.from(res).toString('base64');\n}\n\nfunction H(method, text) {\n return crypto\n .createHash(method)\n .update(text)\n .digest();\n}\n\nfunction HMAC(method, key, text) {\n return crypto\n .createHmac(method, key)\n .update(text)\n .digest();\n}\n\nlet _hiCache = {};\nlet _hiCacheCount = 0;\nfunction _hiCachePurge() {\n _hiCache = {};\n _hiCacheCount = 0;\n}\n\nconst hiLengthMap = {\n sha256: 32,\n sha1: 20\n};\n\nfunction HI(data, salt, iterations, cryptoMethod) {\n // omit the work if already generated\n const key = [data, salt.toString('base64'), iterations].join('_');\n if (_hiCache[key] !== undefined) {\n return _hiCache[key];\n }\n\n // generate the salt\n const saltedData = crypto.pbkdf2Sync(\n data,\n salt,\n iterations,\n hiLengthMap[cryptoMethod],\n cryptoMethod\n );\n\n // cache a copy to speed up the next lookup, but prevent unbounded cache growth\n if (_hiCacheCount >= 200) {\n _hiCachePurge();\n }\n\n _hiCache[key] = saltedData;\n _hiCacheCount += 1;\n return saltedData;\n}\n\nfunction compareDigest(lhs, rhs) {\n if (lhs.length !== rhs.length) {\n return false;\n }\n\n if (typeof crypto.timingSafeEqual === 'function') {\n return crypto.timingSafeEqual(lhs, rhs);\n }\n\n let result = 0;\n for (let i = 0; i < lhs.length; i++) {\n result |= lhs[i] ^ rhs[i];\n }\n\n return result === 0;\n}\n\nfunction resolveError(err, result) {\n if (err) return err;\n\n const r = result.result;\n if (r.$err || r.errmsg) return new MongoError(r);\n}\n\nclass ScramSHA1 extends ScramSHA {\n constructor(bson) {\n super(bson, 'sha1');\n }\n}\n\nclass ScramSHA256 extends ScramSHA {\n constructor(bson) {\n super(bson, 'sha256');\n }\n}\n\nmodule.exports = { ScramSHA1, ScramSHA256 };\n","'use strict';\nconst AuthProvider = require('./auth_provider').AuthProvider;\n\nclass X509 extends AuthProvider {\n prepare(handshakeDoc, authContext, callback) {\n const credentials = authContext.credentials;\n Object.assign(handshakeDoc, {\n speculativeAuthenticate: x509AuthenticateCommand(credentials)\n });\n\n callback(undefined, handshakeDoc);\n }\n\n auth(authContext, callback) {\n const connection = authContext.connection;\n const credentials = authContext.credentials;\n const response = authContext.response;\n if (response.speculativeAuthenticate) {\n return callback();\n }\n\n connection.command('$external.$cmd', x509AuthenticateCommand(credentials), callback);\n }\n}\n\nfunction x509AuthenticateCommand(credentials) {\n const command = { authenticate: 1, mechanism: 'MONGODB-X509' };\n if (credentials.username) {\n Object.apply(command, { user: credentials.username });\n }\n\n return command;\n}\n\nmodule.exports = X509;\n","'use strict';\nconst Msg = require('../connection/msg').Msg;\nconst KillCursor = require('../connection/commands').KillCursor;\nconst GetMore = require('../connection/commands').GetMore;\nconst calculateDurationInMs = require('../../utils').calculateDurationInMs;\n\n/** Commands that we want to redact because of the sensitive nature of their contents */\nconst SENSITIVE_COMMANDS = new Set([\n 'authenticate',\n 'saslStart',\n 'saslContinue',\n 'getnonce',\n 'createUser',\n 'updateUser',\n 'copydbgetnonce',\n 'copydbsaslstart',\n 'copydb'\n]);\n\n// helper methods\nconst extractCommandName = commandDoc => Object.keys(commandDoc)[0];\nconst namespace = command => command.ns;\nconst databaseName = command => command.ns.split('.')[0];\nconst collectionName = command => command.ns.split('.')[1];\nconst generateConnectionId = pool =>\n pool.options ? `${pool.options.host}:${pool.options.port}` : pool.address;\nconst maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result);\nconst isLegacyPool = pool => pool.s && pool.queue;\n\nconst LEGACY_FIND_QUERY_MAP = {\n $query: 'filter',\n $orderby: 'sort',\n $hint: 'hint',\n $comment: 'comment',\n $maxScan: 'maxScan',\n $max: 'max',\n $min: 'min',\n $returnKey: 'returnKey',\n $showDiskLoc: 'showRecordId',\n $maxTimeMS: 'maxTimeMS',\n $snapshot: 'snapshot'\n};\n\nconst LEGACY_FIND_OPTIONS_MAP = {\n numberToSkip: 'skip',\n numberToReturn: 'batchSize',\n returnFieldsSelector: 'projection'\n};\n\nconst OP_QUERY_KEYS = [\n 'tailable',\n 'oplogReplay',\n 'noCursorTimeout',\n 'awaitData',\n 'partial',\n 'exhaust'\n];\n\n/**\n * Extract the actual command from the query, possibly upconverting if it's a legacy\n * format\n *\n * @param {Object} command the command\n */\nconst extractCommand = command => {\n if (command instanceof GetMore) {\n return {\n getMore: command.cursorId,\n collection: collectionName(command),\n batchSize: command.numberToReturn\n };\n }\n\n if (command instanceof KillCursor) {\n return {\n killCursors: collectionName(command),\n cursors: command.cursorIds\n };\n }\n\n if (command instanceof Msg) {\n return command.command;\n }\n\n if (command.query && command.query.$query) {\n let result;\n if (command.ns === 'admin.$cmd') {\n // upconvert legacy command\n result = Object.assign({}, command.query.$query);\n } else {\n // upconvert legacy find command\n result = { find: collectionName(command) };\n Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => {\n if (typeof command.query[key] !== 'undefined')\n result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key];\n });\n }\n\n Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => {\n if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key];\n });\n\n OP_QUERY_KEYS.forEach(key => {\n if (command[key]) result[key] = command[key];\n });\n\n if (typeof command.pre32Limit !== 'undefined') {\n result.limit = command.pre32Limit;\n }\n\n if (command.query.$explain) {\n return { explain: result };\n }\n\n return result;\n }\n\n return command.query ? command.query : command;\n};\n\nconst extractReply = (command, reply) => {\n if (command instanceof GetMore) {\n return {\n ok: 1,\n cursor: {\n id: reply.message.cursorId,\n ns: namespace(command),\n nextBatch: reply.message.documents\n }\n };\n }\n\n if (command instanceof KillCursor) {\n return {\n ok: 1,\n cursorsUnknown: command.cursorIds\n };\n }\n\n // is this a legacy find command?\n if (command.query && typeof command.query.$query !== 'undefined') {\n return {\n ok: 1,\n cursor: {\n id: reply.message.cursorId,\n ns: namespace(command),\n firstBatch: reply.message.documents\n }\n };\n }\n\n return reply && reply.result ? reply.result : reply;\n};\n\nconst extractConnectionDetails = pool => {\n if (isLegacyPool(pool)) {\n return {\n connectionId: generateConnectionId(pool)\n };\n }\n\n // APM in the modern pool is done at the `Connection` level, so we rename it here for\n // readability.\n const connection = pool;\n return {\n address: connection.address,\n connectionId: connection.id\n };\n};\n\n/** An event indicating the start of a given command */\nclass CommandStartedEvent {\n /**\n * Create a started event\n *\n * @param {Pool} pool the pool that originated the command\n * @param {Object} command the command\n */\n constructor(pool, command) {\n const cmd = extractCommand(command);\n const commandName = extractCommandName(cmd);\n const connectionDetails = extractConnectionDetails(pool);\n\n // NOTE: remove in major revision, this is not spec behavior\n if (SENSITIVE_COMMANDS.has(commandName)) {\n this.commandObj = {};\n this.commandObj[commandName] = true;\n }\n\n Object.assign(this, connectionDetails, {\n requestId: command.requestId,\n databaseName: databaseName(command),\n commandName,\n command: cmd\n });\n }\n}\n\n/** An event indicating the success of a given command */\nclass CommandSucceededEvent {\n /**\n * Create a succeeded event\n *\n * @param {Pool} pool the pool that originated the command\n * @param {Object} command the command\n * @param {Object} reply the reply for this command from the server\n * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration\n */\n constructor(pool, command, reply, started) {\n const cmd = extractCommand(command);\n const commandName = extractCommandName(cmd);\n const connectionDetails = extractConnectionDetails(pool);\n\n Object.assign(this, connectionDetails, {\n requestId: command.requestId,\n commandName,\n duration: calculateDurationInMs(started),\n reply: maybeRedact(commandName, extractReply(command, reply))\n });\n }\n}\n\n/** An event indicating the failure of a given command */\nclass CommandFailedEvent {\n /**\n * Create a failure event\n *\n * @param {Pool} pool the pool that originated the command\n * @param {Object} command the command\n * @param {MongoError|Object} error the generated error or a server error response\n * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration\n */\n constructor(pool, command, error, started) {\n const cmd = extractCommand(command);\n const commandName = extractCommandName(cmd);\n const connectionDetails = extractConnectionDetails(pool);\n\n Object.assign(this, connectionDetails, {\n requestId: command.requestId,\n commandName,\n duration: calculateDurationInMs(started),\n failure: maybeRedact(commandName, error)\n });\n }\n}\n\nmodule.exports = {\n CommandStartedEvent,\n CommandSucceededEvent,\n CommandFailedEvent\n};\n","'use strict';\n\n/**\n * Creates a new CommandResult instance\n * @class\n * @param {object} result CommandResult object\n * @param {Connection} connection A connection instance associated with this result\n * @return {CommandResult} A cursor instance\n */\nvar CommandResult = function(result, connection, message) {\n this.result = result;\n this.connection = connection;\n this.message = message;\n};\n\n/**\n * Convert CommandResult to JSON\n * @method\n * @return {object}\n */\nCommandResult.prototype.toJSON = function() {\n let result = Object.assign({}, this, this.result);\n delete result.message;\n return result;\n};\n\n/**\n * Convert CommandResult to String representation\n * @method\n * @return {string}\n */\nCommandResult.prototype.toString = function() {\n return JSON.stringify(this.toJSON());\n};\n\nmodule.exports = CommandResult;\n","'use strict';\n\nvar retrieveBSON = require('./utils').retrieveBSON;\nvar BSON = retrieveBSON();\nvar Long = BSON.Long;\nconst Buffer = require('safe-buffer').Buffer;\n\n// Incrementing request id\nvar _requestId = 0;\n\n// Wire command operation ids\nvar opcodes = require('../wireprotocol/shared').opcodes;\n\n// Query flags\nvar OPTS_TAILABLE_CURSOR = 2;\nvar OPTS_SLAVE = 4;\nvar OPTS_OPLOG_REPLAY = 8;\nvar OPTS_NO_CURSOR_TIMEOUT = 16;\nvar OPTS_AWAIT_DATA = 32;\nvar OPTS_EXHAUST = 64;\nvar OPTS_PARTIAL = 128;\n\n// Response flags\nvar CURSOR_NOT_FOUND = 1;\nvar QUERY_FAILURE = 2;\nvar SHARD_CONFIG_STALE = 4;\nvar AWAIT_CAPABLE = 8;\n\n/**************************************************************\n * QUERY\n **************************************************************/\nvar Query = function(bson, ns, query, options) {\n var self = this;\n // Basic options needed to be passed in\n if (ns == null) throw new Error('ns must be specified for query');\n if (query == null) throw new Error('query must be specified for query');\n\n // Validate that we are not passing 0x00 in the collection name\n if (ns.indexOf('\\x00') !== -1) {\n throw new Error('namespace cannot contain a null character');\n }\n\n // Basic options\n this.bson = bson;\n this.ns = ns;\n this.query = query;\n\n // Additional options\n this.numberToSkip = options.numberToSkip || 0;\n this.numberToReturn = options.numberToReturn || 0;\n this.returnFieldSelector = options.returnFieldSelector || null;\n this.requestId = Query.getRequestId();\n\n // special case for pre-3.2 find commands, delete ASAP\n this.pre32Limit = options.pre32Limit;\n\n // Serialization option\n this.serializeFunctions =\n typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;\n this.ignoreUndefined =\n typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false;\n this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16;\n this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true;\n this.batchSize = self.numberToReturn;\n\n // Flags\n this.tailable = false;\n this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false;\n this.oplogReplay = false;\n this.noCursorTimeout = false;\n this.awaitData = false;\n this.exhaust = false;\n this.partial = false;\n};\n\n//\n// Assign a new request Id\nQuery.prototype.incRequestId = function() {\n this.requestId = _requestId++;\n};\n\n//\n// Assign a new request Id\nQuery.nextRequestId = function() {\n return _requestId + 1;\n};\n\n//\n// Uses a single allocated buffer for the process, avoiding multiple memory allocations\nQuery.prototype.toBin = function() {\n var self = this;\n var buffers = [];\n var projection = null;\n\n // Set up the flags\n var flags = 0;\n if (this.tailable) {\n flags |= OPTS_TAILABLE_CURSOR;\n }\n\n if (this.slaveOk) {\n flags |= OPTS_SLAVE;\n }\n\n if (this.oplogReplay) {\n flags |= OPTS_OPLOG_REPLAY;\n }\n\n if (this.noCursorTimeout) {\n flags |= OPTS_NO_CURSOR_TIMEOUT;\n }\n\n if (this.awaitData) {\n flags |= OPTS_AWAIT_DATA;\n }\n\n if (this.exhaust) {\n flags |= OPTS_EXHAUST;\n }\n\n if (this.partial) {\n flags |= OPTS_PARTIAL;\n }\n\n // If batchSize is different to self.numberToReturn\n if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize;\n\n // Allocate write protocol header buffer\n var header = Buffer.alloc(\n 4 * 4 + // Header\n 4 + // Flags\n Buffer.byteLength(self.ns) +\n 1 + // namespace\n 4 + // numberToSkip\n 4 // numberToReturn\n );\n\n // Add header to buffers\n buffers.push(header);\n\n // Serialize the query\n var query = self.bson.serialize(this.query, {\n checkKeys: this.checkKeys,\n serializeFunctions: this.serializeFunctions,\n ignoreUndefined: this.ignoreUndefined\n });\n\n // Add query document\n buffers.push(query);\n\n if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) {\n // Serialize the projection document\n projection = self.bson.serialize(this.returnFieldSelector, {\n checkKeys: this.checkKeys,\n serializeFunctions: this.serializeFunctions,\n ignoreUndefined: this.ignoreUndefined\n });\n // Add projection document\n buffers.push(projection);\n }\n\n // Total message size\n var totalLength = header.length + query.length + (projection ? projection.length : 0);\n\n // Set up the index\n var index = 4;\n\n // Write total document length\n header[3] = (totalLength >> 24) & 0xff;\n header[2] = (totalLength >> 16) & 0xff;\n header[1] = (totalLength >> 8) & 0xff;\n header[0] = totalLength & 0xff;\n\n // Write header information requestId\n header[index + 3] = (this.requestId >> 24) & 0xff;\n header[index + 2] = (this.requestId >> 16) & 0xff;\n header[index + 1] = (this.requestId >> 8) & 0xff;\n header[index] = this.requestId & 0xff;\n index = index + 4;\n\n // Write header information responseTo\n header[index + 3] = (0 >> 24) & 0xff;\n header[index + 2] = (0 >> 16) & 0xff;\n header[index + 1] = (0 >> 8) & 0xff;\n header[index] = 0 & 0xff;\n index = index + 4;\n\n // Write header information OP_QUERY\n header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff;\n header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff;\n header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff;\n header[index] = opcodes.OP_QUERY & 0xff;\n index = index + 4;\n\n // Write header information flags\n header[index + 3] = (flags >> 24) & 0xff;\n header[index + 2] = (flags >> 16) & 0xff;\n header[index + 1] = (flags >> 8) & 0xff;\n header[index] = flags & 0xff;\n index = index + 4;\n\n // Write collection name\n index = index + header.write(this.ns, index, 'utf8') + 1;\n header[index - 1] = 0;\n\n // Write header information flags numberToSkip\n header[index + 3] = (this.numberToSkip >> 24) & 0xff;\n header[index + 2] = (this.numberToSkip >> 16) & 0xff;\n header[index + 1] = (this.numberToSkip >> 8) & 0xff;\n header[index] = this.numberToSkip & 0xff;\n index = index + 4;\n\n // Write header information flags numberToReturn\n header[index + 3] = (this.numberToReturn >> 24) & 0xff;\n header[index + 2] = (this.numberToReturn >> 16) & 0xff;\n header[index + 1] = (this.numberToReturn >> 8) & 0xff;\n header[index] = this.numberToReturn & 0xff;\n index = index + 4;\n\n // Return the buffers\n return buffers;\n};\n\nQuery.getRequestId = function() {\n return ++_requestId;\n};\n\n/**************************************************************\n * GETMORE\n **************************************************************/\nvar GetMore = function(bson, ns, cursorId, opts) {\n opts = opts || {};\n this.numberToReturn = opts.numberToReturn || 0;\n this.requestId = _requestId++;\n this.bson = bson;\n this.ns = ns;\n this.cursorId = cursorId;\n};\n\n//\n// Uses a single allocated buffer for the process, avoiding multiple memory allocations\nGetMore.prototype.toBin = function() {\n var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4;\n // Create command buffer\n var index = 0;\n // Allocate buffer\n var _buffer = Buffer.alloc(length);\n\n // Write header information\n // index = write32bit(index, _buffer, length);\n _buffer[index + 3] = (length >> 24) & 0xff;\n _buffer[index + 2] = (length >> 16) & 0xff;\n _buffer[index + 1] = (length >> 8) & 0xff;\n _buffer[index] = length & 0xff;\n index = index + 4;\n\n // index = write32bit(index, _buffer, requestId);\n _buffer[index + 3] = (this.requestId >> 24) & 0xff;\n _buffer[index + 2] = (this.requestId >> 16) & 0xff;\n _buffer[index + 1] = (this.requestId >> 8) & 0xff;\n _buffer[index] = this.requestId & 0xff;\n index = index + 4;\n\n // index = write32bit(index, _buffer, 0);\n _buffer[index + 3] = (0 >> 24) & 0xff;\n _buffer[index + 2] = (0 >> 16) & 0xff;\n _buffer[index + 1] = (0 >> 8) & 0xff;\n _buffer[index] = 0 & 0xff;\n index = index + 4;\n\n // index = write32bit(index, _buffer, OP_GETMORE);\n _buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff;\n _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff;\n _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff;\n _buffer[index] = opcodes.OP_GETMORE & 0xff;\n index = index + 4;\n\n // index = write32bit(index, _buffer, 0);\n _buffer[index + 3] = (0 >> 24) & 0xff;\n _buffer[index + 2] = (0 >> 16) & 0xff;\n _buffer[index + 1] = (0 >> 8) & 0xff;\n _buffer[index] = 0 & 0xff;\n index = index + 4;\n\n // Write collection name\n index = index + _buffer.write(this.ns, index, 'utf8') + 1;\n _buffer[index - 1] = 0;\n\n // Write batch size\n // index = write32bit(index, _buffer, numberToReturn);\n _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff;\n _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff;\n _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff;\n _buffer[index] = this.numberToReturn & 0xff;\n index = index + 4;\n\n // Write cursor id\n // index = write32bit(index, _buffer, cursorId.getLowBits());\n _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff;\n _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff;\n _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff;\n _buffer[index] = this.cursorId.getLowBits() & 0xff;\n index = index + 4;\n\n // index = write32bit(index, _buffer, cursorId.getHighBits());\n _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff;\n _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff;\n _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff;\n _buffer[index] = this.cursorId.getHighBits() & 0xff;\n index = index + 4;\n\n // Return buffer\n return _buffer;\n};\n\n/**************************************************************\n * KILLCURSOR\n **************************************************************/\nvar KillCursor = function(bson, ns, cursorIds) {\n this.ns = ns;\n this.requestId = _requestId++;\n this.cursorIds = cursorIds;\n};\n\n//\n// Uses a single allocated buffer for the process, avoiding multiple memory allocations\nKillCursor.prototype.toBin = function() {\n var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8;\n\n // Create command buffer\n var index = 0;\n var _buffer = Buffer.alloc(length);\n\n // Write header information\n // index = write32bit(index, _buffer, length);\n _buffer[index + 3] = (length >> 24) & 0xff;\n _buffer[index + 2] = (length >> 16) & 0xff;\n _buffer[index + 1] = (length >> 8) & 0xff;\n _buffer[index] = length & 0xff;\n index = index + 4;\n\n // index = write32bit(index, _buffer, requestId);\n _buffer[index + 3] = (this.requestId >> 24) & 0xff;\n _buffer[index + 2] = (this.requestId >> 16) & 0xff;\n _buffer[index + 1] = (this.requestId >> 8) & 0xff;\n _buffer[index] = this.requestId & 0xff;\n index = index + 4;\n\n // index = write32bit(index, _buffer, 0);\n _buffer[index + 3] = (0 >> 24) & 0xff;\n _buffer[index + 2] = (0 >> 16) & 0xff;\n _buffer[index + 1] = (0 >> 8) & 0xff;\n _buffer[index] = 0 & 0xff;\n index = index + 4;\n\n // index = write32bit(index, _buffer, OP_KILL_CURSORS);\n _buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff;\n _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff;\n _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff;\n _buffer[index] = opcodes.OP_KILL_CURSORS & 0xff;\n index = index + 4;\n\n // index = write32bit(index, _buffer, 0);\n _buffer[index + 3] = (0 >> 24) & 0xff;\n _buffer[index + 2] = (0 >> 16) & 0xff;\n _buffer[index + 1] = (0 >> 8) & 0xff;\n _buffer[index] = 0 & 0xff;\n index = index + 4;\n\n // Write batch size\n // index = write32bit(index, _buffer, this.cursorIds.length);\n _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff;\n _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff;\n _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff;\n _buffer[index] = this.cursorIds.length & 0xff;\n index = index + 4;\n\n // Write all the cursor ids into the array\n for (var i = 0; i < this.cursorIds.length; i++) {\n // Write cursor id\n // index = write32bit(index, _buffer, cursorIds[i].getLowBits());\n _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff;\n _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff;\n _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff;\n _buffer[index] = this.cursorIds[i].getLowBits() & 0xff;\n index = index + 4;\n\n // index = write32bit(index, _buffer, cursorIds[i].getHighBits());\n _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff;\n _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff;\n _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff;\n _buffer[index] = this.cursorIds[i].getHighBits() & 0xff;\n index = index + 4;\n }\n\n // Return buffer\n return _buffer;\n};\n\nvar Response = function(bson, message, msgHeader, msgBody, opts) {\n opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false };\n this.parsed = false;\n this.raw = message;\n this.data = msgBody;\n this.bson = bson;\n this.opts = opts;\n\n // Read the message header\n this.length = msgHeader.length;\n this.requestId = msgHeader.requestId;\n this.responseTo = msgHeader.responseTo;\n this.opCode = msgHeader.opCode;\n this.fromCompressed = msgHeader.fromCompressed;\n\n // Read the message body\n this.responseFlags = msgBody.readInt32LE(0);\n this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8));\n this.startingFrom = msgBody.readInt32LE(12);\n this.numberReturned = msgBody.readInt32LE(16);\n\n // Preallocate document array\n this.documents = new Array(this.numberReturned);\n\n // Flag values\n this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0;\n this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0;\n this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0;\n this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0;\n this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true;\n this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true;\n this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false;\n};\n\nResponse.prototype.isParsed = function() {\n return this.parsed;\n};\n\nResponse.prototype.parse = function(options) {\n // Don't parse again if not needed\n if (this.parsed) return;\n options = options || {};\n\n // Allow the return of raw documents instead of parsing\n var raw = options.raw || false;\n var documentsReturnedIn = options.documentsReturnedIn || null;\n var promoteLongs =\n typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs;\n var promoteValues =\n typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues;\n var promoteBuffers =\n typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers;\n var bsonSize, _options;\n\n // Set up the options\n _options = {\n promoteLongs: promoteLongs,\n promoteValues: promoteValues,\n promoteBuffers: promoteBuffers\n };\n\n // Position within OP_REPLY at which documents start\n // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply)\n this.index = 20;\n\n //\n // Parse Body\n //\n for (var i = 0; i < this.numberReturned; i++) {\n bsonSize =\n this.data[this.index] |\n (this.data[this.index + 1] << 8) |\n (this.data[this.index + 2] << 16) |\n (this.data[this.index + 3] << 24);\n\n // If we have raw results specified slice the return document\n if (raw) {\n this.documents[i] = this.data.slice(this.index, this.index + bsonSize);\n } else {\n this.documents[i] = this.bson.deserialize(\n this.data.slice(this.index, this.index + bsonSize),\n _options\n );\n }\n\n // Adjust the index\n this.index = this.index + bsonSize;\n }\n\n if (this.documents.length === 1 && documentsReturnedIn != null && raw) {\n const fieldsAsRaw = {};\n fieldsAsRaw[documentsReturnedIn] = true;\n _options.fieldsAsRaw = fieldsAsRaw;\n\n const doc = this.bson.deserialize(this.documents[0], _options);\n this.documents = [doc];\n }\n\n // Set parsed\n this.parsed = true;\n};\n\nmodule.exports = {\n Query: Query,\n GetMore: GetMore,\n Response: Response,\n KillCursor: KillCursor\n};\n","'use strict';\nconst net = require('net');\nconst tls = require('tls');\nconst Connection = require('./connection');\nconst MongoError = require('../error').MongoError;\nconst MongoNetworkError = require('../error').MongoNetworkError;\nconst MongoNetworkTimeoutError = require('../error').MongoNetworkTimeoutError;\nconst defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders;\nconst AuthContext = require('../auth/auth_provider').AuthContext;\nconst WIRE_CONSTANTS = require('../wireprotocol/constants');\nconst makeClientMetadata = require('../utils').makeClientMetadata;\nconst MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION;\nconst MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION;\nconst MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION;\nconst MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION;\nlet AUTH_PROVIDERS;\n\nfunction connect(options, cancellationToken, callback) {\n if (typeof cancellationToken === 'function') {\n callback = cancellationToken;\n cancellationToken = undefined;\n }\n\n const ConnectionType = options && options.connectionType ? options.connectionType : Connection;\n if (AUTH_PROVIDERS == null) {\n AUTH_PROVIDERS = defaultAuthProviders(options.bson);\n }\n\n const family = options.family !== void 0 ? options.family : 0;\n makeConnection(family, options, cancellationToken, (err, socket) => {\n if (err) {\n callback(err, socket); // in the error case, `socket` is the originating error event name\n return;\n }\n\n performInitialHandshake(new ConnectionType(socket, options), options, callback);\n });\n}\n\nfunction isModernConnectionType(conn) {\n return !(conn instanceof Connection);\n}\n\nfunction checkSupportedServer(ismaster, options) {\n const serverVersionHighEnough =\n ismaster &&\n typeof ismaster.maxWireVersion === 'number' &&\n ismaster.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION;\n const serverVersionLowEnough =\n ismaster &&\n typeof ismaster.minWireVersion === 'number' &&\n ismaster.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION;\n\n if (serverVersionHighEnough) {\n if (serverVersionLowEnough) {\n return null;\n }\n\n const message = `Server at ${options.host}:${options.port} reports minimum wire version ${ismaster.minWireVersion}, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`;\n return new MongoError(message);\n }\n\n const message = `Server at ${options.host}:${\n options.port\n } reports maximum wire version ${ismaster.maxWireVersion ||\n 0}, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`;\n return new MongoError(message);\n}\n\nfunction performInitialHandshake(conn, options, _callback) {\n const callback = function(err, ret) {\n if (err && conn) {\n conn.destroy();\n }\n _callback(err, ret);\n };\n\n const credentials = options.credentials;\n if (credentials) {\n if (!credentials.mechanism.match(/DEFAULT/i) && !AUTH_PROVIDERS[credentials.mechanism]) {\n callback(new MongoError(`authMechanism '${credentials.mechanism}' not supported`));\n return;\n }\n }\n\n const authContext = new AuthContext(conn, credentials, options);\n prepareHandshakeDocument(authContext, (err, handshakeDoc) => {\n if (err) {\n return callback(err);\n }\n\n const handshakeOptions = Object.assign({}, options);\n if (options.connectTimeoutMS || options.connectionTimeout) {\n // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS\n handshakeOptions.socketTimeout = options.connectTimeoutMS || options.connectionTimeout;\n }\n\n const start = new Date().getTime();\n conn.command('admin.$cmd', handshakeDoc, handshakeOptions, (err, result) => {\n if (err) {\n callback(err);\n return;\n }\n\n const response = result.result;\n if (response.ok === 0) {\n callback(new MongoError(response));\n return;\n }\n\n const supportedServerErr = checkSupportedServer(response, options);\n if (supportedServerErr) {\n callback(supportedServerErr);\n return;\n }\n\n if (!isModernConnectionType(conn)) {\n // resolve compression\n if (response.compression) {\n const agreedCompressors = handshakeDoc.compression.filter(\n compressor => response.compression.indexOf(compressor) !== -1\n );\n\n if (agreedCompressors.length) {\n conn.agreedCompressor = agreedCompressors[0];\n }\n\n if (options.compression && options.compression.zlibCompressionLevel) {\n conn.zlibCompressionLevel = options.compression.zlibCompressionLevel;\n }\n }\n }\n\n // NOTE: This is metadata attached to the connection while porting away from\n // handshake being done in the `Server` class. Likely, it should be\n // relocated, or at very least restructured.\n conn.ismaster = response;\n conn.lastIsMasterMS = new Date().getTime() - start;\n\n if (!response.arbiterOnly && credentials) {\n // store the response on auth context\n Object.assign(authContext, { response });\n\n const resolvedCredentials = credentials.resolveAuthMechanism(response);\n const authProvider = AUTH_PROVIDERS[resolvedCredentials.mechanism];\n authProvider.auth(authContext, err => {\n if (err) return callback(err);\n callback(undefined, conn);\n });\n\n return;\n }\n\n callback(undefined, conn);\n });\n });\n}\n\nfunction prepareHandshakeDocument(authContext, callback) {\n const options = authContext.options;\n const compressors =\n options.compression && options.compression.compressors ? options.compression.compressors : [];\n\n const handshakeDoc = {\n ismaster: true,\n client: options.metadata || makeClientMetadata(options),\n compression: compressors\n };\n\n const credentials = authContext.credentials;\n if (credentials) {\n if (credentials.mechanism.match(/DEFAULT/i) && credentials.username) {\n Object.assign(handshakeDoc, {\n saslSupportedMechs: `${credentials.source}.${credentials.username}`\n });\n\n AUTH_PROVIDERS['scram-sha-256'].prepare(handshakeDoc, authContext, callback);\n return;\n }\n\n const authProvider = AUTH_PROVIDERS[credentials.mechanism];\n authProvider.prepare(handshakeDoc, authContext, callback);\n return;\n }\n\n callback(undefined, handshakeDoc);\n}\n\nconst LEGAL_SSL_SOCKET_OPTIONS = [\n 'pfx',\n 'key',\n 'passphrase',\n 'cert',\n 'ca',\n 'ciphers',\n 'NPNProtocols',\n 'ALPNProtocols',\n 'servername',\n 'ecdhCurve',\n 'secureProtocol',\n 'secureContext',\n 'session',\n 'minDHSize',\n 'crl',\n 'rejectUnauthorized'\n];\n\nfunction parseConnectOptions(family, options) {\n const host = typeof options.host === 'string' ? options.host : 'localhost';\n if (host.indexOf('/') !== -1) {\n return { path: host };\n }\n\n const result = {\n family,\n host,\n port: typeof options.port === 'number' ? options.port : 27017,\n rejectUnauthorized: false\n };\n\n return result;\n}\n\nfunction parseSslOptions(family, options) {\n const result = parseConnectOptions(family, options);\n\n // Merge in valid SSL options\n for (const name in options) {\n if (options[name] != null && LEGAL_SSL_SOCKET_OPTIONS.indexOf(name) !== -1) {\n result[name] = options[name];\n }\n }\n\n // Override checkServerIdentity behavior\n if (options.checkServerIdentity === false) {\n // Skip the identiy check by retuning undefined as per node documents\n // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback\n result.checkServerIdentity = function() {\n return undefined;\n };\n } else if (typeof options.checkServerIdentity === 'function') {\n result.checkServerIdentity = options.checkServerIdentity;\n }\n\n // Set default sni servername to be the same as host\n if (result.servername == null) {\n result.servername = result.host;\n }\n\n return result;\n}\n\nconst SOCKET_ERROR_EVENTS = new Set(['error', 'close', 'timeout', 'parseError']);\nfunction makeConnection(family, options, cancellationToken, _callback) {\n const useSsl = typeof options.ssl === 'boolean' ? options.ssl : false;\n const keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true;\n let keepAliveInitialDelay =\n typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 120000;\n const noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true;\n const connectionTimeout =\n typeof options.connectionTimeout === 'number'\n ? options.connectionTimeout\n : typeof options.connectTimeoutMS === 'number'\n ? options.connectTimeoutMS\n : 30000;\n const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000;\n const rejectUnauthorized =\n typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true;\n\n if (keepAliveInitialDelay > socketTimeout) {\n keepAliveInitialDelay = Math.round(socketTimeout / 2);\n }\n\n let socket;\n const callback = function(err, ret) {\n if (err && socket) {\n socket.destroy();\n }\n\n _callback(err, ret);\n };\n\n try {\n if (useSsl) {\n socket = tls.connect(parseSslOptions(family, options));\n if (typeof socket.disableRenegotiation === 'function') {\n socket.disableRenegotiation();\n }\n } else {\n socket = net.createConnection(parseConnectOptions(family, options));\n }\n } catch (err) {\n return callback(err);\n }\n\n socket.setKeepAlive(keepAlive, keepAliveInitialDelay);\n socket.setTimeout(connectionTimeout);\n socket.setNoDelay(noDelay);\n\n const connectEvent = useSsl ? 'secureConnect' : 'connect';\n let cancellationHandler;\n function errorHandler(eventName) {\n return err => {\n SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event));\n if (cancellationHandler) {\n cancellationToken.removeListener('cancel', cancellationHandler);\n }\n\n socket.removeListener(connectEvent, connectHandler);\n callback(connectionFailureError(eventName, err));\n };\n }\n\n function connectHandler() {\n SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event));\n if (cancellationHandler) {\n cancellationToken.removeListener('cancel', cancellationHandler);\n }\n\n if (socket.authorizationError && rejectUnauthorized) {\n return callback(socket.authorizationError);\n }\n\n socket.setTimeout(socketTimeout);\n callback(null, socket);\n }\n\n SOCKET_ERROR_EVENTS.forEach(event => socket.once(event, errorHandler(event)));\n if (cancellationToken) {\n cancellationHandler = errorHandler('cancel');\n cancellationToken.once('cancel', cancellationHandler);\n }\n\n socket.once(connectEvent, connectHandler);\n}\n\nfunction connectionFailureError(type, err) {\n switch (type) {\n case 'error':\n return new MongoNetworkError(err);\n case 'timeout':\n return new MongoNetworkTimeoutError(`connection timed out`);\n case 'close':\n return new MongoNetworkError(`connection closed`);\n case 'cancel':\n return new MongoNetworkError(`connection establishment was cancelled`);\n default:\n return new MongoNetworkError(`unknown network error`);\n }\n}\n\nmodule.exports = connect;\n","'use strict';\n\nconst EventEmitter = require('events').EventEmitter;\nconst crypto = require('crypto');\nconst debugOptions = require('./utils').debugOptions;\nconst parseHeader = require('../wireprotocol/shared').parseHeader;\nconst decompress = require('../wireprotocol/compression').decompress;\nconst Response = require('./commands').Response;\nconst BinMsg = require('./msg').BinMsg;\nconst MongoNetworkError = require('../error').MongoNetworkError;\nconst MongoNetworkTimeoutError = require('../error').MongoNetworkTimeoutError;\nconst MongoError = require('../error').MongoError;\nconst Logger = require('./logger');\nconst OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED;\nconst OP_MSG = require('../wireprotocol/shared').opcodes.OP_MSG;\nconst MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE;\nconst Buffer = require('safe-buffer').Buffer;\nconst Query = require('./commands').Query;\nconst CommandResult = require('./command_result');\n\nlet _id = 0;\n\nconst DEFAULT_MAX_BSON_MESSAGE_SIZE = 1024 * 1024 * 16 * 4;\nconst DEBUG_FIELDS = [\n 'host',\n 'port',\n 'size',\n 'keepAlive',\n 'keepAliveInitialDelay',\n 'noDelay',\n 'connectionTimeout',\n 'socketTimeout',\n 'ssl',\n 'ca',\n 'crl',\n 'cert',\n 'rejectUnauthorized',\n 'promoteLongs',\n 'promoteValues',\n 'promoteBuffers',\n 'checkServerIdentity'\n];\n\nlet connectionAccountingSpy = undefined;\nlet connectionAccounting = false;\nlet connections = {};\n\n/**\n * A class representing a single connection to a MongoDB server\n *\n * @fires Connection#connect\n * @fires Connection#close\n * @fires Connection#error\n * @fires Connection#timeout\n * @fires Connection#parseError\n * @fires Connection#message\n */\nclass Connection extends EventEmitter {\n /**\n * Creates a new Connection instance\n *\n * **NOTE**: Internal class, do not instantiate directly\n *\n * @param {Socket} socket The socket this connection wraps\n * @param {Object} options Various settings\n * @param {object} options.bson An implementation of bson serialize and deserialize\n * @param {string} [options.host='localhost'] The host the socket is connected to\n * @param {number} [options.port=27017] The port used for the socket connection\n * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled\n * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled\n * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting\n * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting\n * @param {boolean} [options.promoteLongs] Convert Long values from the db into Numbers if they fit into 53 bits\n * @param {boolean} [options.promoteValues] Promotes BSON values to native types where possible, set to false to only receive wrapper types.\n * @param {boolean} [options.promoteBuffers] Promotes Binary BSON values to native Node Buffers.\n * @param {number} [options.maxBsonMessageSize=0x4000000] Largest possible size of a BSON message (for legacy purposes)\n */\n constructor(socket, options) {\n super();\n\n options = options || {};\n if (!options.bson) {\n throw new TypeError('must pass in valid bson parser');\n }\n\n this.id = _id++;\n this.options = options;\n this.logger = Logger('Connection', options);\n this.bson = options.bson;\n this.tag = options.tag;\n this.maxBsonMessageSize = options.maxBsonMessageSize || DEFAULT_MAX_BSON_MESSAGE_SIZE;\n\n this.port = options.port || 27017;\n this.host = options.host || 'localhost';\n this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000;\n\n // These values are inspected directly in tests, but maybe not necessary to keep around\n this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true;\n this.keepAliveInitialDelay =\n typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 120000;\n this.connectionTimeout =\n typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000;\n if (this.keepAliveInitialDelay > this.socketTimeout) {\n this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2);\n }\n\n // Debug information\n if (this.logger.isDebug()) {\n this.logger.debug(\n `creating connection ${this.id} with options [${JSON.stringify(\n debugOptions(DEBUG_FIELDS, options)\n )}]`\n );\n }\n\n // Response options\n this.responseOptions = {\n promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true,\n promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true,\n promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false\n };\n\n // Flushing\n this.flushing = false;\n this.queue = [];\n\n // Internal state\n this.writeStream = null;\n this.destroyed = false;\n this.timedOut = false;\n\n // Create hash method\n const hash = crypto.createHash('sha1');\n hash.update(this.address);\n this.hashedName = hash.digest('hex');\n\n // All operations in flight on the connection\n this.workItems = [];\n\n // setup socket\n this.socket = socket;\n this.socket.once('error', errorHandler(this));\n this.socket.once('timeout', timeoutHandler(this));\n this.socket.once('close', closeHandler(this));\n this.socket.on('data', dataHandler(this));\n\n if (connectionAccounting) {\n addConnection(this.id, this);\n }\n }\n\n setSocketTimeout(value) {\n if (this.socket) {\n this.socket.setTimeout(value);\n }\n }\n\n resetSocketTimeout() {\n if (this.socket) {\n this.socket.setTimeout(this.socketTimeout);\n }\n }\n\n static enableConnectionAccounting(spy) {\n if (spy) {\n connectionAccountingSpy = spy;\n }\n\n connectionAccounting = true;\n connections = {};\n }\n\n static disableConnectionAccounting() {\n connectionAccounting = false;\n connectionAccountingSpy = undefined;\n }\n\n static connections() {\n return connections;\n }\n\n get address() {\n return `${this.host}:${this.port}`;\n }\n\n /**\n * Unref this connection\n * @method\n * @return {boolean}\n */\n unref() {\n if (this.socket == null) {\n this.once('connect', () => this.socket.unref());\n return;\n }\n\n this.socket.unref();\n }\n\n /**\n * Flush all work Items on this connection\n *\n * @param {*} err The error to propagate to the flushed work items\n */\n flush(err) {\n while (this.workItems.length > 0) {\n const workItem = this.workItems.shift();\n if (workItem.cb) {\n workItem.cb(err);\n }\n }\n }\n\n /**\n * Destroy connection\n * @method\n */\n destroy(options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n options = Object.assign({ force: false }, options);\n\n if (connectionAccounting) {\n deleteConnection(this.id);\n }\n\n if (this.socket == null) {\n this.destroyed = true;\n return;\n }\n\n if (options.force || this.timedOut) {\n this.socket.destroy();\n this.destroyed = true;\n if (typeof callback === 'function') callback(null, null);\n return;\n }\n\n this.socket.end(err => {\n this.destroyed = true;\n if (typeof callback === 'function') callback(err, null);\n });\n }\n\n /**\n * Write to connection\n * @method\n * @param {Command} command Command to write out need to implement toBin and toBinUnified\n */\n write(buffer) {\n // Debug Log\n if (this.logger.isDebug()) {\n if (!Array.isArray(buffer)) {\n this.logger.debug(`writing buffer [${buffer.toString('hex')}] to ${this.address}`);\n } else {\n for (let i = 0; i < buffer.length; i++)\n this.logger.debug(`writing buffer [${buffer[i].toString('hex')}] to ${this.address}`);\n }\n }\n\n // Double check that the connection is not destroyed\n if (this.socket.destroyed === false) {\n // Write out the command\n if (!Array.isArray(buffer)) {\n this.socket.write(buffer, 'binary');\n return true;\n }\n\n // Iterate over all buffers and write them in order to the socket\n for (let i = 0; i < buffer.length; i++) {\n this.socket.write(buffer[i], 'binary');\n }\n\n return true;\n }\n\n // Connection is destroyed return write failed\n return false;\n }\n\n /**\n * Return id of connection as a string\n * @method\n * @return {string}\n */\n toString() {\n return '' + this.id;\n }\n\n /**\n * Return json object of connection\n * @method\n * @return {object}\n */\n toJSON() {\n return { id: this.id, host: this.host, port: this.port };\n }\n\n /**\n * Is the connection connected\n * @method\n * @return {boolean}\n */\n isConnected() {\n if (this.destroyed) return false;\n return !this.socket.destroyed && this.socket.writable;\n }\n\n /**\n * @ignore\n */\n command(ns, command, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n\n const conn = this;\n const socketTimeout =\n typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000;\n const bson = conn.options.bson;\n const query = new Query(bson, ns, command, {\n numberToSkip: 0,\n numberToReturn: 1\n });\n\n const noop = () => {};\n function _callback(err, result) {\n callback(err, result);\n callback = noop;\n }\n\n function errorHandler(err) {\n conn.resetSocketTimeout();\n CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler));\n conn.removeListener('message', messageHandler);\n\n if (err == null) {\n err = new MongoError(`runCommand failed for connection to '${conn.address}'`);\n }\n\n // ignore all future errors\n conn.on('error', noop);\n _callback(err);\n }\n\n function messageHandler(msg) {\n if (msg.responseTo !== query.requestId) {\n return;\n }\n\n conn.resetSocketTimeout();\n CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler));\n conn.removeListener('message', messageHandler);\n\n msg.parse({ promoteValues: true });\n\n const response = msg.documents[0];\n if (response.ok === 0 || response.$err || response.errmsg || response.code) {\n _callback(new MongoError(response));\n return;\n }\n\n _callback(undefined, new CommandResult(response, this, msg));\n }\n\n conn.setSocketTimeout(socketTimeout);\n CONNECTION_ERROR_EVENTS.forEach(eventName => conn.once(eventName, errorHandler));\n conn.on('message', messageHandler);\n conn.write(query.toBin());\n }\n}\n\nconst CONNECTION_ERROR_EVENTS = ['error', 'close', 'timeout', 'parseError'];\n\nfunction deleteConnection(id) {\n // console.log(\"=== deleted connection \" + id + \" :: \" + (connections[id] ? connections[id].port : ''))\n delete connections[id];\n\n if (connectionAccountingSpy) {\n connectionAccountingSpy.deleteConnection(id);\n }\n}\n\nfunction addConnection(id, connection) {\n // console.log(\"=== added connection \" + id + \" :: \" + connection.port)\n connections[id] = connection;\n\n if (connectionAccountingSpy) {\n connectionAccountingSpy.addConnection(id, connection);\n }\n}\n\n//\n// Connection handlers\nfunction errorHandler(conn) {\n return function(err) {\n if (connectionAccounting) deleteConnection(conn.id);\n // Debug information\n if (conn.logger.isDebug()) {\n conn.logger.debug(\n `connection ${conn.id} for [${conn.address}] errored out with [${JSON.stringify(err)}]`\n );\n }\n\n conn.emit('error', new MongoNetworkError(err), conn);\n };\n}\n\nfunction timeoutHandler(conn) {\n return function() {\n if (connectionAccounting) deleteConnection(conn.id);\n\n if (conn.logger.isDebug()) {\n conn.logger.debug(`connection ${conn.id} for [${conn.address}] timed out`);\n }\n\n conn.timedOut = true;\n conn.emit(\n 'timeout',\n new MongoNetworkTimeoutError(`connection ${conn.id} to ${conn.address} timed out`, {\n beforeHandshake: conn.ismaster == null\n }),\n conn\n );\n };\n}\n\nfunction closeHandler(conn) {\n return function(hadError) {\n if (connectionAccounting) deleteConnection(conn.id);\n\n if (conn.logger.isDebug()) {\n conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`);\n }\n\n if (!hadError) {\n conn.emit(\n 'close',\n new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`),\n conn\n );\n }\n };\n}\n\n// Handle a message once it is received\nfunction processMessage(conn, message) {\n const msgHeader = parseHeader(message);\n if (msgHeader.opCode !== OP_COMPRESSED) {\n const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response;\n conn.emit(\n 'message',\n new ResponseConstructor(\n conn.bson,\n message,\n msgHeader,\n message.slice(MESSAGE_HEADER_SIZE),\n conn.responseOptions\n ),\n conn\n );\n\n return;\n }\n\n msgHeader.fromCompressed = true;\n let index = MESSAGE_HEADER_SIZE;\n msgHeader.opCode = message.readInt32LE(index);\n index += 4;\n msgHeader.length = message.readInt32LE(index);\n index += 4;\n const compressorID = message[index];\n index++;\n\n decompress(compressorID, message.slice(index), (err, decompressedMsgBody) => {\n if (err) {\n conn.emit('error', err);\n return;\n }\n\n if (decompressedMsgBody.length !== msgHeader.length) {\n conn.emit(\n 'error',\n new MongoError(\n 'Decompressing a compressed message from the server failed. The message is corrupt.'\n )\n );\n\n return;\n }\n\n const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response;\n conn.emit(\n 'message',\n new ResponseConstructor(\n conn.bson,\n message,\n msgHeader,\n decompressedMsgBody,\n conn.responseOptions\n ),\n conn\n );\n });\n}\n\nfunction dataHandler(conn) {\n return function(data) {\n // Parse until we are done with the data\n while (data.length > 0) {\n // If we still have bytes to read on the current message\n if (conn.bytesRead > 0 && conn.sizeOfMessage > 0) {\n // Calculate the amount of remaining bytes\n const remainingBytesToRead = conn.sizeOfMessage - conn.bytesRead;\n // Check if the current chunk contains the rest of the message\n if (remainingBytesToRead > data.length) {\n // Copy the new data into the exiting buffer (should have been allocated when we know the message size)\n data.copy(conn.buffer, conn.bytesRead);\n // Adjust the number of bytes read so it point to the correct index in the buffer\n conn.bytesRead = conn.bytesRead + data.length;\n\n // Reset state of buffer\n data = Buffer.alloc(0);\n } else {\n // Copy the missing part of the data into our current buffer\n data.copy(conn.buffer, conn.bytesRead, 0, remainingBytesToRead);\n // Slice the overflow into a new buffer that we will then re-parse\n data = data.slice(remainingBytesToRead);\n\n // Emit current complete message\n const emitBuffer = conn.buffer;\n // Reset state of buffer\n conn.buffer = null;\n conn.sizeOfMessage = 0;\n conn.bytesRead = 0;\n conn.stubBuffer = null;\n\n processMessage(conn, emitBuffer);\n }\n } else {\n // Stub buffer is kept in case we don't get enough bytes to determine the\n // size of the message (< 4 bytes)\n if (conn.stubBuffer != null && conn.stubBuffer.length > 0) {\n // If we have enough bytes to determine the message size let's do it\n if (conn.stubBuffer.length + data.length > 4) {\n // Prepad the data\n const newData = Buffer.alloc(conn.stubBuffer.length + data.length);\n conn.stubBuffer.copy(newData, 0);\n data.copy(newData, conn.stubBuffer.length);\n // Reassign for parsing\n data = newData;\n\n // Reset state of buffer\n conn.buffer = null;\n conn.sizeOfMessage = 0;\n conn.bytesRead = 0;\n conn.stubBuffer = null;\n } else {\n // Add the the bytes to the stub buffer\n const newStubBuffer = Buffer.alloc(conn.stubBuffer.length + data.length);\n // Copy existing stub buffer\n conn.stubBuffer.copy(newStubBuffer, 0);\n // Copy missing part of the data\n data.copy(newStubBuffer, conn.stubBuffer.length);\n // Exit parsing loop\n data = Buffer.alloc(0);\n }\n } else {\n if (data.length > 4) {\n // Retrieve the message size\n const sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);\n // If we have a negative sizeOfMessage emit error and return\n if (sizeOfMessage < 0 || sizeOfMessage > conn.maxBsonMessageSize) {\n const errorObject = {\n err: 'socketHandler',\n trace: '',\n bin: conn.buffer,\n parseState: {\n sizeOfMessage: sizeOfMessage,\n bytesRead: conn.bytesRead,\n stubBuffer: conn.stubBuffer\n }\n };\n // We got a parse Error fire it off then keep going\n conn.emit('parseError', errorObject, conn);\n return;\n }\n\n // Ensure that the size of message is larger than 0 and less than the max allowed\n if (\n sizeOfMessage > 4 &&\n sizeOfMessage < conn.maxBsonMessageSize &&\n sizeOfMessage > data.length\n ) {\n conn.buffer = Buffer.alloc(sizeOfMessage);\n // Copy all the data into the buffer\n data.copy(conn.buffer, 0);\n // Update bytes read\n conn.bytesRead = data.length;\n // Update sizeOfMessage\n conn.sizeOfMessage = sizeOfMessage;\n // Ensure stub buffer is null\n conn.stubBuffer = null;\n // Exit parsing loop\n data = Buffer.alloc(0);\n } else if (\n sizeOfMessage > 4 &&\n sizeOfMessage < conn.maxBsonMessageSize &&\n sizeOfMessage === data.length\n ) {\n const emitBuffer = data;\n // Reset state of buffer\n conn.buffer = null;\n conn.sizeOfMessage = 0;\n conn.bytesRead = 0;\n conn.stubBuffer = null;\n // Exit parsing loop\n data = Buffer.alloc(0);\n // Emit the message\n processMessage(conn, emitBuffer);\n } else if (sizeOfMessage <= 4 || sizeOfMessage > conn.maxBsonMessageSize) {\n const errorObject = {\n err: 'socketHandler',\n trace: null,\n bin: data,\n parseState: {\n sizeOfMessage: sizeOfMessage,\n bytesRead: 0,\n buffer: null,\n stubBuffer: null\n }\n };\n // We got a parse Error fire it off then keep going\n conn.emit('parseError', errorObject, conn);\n\n // Clear out the state of the parser\n conn.buffer = null;\n conn.sizeOfMessage = 0;\n conn.bytesRead = 0;\n conn.stubBuffer = null;\n // Exit parsing loop\n data = Buffer.alloc(0);\n } else {\n const emitBuffer = data.slice(0, sizeOfMessage);\n // Reset state of buffer\n conn.buffer = null;\n conn.sizeOfMessage = 0;\n conn.bytesRead = 0;\n conn.stubBuffer = null;\n // Copy rest of message\n data = data.slice(sizeOfMessage);\n // Emit the message\n processMessage(conn, emitBuffer);\n }\n } else {\n // Create a buffer that contains the space for the non-complete message\n conn.stubBuffer = Buffer.alloc(data.length);\n // Copy the data to the stub buffer\n data.copy(conn.stubBuffer, 0);\n // Exit parsing loop\n data = Buffer.alloc(0);\n }\n }\n }\n }\n };\n}\n\n/**\n * A server connect event, used to verify that the connection is up and running\n *\n * @event Connection#connect\n * @type {Connection}\n */\n\n/**\n * The server connection closed, all pool connections closed\n *\n * @event Connection#close\n * @type {Connection}\n */\n\n/**\n * The server connection caused an error, all pool connections closed\n *\n * @event Connection#error\n * @type {Connection}\n */\n\n/**\n * The server connection timed out, all pool connections closed\n *\n * @event Connection#timeout\n * @type {Connection}\n */\n\n/**\n * The driver experienced an invalid message, all pool connections closed\n *\n * @event Connection#parseError\n * @type {Connection}\n */\n\n/**\n * An event emitted each time the connection receives a parsed message from the wire\n *\n * @event Connection#message\n * @type {Connection}\n */\n\nmodule.exports = Connection;\n","'use strict';\n\nvar f = require('util').format,\n MongoError = require('../error').MongoError;\n\n// Filters for classes\nvar classFilters = {};\nvar filteredClasses = {};\nvar level = null;\n// Save the process id\nvar pid = process.pid;\n// current logger\nvar currentLogger = null;\n\n/**\n * @callback Logger~loggerCallback\n * @param {string} msg message being logged\n * @param {object} state an object containing more metadata about the logging message\n */\n\n/**\n * Creates a new Logger instance\n * @class\n * @param {string} className The Class name associated with the logging instance\n * @param {object} [options=null] Optional settings.\n * @param {Logger~loggerCallback} [options.logger=null] Custom logger function;\n * @param {string} [options.loggerLevel=error] Override default global log level.\n */\nvar Logger = function(className, options) {\n if (!(this instanceof Logger)) return new Logger(className, options);\n options = options || {};\n\n // Current reference\n this.className = className;\n\n // Current logger\n if (options.logger) {\n currentLogger = options.logger;\n } else if (currentLogger == null) {\n currentLogger = console.log;\n }\n\n // Set level of logging, default is error\n if (options.loggerLevel) {\n level = options.loggerLevel || 'error';\n }\n\n // Add all class names\n if (filteredClasses[this.className] == null) classFilters[this.className] = true;\n};\n\n/**\n * Log a message at the debug level\n * @method\n * @param {string} message The message to log\n * @param {object} object additional meta data to log\n * @return {null}\n */\nLogger.prototype.debug = function(message, object) {\n if (\n this.isDebug() &&\n ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) ||\n (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))\n ) {\n var dateTime = new Date().getTime();\n var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message);\n var state = {\n type: 'debug',\n message: message,\n className: this.className,\n pid: pid,\n date: dateTime\n };\n if (object) state.meta = object;\n currentLogger(msg, state);\n }\n};\n\n/**\n * Log a message at the warn level\n * @method\n * @param {string} message The message to log\n * @param {object} object additional meta data to log\n * @return {null}\n */\n(Logger.prototype.warn = function(message, object) {\n if (\n this.isWarn() &&\n ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) ||\n (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))\n ) {\n var dateTime = new Date().getTime();\n var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message);\n var state = {\n type: 'warn',\n message: message,\n className: this.className,\n pid: pid,\n date: dateTime\n };\n if (object) state.meta = object;\n currentLogger(msg, state);\n }\n}),\n /**\n * Log a message at the info level\n * @method\n * @param {string} message The message to log\n * @param {object} object additional meta data to log\n * @return {null}\n */\n (Logger.prototype.info = function(message, object) {\n if (\n this.isInfo() &&\n ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) ||\n (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))\n ) {\n var dateTime = new Date().getTime();\n var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message);\n var state = {\n type: 'info',\n message: message,\n className: this.className,\n pid: pid,\n date: dateTime\n };\n if (object) state.meta = object;\n currentLogger(msg, state);\n }\n }),\n /**\n * Log a message at the error level\n * @method\n * @param {string} message The message to log\n * @param {object} object additional meta data to log\n * @return {null}\n */\n (Logger.prototype.error = function(message, object) {\n if (\n this.isError() &&\n ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) ||\n (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))\n ) {\n var dateTime = new Date().getTime();\n var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message);\n var state = {\n type: 'error',\n message: message,\n className: this.className,\n pid: pid,\n date: dateTime\n };\n if (object) state.meta = object;\n currentLogger(msg, state);\n }\n }),\n /**\n * Is the logger set at info level\n * @method\n * @return {boolean}\n */\n (Logger.prototype.isInfo = function() {\n return level === 'info' || level === 'debug';\n }),\n /**\n * Is the logger set at error level\n * @method\n * @return {boolean}\n */\n (Logger.prototype.isError = function() {\n return level === 'error' || level === 'info' || level === 'debug';\n }),\n /**\n * Is the logger set at error level\n * @method\n * @return {boolean}\n */\n (Logger.prototype.isWarn = function() {\n return level === 'error' || level === 'warn' || level === 'info' || level === 'debug';\n }),\n /**\n * Is the logger set at debug level\n * @method\n * @return {boolean}\n */\n (Logger.prototype.isDebug = function() {\n return level === 'debug';\n });\n\n/**\n * Resets the logger to default settings, error and no filtered classes\n * @method\n * @return {null}\n */\nLogger.reset = function() {\n level = 'error';\n filteredClasses = {};\n};\n\n/**\n * Get the current logger function\n * @method\n * @return {Logger~loggerCallback}\n */\nLogger.currentLogger = function() {\n return currentLogger;\n};\n\n/**\n * Set the current logger function\n * @method\n * @param {Logger~loggerCallback} logger Logger function.\n * @return {null}\n */\nLogger.setCurrentLogger = function(logger) {\n if (typeof logger !== 'function') throw new MongoError('current logger must be a function');\n currentLogger = logger;\n};\n\n/**\n * Set what classes to log.\n * @method\n * @param {string} type The type of filter (currently only class)\n * @param {string[]} values The filters to apply\n * @return {null}\n */\nLogger.filter = function(type, values) {\n if (type === 'class' && Array.isArray(values)) {\n filteredClasses = {};\n\n values.forEach(function(x) {\n filteredClasses[x] = true;\n });\n }\n};\n\n/**\n * Set the current log level\n * @method\n * @param {string} level Set current log level (debug, info, error)\n * @return {null}\n */\nLogger.setLevel = function(_level) {\n if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') {\n throw new Error(f('%s is an illegal logging level', _level));\n }\n\n level = _level;\n};\n\nmodule.exports = Logger;\n","'use strict';\n\n// Implementation of OP_MSG spec:\n// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst\n//\n// struct Section {\n// uint8 payloadType;\n// union payload {\n// document document; // payloadType == 0\n// struct sequence { // payloadType == 1\n// int32 size;\n// cstring identifier;\n// document* documents;\n// };\n// };\n// };\n\n// struct OP_MSG {\n// struct MsgHeader {\n// int32 messageLength;\n// int32 requestID;\n// int32 responseTo;\n// int32 opCode = 2013;\n// };\n// uint32 flagBits;\n// Section+ sections;\n// [uint32 checksum;]\n// };\n\nconst Buffer = require('safe-buffer').Buffer;\nconst opcodes = require('../wireprotocol/shared').opcodes;\nconst databaseNamespace = require('../wireprotocol/shared').databaseNamespace;\nconst ReadPreference = require('../topologies/read_preference');\n\n// Incrementing request id\nlet _requestId = 0;\n\n// Msg Flags\nconst OPTS_CHECKSUM_PRESENT = 1;\nconst OPTS_MORE_TO_COME = 2;\nconst OPTS_EXHAUST_ALLOWED = 1 << 16;\n\nclass Msg {\n constructor(bson, ns, command, options) {\n // Basic options needed to be passed in\n if (command == null) throw new Error('query must be specified for query');\n\n // Basic options\n this.bson = bson;\n this.ns = ns;\n this.command = command;\n this.command.$db = databaseNamespace(ns);\n\n if (options.readPreference && options.readPreference.mode !== ReadPreference.PRIMARY) {\n this.command.$readPreference = options.readPreference.toJSON();\n }\n\n // Ensure empty options\n this.options = options || {};\n\n // Additional options\n this.requestId = options.requestId ? options.requestId : Msg.getRequestId();\n\n // Serialization option\n this.serializeFunctions =\n typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;\n this.ignoreUndefined =\n typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false;\n this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;\n this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16;\n\n // flags\n this.checksumPresent = false;\n this.moreToCome = options.moreToCome || false;\n this.exhaustAllowed =\n typeof options.exhaustAllowed === 'boolean' ? options.exhaustAllowed : false;\n }\n\n toBin() {\n const buffers = [];\n let flags = 0;\n\n if (this.checksumPresent) {\n flags |= OPTS_CHECKSUM_PRESENT;\n }\n\n if (this.moreToCome) {\n flags |= OPTS_MORE_TO_COME;\n }\n\n if (this.exhaustAllowed) {\n flags |= OPTS_EXHAUST_ALLOWED;\n }\n\n const header = Buffer.alloc(\n 4 * 4 + // Header\n 4 // Flags\n );\n\n buffers.push(header);\n\n let totalLength = header.length;\n const command = this.command;\n totalLength += this.makeDocumentSegment(buffers, command);\n\n header.writeInt32LE(totalLength, 0); // messageLength\n header.writeInt32LE(this.requestId, 4); // requestID\n header.writeInt32LE(0, 8); // responseTo\n header.writeInt32LE(opcodes.OP_MSG, 12); // opCode\n header.writeUInt32LE(flags, 16); // flags\n return buffers;\n }\n\n makeDocumentSegment(buffers, document) {\n const payloadTypeBuffer = Buffer.alloc(1);\n payloadTypeBuffer[0] = 0;\n\n const documentBuffer = this.serializeBson(document);\n buffers.push(payloadTypeBuffer);\n buffers.push(documentBuffer);\n\n return payloadTypeBuffer.length + documentBuffer.length;\n }\n\n serializeBson(document) {\n return this.bson.serialize(document, {\n checkKeys: this.checkKeys,\n serializeFunctions: this.serializeFunctions,\n ignoreUndefined: this.ignoreUndefined\n });\n }\n}\n\nMsg.getRequestId = function() {\n _requestId = (_requestId + 1) & 0x7fffffff;\n return _requestId;\n};\n\nclass BinMsg {\n constructor(bson, message, msgHeader, msgBody, opts) {\n opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false };\n this.parsed = false;\n this.raw = message;\n this.data = msgBody;\n this.bson = bson;\n this.opts = opts;\n\n // Read the message header\n this.length = msgHeader.length;\n this.requestId = msgHeader.requestId;\n this.responseTo = msgHeader.responseTo;\n this.opCode = msgHeader.opCode;\n this.fromCompressed = msgHeader.fromCompressed;\n\n // Read response flags\n this.responseFlags = msgBody.readInt32LE(0);\n this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0;\n this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0;\n this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0;\n this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true;\n this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true;\n this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false;\n\n this.documents = [];\n }\n\n isParsed() {\n return this.parsed;\n }\n\n parse(options) {\n // Don't parse again if not needed\n if (this.parsed) return;\n options = options || {};\n\n this.index = 4;\n // Allow the return of raw documents instead of parsing\n const raw = options.raw || false;\n const documentsReturnedIn = options.documentsReturnedIn || null;\n const promoteLongs =\n typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs;\n const promoteValues =\n typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues;\n const promoteBuffers =\n typeof options.promoteBuffers === 'boolean'\n ? options.promoteBuffers\n : this.opts.promoteBuffers;\n\n // Set up the options\n const _options = {\n promoteLongs: promoteLongs,\n promoteValues: promoteValues,\n promoteBuffers: promoteBuffers\n };\n\n while (this.index < this.data.length) {\n const payloadType = this.data.readUInt8(this.index++);\n if (payloadType === 1) {\n console.error('TYPE 1');\n } else if (payloadType === 0) {\n const bsonSize = this.data.readUInt32LE(this.index);\n const bin = this.data.slice(this.index, this.index + bsonSize);\n this.documents.push(raw ? bin : this.bson.deserialize(bin, _options));\n\n this.index += bsonSize;\n }\n }\n\n if (this.documents.length === 1 && documentsReturnedIn != null && raw) {\n const fieldsAsRaw = {};\n fieldsAsRaw[documentsReturnedIn] = true;\n _options.fieldsAsRaw = fieldsAsRaw;\n\n const doc = this.bson.deserialize(this.documents[0], _options);\n this.documents = [doc];\n }\n\n this.parsed = true;\n }\n}\n\nmodule.exports = { Msg, BinMsg };\n","'use strict';\n\nconst inherits = require('util').inherits;\nconst EventEmitter = require('events').EventEmitter;\nconst MongoError = require('../error').MongoError;\nconst MongoTimeoutError = require('../error').MongoTimeoutError;\nconst MongoWriteConcernError = require('../error').MongoWriteConcernError;\nconst Logger = require('./logger');\nconst f = require('util').format;\nconst Msg = require('./msg').Msg;\nconst CommandResult = require('./command_result');\nconst MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE;\nconst COMPRESSION_DETAILS_SIZE = require('../wireprotocol/shared').COMPRESSION_DETAILS_SIZE;\nconst opcodes = require('../wireprotocol/shared').opcodes;\nconst compress = require('../wireprotocol/compression').compress;\nconst compressorIDs = require('../wireprotocol/compression').compressorIDs;\nconst uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands;\nconst apm = require('./apm');\nconst Buffer = require('safe-buffer').Buffer;\nconst connect = require('./connect');\nconst updateSessionFromResponse = require('../sessions').updateSessionFromResponse;\nconst eachAsync = require('../utils').eachAsync;\nconst makeStateMachine = require('../utils').makeStateMachine;\nconst now = require('../../utils').now;\n\nconst DISCONNECTED = 'disconnected';\nconst CONNECTING = 'connecting';\nconst CONNECTED = 'connected';\nconst DRAINING = 'draining';\nconst DESTROYING = 'destroying';\nconst DESTROYED = 'destroyed';\nconst stateTransition = makeStateMachine({\n [DISCONNECTED]: [CONNECTING, DRAINING, DISCONNECTED],\n [CONNECTING]: [CONNECTING, CONNECTED, DRAINING, DISCONNECTED],\n [CONNECTED]: [CONNECTED, DISCONNECTED, DRAINING],\n [DRAINING]: [DRAINING, DESTROYING, DESTROYED],\n [DESTROYING]: [DESTROYING, DESTROYED],\n [DESTROYED]: [DESTROYED]\n});\n\nconst CONNECTION_EVENTS = new Set([\n 'error',\n 'close',\n 'timeout',\n 'parseError',\n 'connect',\n 'message'\n]);\n\nvar _id = 0;\n\n/**\n * Creates a new Pool instance\n * @class\n * @param {string} options.host The server host\n * @param {number} options.port The server port\n * @param {number} [options.size=5] Max server connection pool size\n * @param {number} [options.minSize=0] Minimum server connection pool size\n * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection\n * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times\n * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries\n * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled\n * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled\n * @param {boolean} [options.noDelay=true] TCP Connection no delay\n * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting\n * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting\n * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket\n * @param {boolean} [options.ssl=false] Use SSL for connection\n * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.\n * @param {Buffer} [options.ca] SSL Certificate store binary buffer\n * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer\n * @param {Buffer} [options.cert] SSL Certificate binary buffer\n * @param {Buffer} [options.key] SSL Key file binary buffer\n * @param {string} [options.passphrase] SSL Certificate pass phrase\n * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates\n * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits\n * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.\n * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.\n * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.\n * @fires Pool#connect\n * @fires Pool#close\n * @fires Pool#error\n * @fires Pool#timeout\n * @fires Pool#parseError\n * @return {Pool} A cursor instance\n */\nvar Pool = function(topology, options) {\n // Add event listener\n EventEmitter.call(this);\n\n // Store topology for later use\n this.topology = topology;\n\n this.s = {\n state: DISCONNECTED,\n cancellationToken: new EventEmitter()\n };\n\n // we don't care how many connections are listening for cancellation\n this.s.cancellationToken.setMaxListeners(Infinity);\n\n // Add the options\n this.options = Object.assign(\n {\n // Host and port settings\n host: 'localhost',\n port: 27017,\n // Pool default max size\n size: 5,\n // Pool default min size\n minSize: 0,\n // socket settings\n connectionTimeout: 30000,\n socketTimeout: 360000,\n keepAlive: true,\n keepAliveInitialDelay: 120000,\n noDelay: true,\n // SSL Settings\n ssl: false,\n checkServerIdentity: true,\n ca: null,\n crl: null,\n cert: null,\n key: null,\n passphrase: null,\n rejectUnauthorized: false,\n promoteLongs: true,\n promoteValues: true,\n promoteBuffers: false,\n // Reconnection options\n reconnect: true,\n reconnectInterval: 1000,\n reconnectTries: 30,\n // Enable domains\n domainsEnabled: false,\n // feature flag for determining if we are running with the unified topology or not\n legacyCompatMode: true\n },\n options\n );\n\n // Identification information\n this.id = _id++;\n // Current reconnect retries\n this.retriesLeft = this.options.reconnectTries;\n this.reconnectId = null;\n this.reconnectError = null;\n // No bson parser passed in\n if (\n !options.bson ||\n (options.bson &&\n (typeof options.bson.serialize !== 'function' ||\n typeof options.bson.deserialize !== 'function'))\n ) {\n throw new Error('must pass in valid bson parser');\n }\n\n // Logger instance\n this.logger = Logger('Pool', options);\n // Connections\n this.availableConnections = [];\n this.inUseConnections = [];\n this.connectingConnections = 0;\n // Currently executing\n this.executing = false;\n // Operation work queue\n this.queue = [];\n\n // Number of consecutive timeouts caught\n this.numberOfConsecutiveTimeouts = 0;\n // Current pool Index\n this.connectionIndex = 0;\n\n // event handlers\n const pool = this;\n this._messageHandler = messageHandler(this);\n this._connectionCloseHandler = function(err) {\n const connection = this;\n connectionFailureHandler(pool, 'close', err, connection);\n };\n\n this._connectionErrorHandler = function(err) {\n const connection = this;\n connectionFailureHandler(pool, 'error', err, connection);\n };\n\n this._connectionTimeoutHandler = function(err) {\n const connection = this;\n connectionFailureHandler(pool, 'timeout', err, connection);\n };\n\n this._connectionParseErrorHandler = function(err) {\n const connection = this;\n connectionFailureHandler(pool, 'parseError', err, connection);\n };\n};\n\ninherits(Pool, EventEmitter);\n\nObject.defineProperty(Pool.prototype, 'size', {\n enumerable: true,\n get: function() {\n return this.options.size;\n }\n});\n\nObject.defineProperty(Pool.prototype, 'minSize', {\n enumerable: true,\n get: function() {\n return this.options.minSize;\n }\n});\n\nObject.defineProperty(Pool.prototype, 'connectionTimeout', {\n enumerable: true,\n get: function() {\n return this.options.connectionTimeout;\n }\n});\n\nObject.defineProperty(Pool.prototype, 'socketTimeout', {\n enumerable: true,\n get: function() {\n return this.options.socketTimeout;\n }\n});\n\nObject.defineProperty(Pool.prototype, 'state', {\n enumerable: true,\n get: function() {\n return this.s.state;\n }\n});\n\n// clears all pool state\nfunction resetPoolState(pool) {\n pool.inUseConnections = [];\n pool.availableConnections = [];\n pool.connectingConnections = 0;\n pool.executing = false;\n pool.numberOfConsecutiveTimeouts = 0;\n pool.connectionIndex = 0;\n pool.retriesLeft = pool.options.reconnectTries;\n pool.reconnectId = null;\n}\n\nfunction connectionFailureHandler(pool, event, err, conn) {\n if (conn) {\n if (conn._connectionFailHandled) {\n return;\n }\n\n conn._connectionFailHandled = true;\n conn.destroy();\n\n // Remove the connection\n removeConnection(pool, conn);\n\n // flush remaining work items\n conn.flush(err);\n }\n\n // Did we catch a timeout, increment the numberOfConsecutiveTimeouts\n if (event === 'timeout') {\n pool.numberOfConsecutiveTimeouts = pool.numberOfConsecutiveTimeouts + 1;\n\n // Have we timed out more than reconnectTries in a row ?\n // Force close the pool as we are trying to connect to tcp sink hole\n if (pool.numberOfConsecutiveTimeouts > pool.options.reconnectTries) {\n pool.numberOfConsecutiveTimeouts = 0;\n // Destroy all connections and pool\n pool.destroy(true);\n // Emit close event\n return pool.emit('close', pool);\n }\n }\n\n // No more socket available propegate the event\n if (pool.socketCount() === 0) {\n if (pool.state !== DESTROYED && pool.state !== DESTROYING && pool.state !== DRAINING) {\n if (pool.options.reconnect) {\n stateTransition(pool, DISCONNECTED);\n }\n }\n\n // Do not emit error events, they are always close events\n // do not trigger the low level error handler in node\n event = event === 'error' ? 'close' : event;\n pool.emit(event, err);\n }\n\n // Start reconnection attempts\n if (!pool.reconnectId && pool.options.reconnect) {\n pool.reconnectError = err;\n pool.reconnectId = setTimeout(attemptReconnect(pool), pool.options.reconnectInterval);\n }\n\n // Do we need to do anything to maintain the minimum pool size\n const totalConnections = totalConnectionCount(pool);\n if (totalConnections < pool.minSize) {\n createConnection(pool);\n }\n}\n\nfunction attemptReconnect(pool, callback) {\n return function() {\n pool.emit('attemptReconnect', pool);\n\n if (pool.state === DESTROYED || pool.state === DESTROYING) {\n if (typeof callback === 'function') {\n callback(new MongoError('Cannot create connection when pool is destroyed'));\n }\n\n return;\n }\n\n pool.retriesLeft = pool.retriesLeft - 1;\n if (pool.retriesLeft <= 0) {\n pool.destroy();\n\n const error = new MongoTimeoutError(\n `failed to reconnect after ${pool.options.reconnectTries} attempts with interval ${pool.options.reconnectInterval} ms`,\n pool.reconnectError\n );\n\n pool.emit('reconnectFailed', error);\n if (typeof callback === 'function') {\n callback(error);\n }\n\n return;\n }\n\n // clear the reconnect id on retry\n pool.reconnectId = null;\n\n // now retry creating a connection\n createConnection(pool, (err, conn) => {\n if (err == null) {\n pool.reconnectId = null;\n pool.retriesLeft = pool.options.reconnectTries;\n pool.emit('reconnect', pool);\n }\n\n if (typeof callback === 'function') {\n callback(err, conn);\n }\n });\n };\n}\n\nfunction moveConnectionBetween(connection, from, to) {\n var index = from.indexOf(connection);\n // Move the connection from connecting to available\n if (index !== -1) {\n from.splice(index, 1);\n to.push(connection);\n }\n}\n\nfunction messageHandler(self) {\n return function(message, connection) {\n // workItem to execute\n var workItem = null;\n\n // Locate the workItem\n for (var i = 0; i < connection.workItems.length; i++) {\n if (connection.workItems[i].requestId === message.responseTo) {\n // Get the callback\n workItem = connection.workItems[i];\n // Remove from list of workItems\n connection.workItems.splice(i, 1);\n }\n }\n\n if (workItem && workItem.monitoring) {\n moveConnectionBetween(connection, self.inUseConnections, self.availableConnections);\n }\n\n // Reset timeout counter\n self.numberOfConsecutiveTimeouts = 0;\n\n // Reset the connection timeout if we modified it for\n // this operation\n if (workItem && workItem.socketTimeout) {\n connection.resetSocketTimeout();\n }\n\n // Log if debug enabled\n if (self.logger.isDebug()) {\n self.logger.debug(\n f(\n 'message [%s] received from %s:%s',\n message.raw.toString('hex'),\n self.options.host,\n self.options.port\n )\n );\n }\n\n function handleOperationCallback(self, cb, err, result) {\n // No domain enabled\n if (!self.options.domainsEnabled) {\n return process.nextTick(function() {\n return cb(err, result);\n });\n }\n\n // Domain enabled just call the callback\n cb(err, result);\n }\n\n // Keep executing, ensure current message handler does not stop execution\n if (!self.executing) {\n process.nextTick(function() {\n _execute(self)();\n });\n }\n\n // Time to dispatch the message if we have a callback\n if (workItem && !workItem.immediateRelease) {\n try {\n // Parse the message according to the provided options\n message.parse(workItem);\n } catch (err) {\n return handleOperationCallback(self, workItem.cb, new MongoError(err));\n }\n\n if (message.documents[0]) {\n const document = message.documents[0];\n const session = workItem.session;\n if (session) {\n updateSessionFromResponse(session, document);\n }\n\n if (self.topology && document.$clusterTime) {\n self.topology.clusterTime = document.$clusterTime;\n }\n }\n\n // Establish if we have an error\n if (workItem.command && message.documents[0]) {\n const responseDoc = message.documents[0];\n\n if (responseDoc.writeConcernError) {\n const err = new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc);\n return handleOperationCallback(self, workItem.cb, err);\n }\n\n if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) {\n return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc));\n }\n }\n\n // Add the connection details\n message.hashedName = connection.hashedName;\n\n // Return the documents\n handleOperationCallback(\n self,\n workItem.cb,\n null,\n new CommandResult(workItem.fullResult ? message : message.documents[0], connection, message)\n );\n }\n };\n}\n\n/**\n * Return the total socket count in the pool.\n * @method\n * @return {Number} The number of socket available.\n */\nPool.prototype.socketCount = function() {\n return this.availableConnections.length + this.inUseConnections.length;\n // + this.connectingConnections.length;\n};\n\nfunction totalConnectionCount(pool) {\n return (\n pool.availableConnections.length + pool.inUseConnections.length + pool.connectingConnections\n );\n}\n\n/**\n * Return all pool connections\n * @method\n * @return {Connection[]} The pool connections\n */\nPool.prototype.allConnections = function() {\n return this.availableConnections.concat(this.inUseConnections);\n};\n\n/**\n * Get a pool connection (round-robin)\n * @method\n * @return {Connection}\n */\nPool.prototype.get = function() {\n return this.allConnections()[0];\n};\n\n/**\n * Is the pool connected\n * @method\n * @return {boolean}\n */\nPool.prototype.isConnected = function() {\n // We are in a destroyed state\n if (this.state === DESTROYED || this.state === DESTROYING) {\n return false;\n }\n\n // Get connections\n var connections = this.availableConnections.concat(this.inUseConnections);\n\n // Check if we have any connected connections\n for (var i = 0; i < connections.length; i++) {\n if (connections[i].isConnected()) return true;\n }\n\n // Not connected\n return false;\n};\n\n/**\n * Was the pool destroyed\n * @method\n * @return {boolean}\n */\nPool.prototype.isDestroyed = function() {\n return this.state === DESTROYED || this.state === DESTROYING;\n};\n\n/**\n * Is the pool in a disconnected state\n * @method\n * @return {boolean}\n */\nPool.prototype.isDisconnected = function() {\n return this.state === DISCONNECTED;\n};\n\n/**\n * Connect pool\n */\nPool.prototype.connect = function(callback) {\n if (this.state !== DISCONNECTED) {\n throw new MongoError('connection in unlawful state ' + this.state);\n }\n\n stateTransition(this, CONNECTING);\n createConnection(this, (err, conn) => {\n if (err) {\n if (typeof callback === 'function') {\n this.destroy();\n callback(err);\n return;\n }\n\n if (this.state === CONNECTING) {\n this.emit('error', err);\n }\n\n this.destroy();\n return;\n }\n\n stateTransition(this, CONNECTED);\n\n // create min connections\n if (this.minSize) {\n for (let i = 0; i < this.minSize; i++) {\n createConnection(this);\n }\n }\n\n if (typeof callback === 'function') {\n callback(null, conn);\n } else {\n this.emit('connect', this, conn);\n }\n });\n};\n\n/**\n * Authenticate using a specified mechanism\n * @param {authResultCallback} callback A callback function\n */\nPool.prototype.auth = function(credentials, callback) {\n if (typeof callback === 'function') callback(null, null);\n};\n\n/**\n * Logout all users against a database\n * @param {authResultCallback} callback A callback function\n */\nPool.prototype.logout = function(dbName, callback) {\n if (typeof callback === 'function') callback(null, null);\n};\n\n/**\n * Unref the pool\n * @method\n */\nPool.prototype.unref = function() {\n // Get all the known connections\n var connections = this.availableConnections.concat(this.inUseConnections);\n\n connections.forEach(function(c) {\n c.unref();\n });\n};\n\n// Destroy the connections\nfunction destroy(self, connections, options, callback) {\n stateTransition(self, DESTROYING);\n\n // indicate that in-flight connections should cancel\n self.s.cancellationToken.emit('cancel');\n\n eachAsync(\n connections,\n (conn, cb) => {\n for (const eventName of CONNECTION_EVENTS) {\n conn.removeAllListeners(eventName);\n }\n\n // ignore any errors during destruction\n conn.on('error', () => {});\n\n conn.destroy(options, cb);\n },\n err => {\n if (err) {\n if (typeof callback === 'function') callback(err, null);\n return;\n }\n\n resetPoolState(self);\n self.queue = [];\n\n stateTransition(self, DESTROYED);\n if (typeof callback === 'function') callback(null, null);\n }\n );\n}\n\n/**\n * Destroy pool\n * @method\n */\nPool.prototype.destroy = function(force, callback) {\n var self = this;\n if (typeof force === 'function') {\n callback = force;\n force = false;\n }\n\n // Do not try again if the pool is already dead\n if (this.state === DESTROYED || self.state === DESTROYING) {\n if (typeof callback === 'function') callback(null, null);\n return;\n }\n\n // Set state to draining\n stateTransition(this, DRAINING);\n\n // Are we force closing\n if (force) {\n // Get all the known connections\n var connections = self.availableConnections.concat(self.inUseConnections);\n\n // Flush any remaining work items with\n // an error\n while (self.queue.length > 0) {\n var workItem = self.queue.shift();\n if (typeof workItem.cb === 'function') {\n workItem.cb(new MongoError('Pool was force destroyed'));\n }\n }\n\n // Destroy the topology\n return destroy(self, connections, { force: true }, callback);\n }\n\n // Clear out the reconnect if set\n if (this.reconnectId) {\n clearTimeout(this.reconnectId);\n }\n\n // Wait for the operations to drain before we close the pool\n function checkStatus() {\n if (self.state === DESTROYED || self.state === DESTROYING) {\n if (typeof callback === 'function') {\n callback();\n }\n\n return;\n }\n\n flushMonitoringOperations(self.queue);\n\n if (self.queue.length === 0) {\n // Get all the known connections\n var connections = self.availableConnections.concat(self.inUseConnections);\n\n // Check if we have any in flight operations\n for (var i = 0; i < connections.length; i++) {\n // There is an operation still in flight, reschedule a\n // check waiting for it to drain\n if (connections[i].workItems.length > 0) {\n return setTimeout(checkStatus, 1);\n }\n }\n\n destroy(self, connections, { force: false }, callback);\n } else {\n // Ensure we empty the queue\n _execute(self)();\n // Set timeout\n setTimeout(checkStatus, 1);\n }\n }\n\n // Initiate drain of operations\n checkStatus();\n};\n\n/**\n * Reset all connections of this pool\n *\n * @param {function} [callback]\n */\nPool.prototype.reset = function(callback) {\n if (this.s.state !== CONNECTED) {\n if (typeof callback === 'function') {\n callback(new MongoError('pool is not connected, reset aborted'));\n }\n\n return;\n }\n\n // signal in-flight connections should be cancelled\n this.s.cancellationToken.emit('cancel');\n\n // destroy existing connections\n const connections = this.availableConnections.concat(this.inUseConnections);\n eachAsync(\n connections,\n (conn, cb) => {\n for (const eventName of CONNECTION_EVENTS) {\n conn.removeAllListeners(eventName);\n }\n\n conn.destroy({ force: true }, cb);\n },\n err => {\n if (err) {\n if (typeof callback === 'function') {\n callback(err, null);\n return;\n }\n }\n\n resetPoolState(this);\n\n // create a new connection, this will ultimately trigger execution\n createConnection(this, () => {\n if (typeof callback === 'function') {\n callback(null, null);\n }\n });\n }\n );\n};\n\n// Prepare the buffer that Pool.prototype.write() uses to send to the server\nfunction serializeCommand(self, command, callback) {\n const originalCommandBuffer = command.toBin();\n\n // Check whether we and the server have agreed to use a compressor\n const shouldCompress = !!self.options.agreedCompressor;\n if (!shouldCompress || !canCompress(command)) {\n return callback(null, originalCommandBuffer);\n }\n\n // Transform originalCommandBuffer into OP_COMPRESSED\n const concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer);\n const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE);\n\n // Extract information needed for OP_COMPRESSED from the uncompressed message\n const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12);\n\n // Compress the message body\n compress(self, messageToBeCompressed, function(err, compressedMessage) {\n if (err) return callback(err, null);\n\n // Create the msgHeader of OP_COMPRESSED\n const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE);\n msgHeader.writeInt32LE(\n MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length,\n 0\n ); // messageLength\n msgHeader.writeInt32LE(command.requestId, 4); // requestID\n msgHeader.writeInt32LE(0, 8); // responseTo (zero)\n msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode\n\n // Create the compression details of OP_COMPRESSED\n const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE);\n compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode\n compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader\n compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID\n\n return callback(null, [msgHeader, compressionDetails, compressedMessage]);\n });\n}\n\n/**\n * Write a message to MongoDB\n * @method\n * @return {Connection}\n */\nPool.prototype.write = function(command, options, cb) {\n var self = this;\n // Ensure we have a callback\n if (typeof options === 'function') {\n cb = options;\n }\n\n // Always have options\n options = options || {};\n\n // We need to have a callback function unless the message returns no response\n if (!(typeof cb === 'function') && !options.noResponse) {\n throw new MongoError('write method must provide a callback');\n }\n\n // Pool was destroyed error out\n if (this.state === DESTROYED || this.state === DESTROYING) {\n cb(new MongoError('pool destroyed'));\n return;\n }\n\n if (this.state === DRAINING) {\n cb(new MongoError('pool is draining, new operations prohibited'));\n return;\n }\n\n if (this.options.domainsEnabled && process.domain && typeof cb === 'function') {\n // if we have a domain bind to it\n var oldCb = cb;\n cb = process.domain.bind(function() {\n // v8 - argumentsToArray one-liner\n var args = new Array(arguments.length);\n for (var i = 0; i < arguments.length; i++) {\n args[i] = arguments[i];\n }\n // bounce off event loop so domain switch takes place\n process.nextTick(function() {\n oldCb.apply(null, args);\n });\n });\n }\n\n // Do we have an operation\n var operation = {\n cb: cb,\n raw: false,\n promoteLongs: true,\n promoteValues: true,\n promoteBuffers: false,\n fullResult: false\n };\n\n // Set the options for the parsing\n operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true;\n operation.promoteValues =\n typeof options.promoteValues === 'boolean' ? options.promoteValues : true;\n operation.promoteBuffers =\n typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false;\n operation.raw = typeof options.raw === 'boolean' ? options.raw : false;\n operation.immediateRelease =\n typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false;\n operation.documentsReturnedIn = options.documentsReturnedIn;\n operation.command = typeof options.command === 'boolean' ? options.command : false;\n operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false;\n operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false;\n operation.session = options.session || null;\n\n // Optional per operation socketTimeout\n operation.socketTimeout = options.socketTimeout;\n operation.monitoring = options.monitoring;\n\n // Get the requestId\n operation.requestId = command.requestId;\n\n // If command monitoring is enabled we need to modify the callback here\n if (self.options.monitorCommands) {\n this.emit('commandStarted', new apm.CommandStartedEvent(this, command));\n\n operation.started = now();\n operation.cb = (err, reply) => {\n if (err) {\n self.emit(\n 'commandFailed',\n new apm.CommandFailedEvent(this, command, err, operation.started)\n );\n } else {\n if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) {\n self.emit(\n 'commandFailed',\n new apm.CommandFailedEvent(this, command, reply.result, operation.started)\n );\n } else {\n self.emit(\n 'commandSucceeded',\n new apm.CommandSucceededEvent(this, command, reply, operation.started)\n );\n }\n }\n\n if (typeof cb === 'function') cb(err, reply);\n };\n }\n\n // Prepare the operation buffer\n serializeCommand(self, command, (err, serializedBuffers) => {\n if (err) throw err;\n\n // Set the operation's buffer to the serialization of the commands\n operation.buffer = serializedBuffers;\n\n // If we have a monitoring operation schedule as the very first operation\n // Otherwise add to back of queue\n if (options.monitoring) {\n self.queue.unshift(operation);\n } else {\n self.queue.push(operation);\n }\n\n // Attempt to execute the operation\n if (!self.executing) {\n process.nextTick(function() {\n _execute(self)();\n });\n }\n });\n};\n\n// Return whether a command contains an uncompressible command term\n// Will return true if command contains no uncompressible command terms\nfunction canCompress(command) {\n const commandDoc = command instanceof Msg ? command.command : command.query;\n const commandName = Object.keys(commandDoc)[0];\n return !uncompressibleCommands.has(commandName);\n}\n\n// Remove connection method\nfunction remove(connection, connections) {\n for (var i = 0; i < connections.length; i++) {\n if (connections[i] === connection) {\n connections.splice(i, 1);\n return true;\n }\n }\n}\n\nfunction removeConnection(self, connection) {\n if (remove(connection, self.availableConnections)) return;\n if (remove(connection, self.inUseConnections)) return;\n}\n\nfunction createConnection(pool, callback) {\n if (pool.state === DESTROYED || pool.state === DESTROYING) {\n if (typeof callback === 'function') {\n callback(new MongoError('Cannot create connection when pool is destroyed'));\n }\n\n return;\n }\n\n pool.connectingConnections++;\n connect(pool.options, pool.s.cancellationToken, (err, connection) => {\n pool.connectingConnections--;\n\n if (err) {\n if (pool.logger.isDebug()) {\n pool.logger.debug(`connection attempt failed with error [${JSON.stringify(err)}]`);\n }\n\n // check if reconnect is enabled, and attempt retry if so\n if (!pool.reconnectId && pool.options.reconnect) {\n if (pool.state === CONNECTING && pool.options.legacyCompatMode) {\n callback(err);\n return;\n }\n\n pool.reconnectError = err;\n pool.reconnectId = setTimeout(\n attemptReconnect(pool, callback),\n pool.options.reconnectInterval\n );\n\n return;\n }\n\n if (typeof callback === 'function') {\n callback(err);\n }\n\n return;\n }\n\n // the pool might have been closed since we started creating the connection\n if (pool.state === DESTROYED || pool.state === DESTROYING) {\n if (typeof callback === 'function') {\n callback(new MongoError('Pool was destroyed after connection creation'));\n }\n\n connection.destroy();\n return;\n }\n\n // otherwise, connect relevant event handlers and add it to our available connections\n connection.on('error', pool._connectionErrorHandler);\n connection.on('close', pool._connectionCloseHandler);\n connection.on('timeout', pool._connectionTimeoutHandler);\n connection.on('parseError', pool._connectionParseErrorHandler);\n connection.on('message', pool._messageHandler);\n\n pool.availableConnections.push(connection);\n\n // if a callback was provided, return the connection\n if (typeof callback === 'function') {\n callback(null, connection);\n }\n\n // immediately execute any waiting work\n _execute(pool)();\n });\n}\n\nfunction flushMonitoringOperations(queue) {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].monitoring) {\n var workItem = queue[i];\n queue.splice(i, 1);\n workItem.cb(\n new MongoError({ message: 'no connection available for monitoring', driver: true })\n );\n }\n }\n}\n\nfunction _execute(self) {\n return function() {\n if (self.state === DESTROYED) return;\n // Already executing, skip\n if (self.executing) return;\n // Set pool as executing\n self.executing = true;\n\n // New pool connections are in progress, wait them to finish\n // before executing any more operation to ensure distribution of\n // operations\n if (self.connectingConnections > 0) {\n self.executing = false;\n return;\n }\n\n // As long as we have available connections\n // eslint-disable-next-line\n while (true) {\n // Total availble connections\n const totalConnections = totalConnectionCount(self);\n\n // No available connections available, flush any monitoring ops\n if (self.availableConnections.length === 0) {\n // Flush any monitoring operations\n flushMonitoringOperations(self.queue);\n\n // Try to create a new connection to execute stuck operation\n if (totalConnections < self.options.size && self.queue.length > 0) {\n createConnection(self);\n }\n\n break;\n }\n\n // No queue break\n if (self.queue.length === 0) {\n break;\n }\n\n var connection = null;\n const connections = self.availableConnections.filter(conn => conn.workItems.length === 0);\n\n // No connection found that has no work on it, just pick one for pipelining\n if (connections.length === 0) {\n connection =\n self.availableConnections[self.connectionIndex++ % self.availableConnections.length];\n } else {\n connection = connections[self.connectionIndex++ % connections.length];\n }\n\n // Is the connection connected\n if (!connection.isConnected()) {\n // Remove the disconnected connection\n removeConnection(self, connection);\n // Flush any monitoring operations in the queue, failing fast\n flushMonitoringOperations(self.queue);\n break;\n }\n\n // Get the next work item\n var workItem = self.queue.shift();\n\n // If we are monitoring we need to use a connection that is not\n // running another operation to avoid socket timeout changes\n // affecting an existing operation\n if (workItem.monitoring) {\n var foundValidConnection = false;\n\n for (let i = 0; i < self.availableConnections.length; i++) {\n // If the connection is connected\n // And there are no pending workItems on it\n // Then we can safely use it for monitoring.\n if (\n self.availableConnections[i].isConnected() &&\n self.availableConnections[i].workItems.length === 0\n ) {\n foundValidConnection = true;\n connection = self.availableConnections[i];\n break;\n }\n }\n\n // No safe connection found, attempt to grow the connections\n // if possible and break from the loop\n if (!foundValidConnection) {\n // Put workItem back on the queue\n self.queue.unshift(workItem);\n\n // Attempt to grow the pool if it's not yet maxsize\n if (totalConnections < self.options.size && self.queue.length > 0) {\n // Create a new connection\n createConnection(self);\n }\n\n // Re-execute the operation\n setTimeout(() => _execute(self)(), 10);\n break;\n }\n }\n\n // Don't execute operation until we have a full pool\n if (totalConnections < self.options.size) {\n // Connection has work items, then put it back on the queue\n // and create a new connection\n if (connection.workItems.length > 0) {\n // Lets put the workItem back on the list\n self.queue.unshift(workItem);\n // Create a new connection\n createConnection(self);\n // Break from the loop\n break;\n }\n }\n\n // Get actual binary commands\n var buffer = workItem.buffer;\n\n // If we are monitoring take the connection of the availableConnections\n if (workItem.monitoring) {\n moveConnectionBetween(connection, self.availableConnections, self.inUseConnections);\n }\n\n // Track the executing commands on the mongo server\n // as long as there is an expected response\n if (!workItem.noResponse) {\n connection.workItems.push(workItem);\n }\n\n // We have a custom socketTimeout\n if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') {\n connection.setSocketTimeout(workItem.socketTimeout);\n }\n\n // Capture if write was successful\n var writeSuccessful = true;\n\n // Put operation on the wire\n if (Array.isArray(buffer)) {\n for (let i = 0; i < buffer.length; i++) {\n writeSuccessful = connection.write(buffer[i]);\n }\n } else {\n writeSuccessful = connection.write(buffer);\n }\n\n // if the command is designated noResponse, call the callback immeditely\n if (workItem.noResponse && typeof workItem.cb === 'function') {\n workItem.cb(null, null);\n }\n\n if (writeSuccessful === false) {\n // If write not successful put back on queue\n self.queue.unshift(workItem);\n // Remove the disconnected connection\n removeConnection(self, connection);\n // Flush any monitoring operations in the queue, failing fast\n flushMonitoringOperations(self.queue);\n break;\n }\n }\n\n self.executing = false;\n };\n}\n\n// Make execution loop available for testing\nPool._execute = _execute;\n\n/**\n * A server connect event, used to verify that the connection is up and running\n *\n * @event Pool#connect\n * @type {Pool}\n */\n\n/**\n * A server reconnect event, used to verify that pool reconnected.\n *\n * @event Pool#reconnect\n * @type {Pool}\n */\n\n/**\n * The server connection closed, all pool connections closed\n *\n * @event Pool#close\n * @type {Pool}\n */\n\n/**\n * The server connection caused an error, all pool connections closed\n *\n * @event Pool#error\n * @type {Pool}\n */\n\n/**\n * The server connection timed out, all pool connections closed\n *\n * @event Pool#timeout\n * @type {Pool}\n */\n\n/**\n * The driver experienced an invalid message, all pool connections closed\n *\n * @event Pool#parseError\n * @type {Pool}\n */\n\n/**\n * The driver attempted to reconnect\n *\n * @event Pool#attemptReconnect\n * @type {Pool}\n */\n\n/**\n * The driver exhausted all reconnect attempts\n *\n * @event Pool#reconnectFailed\n * @type {Pool}\n */\n\nmodule.exports = Pool;\n","'use strict';\n\nconst require_optional = require('require_optional');\n\nfunction debugOptions(debugFields, options) {\n var finaloptions = {};\n debugFields.forEach(function(n) {\n finaloptions[n] = options[n];\n });\n\n return finaloptions;\n}\n\nfunction retrieveBSON() {\n var BSON = require('bson');\n BSON.native = false;\n\n try {\n var optionalBSON = require_optional('bson-ext');\n if (optionalBSON) {\n optionalBSON.native = true;\n return optionalBSON;\n }\n } catch (err) {} // eslint-disable-line\n\n return BSON;\n}\n\n// Throw an error if an attempt to use Snappy is made when Snappy is not installed\nfunction noSnappyWarning() {\n throw new Error(\n 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.'\n );\n}\n\n// Facilitate loading Snappy optionally\nfunction retrieveSnappy() {\n var snappy = null;\n try {\n snappy = require_optional('snappy');\n } catch (error) {} // eslint-disable-line\n if (!snappy) {\n snappy = {\n compress: noSnappyWarning,\n uncompress: noSnappyWarning,\n compressSync: noSnappyWarning,\n uncompressSync: noSnappyWarning\n };\n }\n return snappy;\n}\n\nmodule.exports = {\n debugOptions,\n retrieveBSON,\n retrieveSnappy\n};\n","'use strict';\n\nconst Logger = require('./connection/logger');\nconst retrieveBSON = require('./connection/utils').retrieveBSON;\nconst MongoError = require('./error').MongoError;\nconst MongoNetworkError = require('./error').MongoNetworkError;\nconst collationNotSupported = require('./utils').collationNotSupported;\nconst ReadPreference = require('./topologies/read_preference');\nconst isUnifiedTopology = require('./utils').isUnifiedTopology;\nconst executeOperation = require('../operations/execute_operation');\nconst Readable = require('stream').Readable;\nconst SUPPORTS = require('../utils').SUPPORTS;\nconst MongoDBNamespace = require('../utils').MongoDBNamespace;\nconst OperationBase = require('../operations/operation').OperationBase;\n\nconst BSON = retrieveBSON();\nconst Long = BSON.Long;\n\n// Possible states for a cursor\nconst CursorState = {\n INIT: 0,\n OPEN: 1,\n CLOSED: 2,\n GET_MORE: 3\n};\n\n//\n// Handle callback (including any exceptions thrown)\nfunction handleCallback(callback, err, result) {\n try {\n callback(err, result);\n } catch (err) {\n process.nextTick(function() {\n throw err;\n });\n }\n}\n\n/**\n * This is a cursor results callback\n *\n * @callback resultCallback\n * @param {error} error An error object. Set to null if no error present\n * @param {object} document\n */\n\n/**\n * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB\n * allowing for iteration over the results returned from the underlying query.\n *\n * **CURSORS Cannot directly be instantiated**\n */\n\n/**\n * The core cursor class. All cursors in the driver build off of this one.\n *\n * @property {number} cursorBatchSize The current cursorBatchSize for the cursor\n * @property {number} cursorLimit The current cursorLimit for the cursor\n * @property {number} cursorSkip The current cursorSkip for the cursor\n */\nclass CoreCursor extends Readable {\n /**\n * Create a new core `Cursor` instance.\n * **NOTE** Not to be instantiated directly\n *\n * @param {object} topology The server topology instance.\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {{object}|Long} cmd The selector (can be a command or a cursorId)\n * @param {object} [options=null] Optional settings.\n * @param {object} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/| find command documentation} and {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @param {array} [options.documents=[]] Initial documents list for cursor\n * @param {object} [options.transforms=null] Transform methods for the cursor results\n * @param {function} [options.transforms.query] Transform the value returned from the initial query\n * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype._next\n */\n constructor(topology, ns, cmd, options) {\n super({ objectMode: true });\n options = options || {};\n\n if (ns instanceof OperationBase) {\n this.operation = ns;\n ns = this.operation.ns.toString();\n options = this.operation.options;\n cmd = this.operation.cmd ? this.operation.cmd : {};\n }\n\n // Cursor pool\n this.pool = null;\n // Cursor server\n this.server = null;\n\n // Do we have a not connected handler\n this.disconnectHandler = options.disconnectHandler;\n\n // Set local values\n this.bson = topology.s.bson;\n this.ns = ns;\n this.namespace = MongoDBNamespace.fromString(ns);\n this.cmd = cmd;\n this.options = options;\n this.topology = topology;\n\n // All internal state\n this.cursorState = {\n cursorId: null,\n cmd,\n documents: options.documents || [],\n cursorIndex: 0,\n dead: false,\n killed: false,\n init: false,\n notified: false,\n limit: options.limit || cmd.limit || 0,\n skip: options.skip || cmd.skip || 0,\n batchSize: options.batchSize || cmd.batchSize || 1000,\n currentLimit: 0,\n // Result field name if not a cursor (contains the array of results)\n transforms: options.transforms,\n raw: options.raw || (cmd && cmd.raw)\n };\n\n if (typeof options.session === 'object') {\n this.cursorState.session = options.session;\n }\n\n // Add promoteLong to cursor state\n const topologyOptions = topology.s.options;\n if (typeof topologyOptions.promoteLongs === 'boolean') {\n this.cursorState.promoteLongs = topologyOptions.promoteLongs;\n } else if (typeof options.promoteLongs === 'boolean') {\n this.cursorState.promoteLongs = options.promoteLongs;\n }\n\n // Add promoteValues to cursor state\n if (typeof topologyOptions.promoteValues === 'boolean') {\n this.cursorState.promoteValues = topologyOptions.promoteValues;\n } else if (typeof options.promoteValues === 'boolean') {\n this.cursorState.promoteValues = options.promoteValues;\n }\n\n // Add promoteBuffers to cursor state\n if (typeof topologyOptions.promoteBuffers === 'boolean') {\n this.cursorState.promoteBuffers = topologyOptions.promoteBuffers;\n } else if (typeof options.promoteBuffers === 'boolean') {\n this.cursorState.promoteBuffers = options.promoteBuffers;\n }\n\n if (topologyOptions.reconnect) {\n this.cursorState.reconnect = topologyOptions.reconnect;\n }\n\n // Logger\n this.logger = Logger('Cursor', topologyOptions);\n\n //\n // Did we pass in a cursor id\n if (typeof cmd === 'number') {\n this.cursorState.cursorId = Long.fromNumber(cmd);\n this.cursorState.lastCursorId = this.cursorState.cursorId;\n } else if (cmd instanceof Long) {\n this.cursorState.cursorId = cmd;\n this.cursorState.lastCursorId = cmd;\n }\n\n // TODO: remove as part of NODE-2104\n if (this.operation) {\n this.operation.cursorState = this.cursorState;\n }\n }\n\n setCursorBatchSize(value) {\n this.cursorState.batchSize = value;\n }\n\n cursorBatchSize() {\n return this.cursorState.batchSize;\n }\n\n setCursorLimit(value) {\n this.cursorState.limit = value;\n }\n\n cursorLimit() {\n return this.cursorState.limit;\n }\n\n setCursorSkip(value) {\n this.cursorState.skip = value;\n }\n\n cursorSkip() {\n return this.cursorState.skip;\n }\n\n /**\n * Retrieve the next document from the cursor\n * @method\n * @param {resultCallback} callback A callback function\n */\n _next(callback) {\n nextFunction(this, callback);\n }\n\n /**\n * Clone the cursor\n * @method\n * @return {Cursor}\n */\n clone() {\n return this.topology.cursor(this.ns, this.cmd, this.options);\n }\n\n /**\n * Checks if the cursor is dead\n * @method\n * @return {boolean} A boolean signifying if the cursor is dead or not\n */\n isDead() {\n return this.cursorState.dead === true;\n }\n\n /**\n * Checks if the cursor was killed by the application\n * @method\n * @return {boolean} A boolean signifying if the cursor was killed by the application\n */\n isKilled() {\n return this.cursorState.killed === true;\n }\n\n /**\n * Checks if the cursor notified it's caller about it's death\n * @method\n * @return {boolean} A boolean signifying if the cursor notified the callback\n */\n isNotified() {\n return this.cursorState.notified === true;\n }\n\n /**\n * Returns current buffered documents length\n * @method\n * @return {number} The number of items in the buffered documents\n */\n bufferedCount() {\n return this.cursorState.documents.length - this.cursorState.cursorIndex;\n }\n\n /**\n * Returns current buffered documents\n * @method\n * @return {Array} An array of buffered documents\n */\n readBufferedDocuments(number) {\n const unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex;\n const length = number < unreadDocumentsLength ? number : unreadDocumentsLength;\n let elements = this.cursorState.documents.slice(\n this.cursorState.cursorIndex,\n this.cursorState.cursorIndex + length\n );\n\n // Transform the doc with passed in transformation method if provided\n if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') {\n // Transform all the elements\n for (let i = 0; i < elements.length; i++) {\n elements[i] = this.cursorState.transforms.doc(elements[i]);\n }\n }\n\n // Ensure we do not return any more documents than the limit imposed\n // Just return the number of elements up to the limit\n if (\n this.cursorState.limit > 0 &&\n this.cursorState.currentLimit + elements.length > this.cursorState.limit\n ) {\n elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit);\n this.kill();\n }\n\n // Adjust current limit\n this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length;\n this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length;\n\n // Return elements\n return elements;\n }\n\n /**\n * Resets local state for this cursor instance, and issues a `killCursors` command to the server\n *\n * @param {resultCallback} callback A callback function\n */\n kill(callback) {\n // Set cursor to dead\n this.cursorState.dead = true;\n this.cursorState.killed = true;\n // Remove documents\n this.cursorState.documents = [];\n\n // If no cursor id just return\n if (\n this.cursorState.cursorId == null ||\n this.cursorState.cursorId.isZero() ||\n this.cursorState.init === false\n ) {\n if (callback) callback(null, null);\n return;\n }\n\n this.server.killCursors(this.ns, this.cursorState, callback);\n }\n\n /**\n * Resets the cursor\n */\n rewind() {\n if (this.cursorState.init) {\n if (!this.cursorState.dead) {\n this.kill();\n }\n\n this.cursorState.currentLimit = 0;\n this.cursorState.init = false;\n this.cursorState.dead = false;\n this.cursorState.killed = false;\n this.cursorState.notified = false;\n this.cursorState.documents = [];\n this.cursorState.cursorId = null;\n this.cursorState.cursorIndex = 0;\n }\n }\n\n // Internal methods\n _read() {\n if ((this.s && this.s.state === CursorState.CLOSED) || this.isDead()) {\n return this.push(null);\n }\n\n // Get the next item\n this._next((err, result) => {\n if (err) {\n if (this.listeners('error') && this.listeners('error').length > 0) {\n this.emit('error', err);\n }\n if (!this.isDead()) this.close();\n\n // Emit end event\n this.emit('end');\n return this.emit('finish');\n }\n\n // If we provided a transformation method\n if (\n this.cursorState.streamOptions &&\n typeof this.cursorState.streamOptions.transform === 'function' &&\n result != null\n ) {\n return this.push(this.cursorState.streamOptions.transform(result));\n }\n\n // Return the result\n this.push(result);\n\n if (result === null && this.isDead()) {\n this.once('end', () => {\n this.close();\n this.emit('finish');\n });\n }\n });\n }\n\n _endSession(options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n const session = this.cursorState.session;\n\n if (session && (options.force || session.owner === this)) {\n this.cursorState.session = undefined;\n\n if (this.operation) {\n this.operation.clearSession();\n }\n\n session.endSession(callback);\n return true;\n }\n\n if (callback) {\n callback();\n }\n\n return false;\n }\n\n _getMore(callback) {\n if (this.logger.isDebug()) {\n this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`);\n }\n\n // Set the current batchSize\n let batchSize = this.cursorState.batchSize;\n if (\n this.cursorState.limit > 0 &&\n this.cursorState.currentLimit + batchSize > this.cursorState.limit\n ) {\n batchSize = this.cursorState.limit - this.cursorState.currentLimit;\n }\n\n const cursorState = this.cursorState;\n this.server.getMore(this.ns, cursorState, batchSize, this.options, (err, result, conn) => {\n // NOTE: `getMore` modifies `cursorState`, would be very ideal not to do so in the future\n if (err || (cursorState.cursorId && cursorState.cursorId.isZero())) {\n this._endSession();\n }\n\n callback(err, result, conn);\n });\n }\n\n _initializeCursor(callback) {\n const cursor = this;\n\n // NOTE: this goes away once cursors use `executeOperation`\n if (isUnifiedTopology(cursor.topology) && cursor.topology.shouldCheckForSessionSupport()) {\n cursor.topology.selectServer(ReadPreference.primaryPreferred, err => {\n if (err) {\n callback(err);\n return;\n }\n\n this._initializeCursor(callback);\n });\n\n return;\n }\n\n function done(err, result) {\n const cursorState = cursor.cursorState;\n if (err || (cursorState.cursorId && cursorState.cursorId.isZero())) {\n cursor._endSession();\n }\n\n if (\n cursorState.documents.length === 0 &&\n cursorState.cursorId &&\n cursorState.cursorId.isZero() &&\n !cursor.cmd.tailable &&\n !cursor.cmd.awaitData\n ) {\n return setCursorNotified(cursor, callback);\n }\n\n callback(err, result);\n }\n\n const queryCallback = (err, r) => {\n if (err) {\n return done(err);\n }\n\n const result = r.message;\n\n if (Array.isArray(result.documents) && result.documents.length === 1) {\n const document = result.documents[0];\n\n if (result.queryFailure) {\n return done(new MongoError(document), null);\n }\n\n // Check if we have a command cursor\n if (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) {\n // We have an error document, return the error\n if (document.$err || document.errmsg) {\n return done(new MongoError(document), null);\n }\n\n // We have a cursor document\n if (document.cursor != null && typeof document.cursor !== 'string') {\n const id = document.cursor.id;\n // If we have a namespace change set the new namespace for getmores\n if (document.cursor.ns) {\n cursor.ns = document.cursor.ns;\n }\n // Promote id to long if needed\n cursor.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id;\n cursor.cursorState.lastCursorId = cursor.cursorState.cursorId;\n cursor.cursorState.operationTime = document.operationTime;\n\n // If we have a firstBatch set it\n if (Array.isArray(document.cursor.firstBatch)) {\n cursor.cursorState.documents = document.cursor.firstBatch; //.reverse();\n }\n\n // Return after processing command cursor\n return done(null, result);\n }\n }\n }\n\n // Otherwise fall back to regular find path\n const cursorId = result.cursorId || 0;\n cursor.cursorState.cursorId = cursorId instanceof Long ? cursorId : Long.fromNumber(cursorId);\n cursor.cursorState.documents = result.documents;\n cursor.cursorState.lastCursorId = result.cursorId;\n\n // Transform the results with passed in transformation method if provided\n if (\n cursor.cursorState.transforms &&\n typeof cursor.cursorState.transforms.query === 'function'\n ) {\n cursor.cursorState.documents = cursor.cursorState.transforms.query(result);\n }\n\n done(null, result);\n };\n\n if (cursor.operation) {\n if (cursor.logger.isDebug()) {\n cursor.logger.debug(\n `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify(\n cursor.query\n )}]`\n );\n }\n\n executeOperation(cursor.topology, cursor.operation, (err, result) => {\n if (err) {\n done(err);\n return;\n }\n\n cursor.server = cursor.operation.server;\n cursor.cursorState.init = true;\n\n // NOTE: this is a special internal method for cloning a cursor, consider removing\n if (cursor.cursorState.cursorId != null) {\n return done();\n }\n\n queryCallback(err, result);\n });\n\n return;\n }\n\n // Very explicitly choose what is passed to selectServer\n const serverSelectOptions = {};\n if (cursor.cursorState.session) {\n serverSelectOptions.session = cursor.cursorState.session;\n }\n\n if (cursor.operation) {\n serverSelectOptions.readPreference = cursor.operation.readPreference;\n } else if (cursor.options.readPreference) {\n serverSelectOptions.readPreference = cursor.options.readPreference;\n }\n\n return cursor.topology.selectServer(serverSelectOptions, (err, server) => {\n if (err) {\n const disconnectHandler = cursor.disconnectHandler;\n if (disconnectHandler != null) {\n return disconnectHandler.addObjectAndMethod(\n 'cursor',\n cursor,\n 'next',\n [callback],\n callback\n );\n }\n\n return callback(err);\n }\n\n cursor.server = server;\n cursor.cursorState.init = true;\n if (collationNotSupported(cursor.server, cursor.cmd)) {\n return callback(new MongoError(`server ${cursor.server.name} does not support collation`));\n }\n\n // NOTE: this is a special internal method for cloning a cursor, consider removing\n if (cursor.cursorState.cursorId != null) {\n return done();\n }\n\n if (cursor.logger.isDebug()) {\n cursor.logger.debug(\n `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify(\n cursor.query\n )}]`\n );\n }\n\n if (cursor.cmd.find != null) {\n server.query(cursor.ns, cursor.cmd, cursor.cursorState, cursor.options, queryCallback);\n return;\n }\n\n const commandOptions = Object.assign({ session: cursor.cursorState.session }, cursor.options);\n server.command(cursor.ns, cursor.cmd, commandOptions, queryCallback);\n });\n }\n}\n\nif (SUPPORTS.ASYNC_ITERATOR) {\n CoreCursor.prototype[Symbol.asyncIterator] = require('../async/async_iterator').asyncIterator;\n}\n\n/**\n * Validate if the pool is dead and return error\n */\nfunction isConnectionDead(self, callback) {\n if (self.pool && self.pool.isDestroyed()) {\n self.cursorState.killed = true;\n const err = new MongoNetworkError(\n `connection to host ${self.pool.host}:${self.pool.port} was destroyed`\n );\n\n _setCursorNotifiedImpl(self, () => callback(err));\n return true;\n }\n\n return false;\n}\n\n/**\n * Validate if the cursor is dead but was not explicitly killed by user\n */\nfunction isCursorDeadButNotkilled(self, callback) {\n // Cursor is dead but not marked killed, return null\n if (self.cursorState.dead && !self.cursorState.killed) {\n self.cursorState.killed = true;\n setCursorNotified(self, callback);\n return true;\n }\n\n return false;\n}\n\n/**\n * Validate if the cursor is dead and was killed by user\n */\nfunction isCursorDeadAndKilled(self, callback) {\n if (self.cursorState.dead && self.cursorState.killed) {\n handleCallback(callback, new MongoError('cursor is dead'));\n return true;\n }\n\n return false;\n}\n\n/**\n * Validate if the cursor was killed by the user\n */\nfunction isCursorKilled(self, callback) {\n if (self.cursorState.killed) {\n setCursorNotified(self, callback);\n return true;\n }\n\n return false;\n}\n\n/**\n * Mark cursor as being dead and notified\n */\nfunction setCursorDeadAndNotified(self, callback) {\n self.cursorState.dead = true;\n setCursorNotified(self, callback);\n}\n\n/**\n * Mark cursor as being notified\n */\nfunction setCursorNotified(self, callback) {\n _setCursorNotifiedImpl(self, () => handleCallback(callback, null, null));\n}\n\nfunction _setCursorNotifiedImpl(self, callback) {\n self.cursorState.notified = true;\n self.cursorState.documents = [];\n self.cursorState.cursorIndex = 0;\n\n if (self.cursorState.session) {\n self._endSession(callback);\n return;\n }\n\n return callback();\n}\n\nfunction nextFunction(self, callback) {\n // We have notified about it\n if (self.cursorState.notified) {\n return callback(new Error('cursor is exhausted'));\n }\n\n // Cursor is killed return null\n if (isCursorKilled(self, callback)) return;\n\n // Cursor is dead but not marked killed, return null\n if (isCursorDeadButNotkilled(self, callback)) return;\n\n // We have a dead and killed cursor, attempting to call next should error\n if (isCursorDeadAndKilled(self, callback)) return;\n\n // We have just started the cursor\n if (!self.cursorState.init) {\n // Topology is not connected, save the call in the provided store to be\n // Executed at some point when the handler deems it's reconnected\n if (!self.topology.isConnected(self.options)) {\n // Only need this for single server, because repl sets and mongos\n // will always continue trying to reconnect\n if (self.topology._type === 'server' && !self.topology.s.options.reconnect) {\n // Reconnect is disabled, so we'll never reconnect\n return callback(new MongoError('no connection available'));\n }\n\n if (self.disconnectHandler != null) {\n if (self.topology.isDestroyed()) {\n // Topology was destroyed, so don't try to wait for it to reconnect\n return callback(new MongoError('Topology was destroyed'));\n }\n\n self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback);\n return;\n }\n }\n\n self._initializeCursor((err, result) => {\n if (err || result === null) {\n callback(err, result);\n return;\n }\n\n nextFunction(self, callback);\n });\n\n return;\n }\n\n if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) {\n // Ensure we kill the cursor on the server\n self.kill(() =>\n // Set cursor in dead and notified state\n setCursorDeadAndNotified(self, callback)\n );\n } else if (\n self.cursorState.cursorIndex === self.cursorState.documents.length &&\n !Long.ZERO.equals(self.cursorState.cursorId)\n ) {\n // Ensure an empty cursor state\n self.cursorState.documents = [];\n self.cursorState.cursorIndex = 0;\n\n // Check if topology is destroyed\n if (self.topology.isDestroyed())\n return callback(\n new MongoNetworkError('connection destroyed, not possible to instantiate cursor')\n );\n\n // Check if connection is dead and return if not possible to\n // execute a getMore on this connection\n if (isConnectionDead(self, callback)) return;\n\n // Execute the next get more\n self._getMore(function(err, doc, connection) {\n if (err) {\n return handleCallback(callback, err);\n }\n\n // Save the returned connection to ensure all getMore's fire over the same connection\n self.connection = connection;\n\n // Tailable cursor getMore result, notify owner about it\n // No attempt is made here to retry, this is left to the user of the\n // core module to handle to keep core simple\n if (\n self.cursorState.documents.length === 0 &&\n self.cmd.tailable &&\n Long.ZERO.equals(self.cursorState.cursorId)\n ) {\n // No more documents in the tailed cursor\n return handleCallback(\n callback,\n new MongoError({\n message: 'No more documents in tailed cursor',\n tailable: self.cmd.tailable,\n awaitData: self.cmd.awaitData\n })\n );\n } else if (\n self.cursorState.documents.length === 0 &&\n self.cmd.tailable &&\n !Long.ZERO.equals(self.cursorState.cursorId)\n ) {\n return nextFunction(self, callback);\n }\n\n if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) {\n return setCursorDeadAndNotified(self, callback);\n }\n\n nextFunction(self, callback);\n });\n } else if (\n self.cursorState.documents.length === self.cursorState.cursorIndex &&\n self.cmd.tailable &&\n Long.ZERO.equals(self.cursorState.cursorId)\n ) {\n return handleCallback(\n callback,\n new MongoError({\n message: 'No more documents in tailed cursor',\n tailable: self.cmd.tailable,\n awaitData: self.cmd.awaitData\n })\n );\n } else if (\n self.cursorState.documents.length === self.cursorState.cursorIndex &&\n Long.ZERO.equals(self.cursorState.cursorId)\n ) {\n setCursorDeadAndNotified(self, callback);\n } else {\n if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) {\n // Ensure we kill the cursor on the server\n self.kill(() =>\n // Set cursor in dead and notified state\n setCursorDeadAndNotified(self, callback)\n );\n\n return;\n }\n\n // Increment the current cursor limit\n self.cursorState.currentLimit += 1;\n\n // Get the document\n let doc = self.cursorState.documents[self.cursorState.cursorIndex++];\n\n // Doc overflow\n if (!doc || doc.$err) {\n // Ensure we kill the cursor on the server\n self.kill(() =>\n // Set cursor in dead and notified state\n setCursorDeadAndNotified(self, function() {\n handleCallback(callback, new MongoError(doc ? doc.$err : undefined));\n })\n );\n\n return;\n }\n\n // Transform the doc with passed in transformation method if provided\n if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') {\n doc = self.cursorState.transforms.doc(doc);\n }\n\n // Return the document\n handleCallback(callback, null, doc);\n }\n}\n\nmodule.exports = {\n CursorState,\n CoreCursor\n};\n","'use strict';\n\nconst kErrorLabels = Symbol('errorLabels');\n\n/**\n * Creates a new MongoError\n *\n * @augments Error\n * @param {Error|string|object} message The error message\n * @property {string} message The error message\n * @property {string} stack The error call stack\n */\nclass MongoError extends Error {\n constructor(message) {\n if (message instanceof Error) {\n super(message.message);\n this.stack = message.stack;\n } else {\n if (typeof message === 'string') {\n super(message);\n } else {\n super(message.message || message.errmsg || message.$err || 'n/a');\n if (message.errorLabels) {\n this[kErrorLabels] = new Set(message.errorLabels);\n }\n\n for (var name in message) {\n if (name === 'errorLabels' || name === 'errmsg') {\n continue;\n }\n\n this[name] = message[name];\n }\n }\n\n Error.captureStackTrace(this, this.constructor);\n }\n\n this.name = 'MongoError';\n }\n\n /**\n * Legacy name for server error responses\n */\n get errmsg() {\n return this.message;\n }\n\n /**\n * Creates a new MongoError object\n *\n * @param {Error|string|object} options The options used to create the error.\n * @return {MongoError} A MongoError instance\n * @deprecated Use `new MongoError()` instead.\n */\n static create(options) {\n return new MongoError(options);\n }\n\n /**\n * Checks the error to see if it has an error label\n * @param {string} label The error label to check for\n * @returns {boolean} returns true if the error has the provided error label\n */\n hasErrorLabel(label) {\n if (this[kErrorLabels] == null) {\n return false;\n }\n\n return this[kErrorLabels].has(label);\n }\n\n addErrorLabel(label) {\n if (this[kErrorLabels] == null) {\n this[kErrorLabels] = new Set();\n }\n\n this[kErrorLabels].add(label);\n }\n\n get errorLabels() {\n return this[kErrorLabels] ? Array.from(this[kErrorLabels]) : [];\n }\n}\n\nconst kBeforeHandshake = Symbol('beforeHandshake');\nfunction isNetworkErrorBeforeHandshake(err) {\n return err[kBeforeHandshake] === true;\n}\n\n/**\n * An error indicating an issue with the network, including TCP\n * errors and timeouts.\n *\n * @param {Error|string|object} message The error message\n * @property {string} message The error message\n * @property {string} stack The error call stack\n * @extends MongoError\n */\nclass MongoNetworkError extends MongoError {\n constructor(message, options) {\n super(message);\n this.name = 'MongoNetworkError';\n\n if (options && options.beforeHandshake === true) {\n this[kBeforeHandshake] = true;\n }\n }\n}\n\n/**\n * An error indicating a network timeout occurred\n *\n * @param {Error|string|object} message The error message\n * @property {string} message The error message\n * @property {object} [options.beforeHandshake] Indicates the timeout happened before a connection handshake completed\n * @extends MongoError\n */\nclass MongoNetworkTimeoutError extends MongoNetworkError {\n constructor(message, options) {\n super(message, options);\n this.name = 'MongoNetworkTimeoutError';\n }\n}\n\n/**\n * An error used when attempting to parse a value (like a connection string)\n *\n * @param {Error|string|object} message The error message\n * @property {string} message The error message\n * @extends MongoError\n */\nclass MongoParseError extends MongoError {\n constructor(message) {\n super(message);\n this.name = 'MongoParseError';\n }\n}\n\n/**\n * An error signifying a client-side timeout event\n *\n * @param {Error|string|object} message The error message\n * @param {string|object} [reason] The reason the timeout occured\n * @property {string} message The error message\n * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers\n * @extends MongoError\n */\nclass MongoTimeoutError extends MongoError {\n constructor(message, reason) {\n if (reason && reason.error) {\n super(reason.error.message || reason.error);\n } else {\n super(message);\n }\n\n this.name = 'MongoTimeoutError';\n if (reason) {\n this.reason = reason;\n }\n }\n}\n\n/**\n * An error signifying a client-side server selection error\n *\n * @param {Error|string|object} message The error message\n * @param {string|object} [reason] The reason the timeout occured\n * @property {string} message The error message\n * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers\n * @extends MongoError\n */\nclass MongoServerSelectionError extends MongoTimeoutError {\n constructor(message, reason) {\n super(message, reason);\n this.name = 'MongoServerSelectionError';\n }\n}\n\nfunction makeWriteConcernResultObject(input) {\n const output = Object.assign({}, input);\n\n if (output.ok === 0) {\n output.ok = 1;\n delete output.errmsg;\n delete output.code;\n delete output.codeName;\n }\n\n return output;\n}\n\n/**\n * An error thrown when the server reports a writeConcernError\n *\n * @param {Error|string|object} message The error message\n * @param {object} result The result document (provided if ok: 1)\n * @property {string} message The error message\n * @property {object} [result] The result document (provided if ok: 1)\n * @extends MongoError\n */\nclass MongoWriteConcernError extends MongoError {\n constructor(message, result) {\n super(message);\n this.name = 'MongoWriteConcernError';\n\n if (result && Array.isArray(result.errorLabels)) {\n this[kErrorLabels] = new Set(result.errorLabels);\n }\n\n if (result != null) {\n this.result = makeWriteConcernResultObject(result);\n }\n }\n}\n\n// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms\nconst RETRYABLE_ERROR_CODES = new Set([\n 6, // HostUnreachable\n 7, // HostNotFound\n 89, // NetworkTimeout\n 91, // ShutdownInProgress\n 189, // PrimarySteppedDown\n 9001, // SocketException\n 10107, // NotMaster\n 11600, // InterruptedAtShutdown\n 11602, // InterruptedDueToReplStateChange\n 13435, // NotMasterNoSlaveOk\n 13436 // NotMasterOrSecondary\n]);\n\nconst RETRYABLE_WRITE_ERROR_CODES = new Set([\n 11600, // InterruptedAtShutdown\n 11602, // InterruptedDueToReplStateChange\n 10107, // NotMaster\n 13435, // NotMasterNoSlaveOk\n 13436, // NotMasterOrSecondary\n 189, // PrimarySteppedDown\n 91, // ShutdownInProgress\n 7, // HostNotFound\n 6, // HostUnreachable\n 89, // NetworkTimeout\n 9001, // SocketException\n 262 // ExceededTimeLimit\n]);\n\nfunction isRetryableWriteError(error) {\n if (error instanceof MongoWriteConcernError) {\n return (\n RETRYABLE_WRITE_ERROR_CODES.has(error.code) ||\n RETRYABLE_WRITE_ERROR_CODES.has(error.result.code)\n );\n }\n\n return RETRYABLE_WRITE_ERROR_CODES.has(error.code);\n}\n\n/**\n * Determines whether an error is something the driver should attempt to retry\n *\n * @ignore\n * @param {MongoError|Error} error\n */\nfunction isRetryableError(error) {\n return (\n RETRYABLE_ERROR_CODES.has(error.code) ||\n error instanceof MongoNetworkError ||\n error.message.match(/not master/) ||\n error.message.match(/node is recovering/)\n );\n}\n\nconst SDAM_RECOVERING_CODES = new Set([\n 91, // ShutdownInProgress\n 189, // PrimarySteppedDown\n 11600, // InterruptedAtShutdown\n 11602, // InterruptedDueToReplStateChange\n 13436 // NotMasterOrSecondary\n]);\n\nconst SDAM_NOTMASTER_CODES = new Set([\n 10107, // NotMaster\n 13435 // NotMasterNoSlaveOk\n]);\n\nconst SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([\n 11600, // InterruptedAtShutdown\n 91 // ShutdownInProgress\n]);\n\nfunction isRecoveringError(err) {\n if (err.code && SDAM_RECOVERING_CODES.has(err.code)) {\n return true;\n }\n\n return err.message.match(/not master or secondary/) || err.message.match(/node is recovering/);\n}\n\nfunction isNotMasterError(err) {\n if (err.code && SDAM_NOTMASTER_CODES.has(err.code)) {\n return true;\n }\n\n if (isRecoveringError(err)) {\n return false;\n }\n\n return err.message.match(/not master/);\n}\n\nfunction isNodeShuttingDownError(err) {\n return err.code && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code);\n}\n\n/**\n * Determines whether SDAM can recover from a given error. If it cannot\n * then the pool will be cleared, and server state will completely reset\n * locally.\n *\n * @ignore\n * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering\n * @param {MongoError|Error} error\n */\nfunction isSDAMUnrecoverableError(error) {\n // NOTE: null check is here for a strictly pre-CMAP world, a timeout or\n // close event are considered unrecoverable\n if (error instanceof MongoParseError || error == null) {\n return true;\n }\n\n if (isRecoveringError(error) || isNotMasterError(error)) {\n return true;\n }\n\n return false;\n}\n\nmodule.exports = {\n MongoError,\n MongoNetworkError,\n MongoNetworkTimeoutError,\n MongoParseError,\n MongoTimeoutError,\n MongoServerSelectionError,\n MongoWriteConcernError,\n isRetryableError,\n isSDAMUnrecoverableError,\n isNodeShuttingDownError,\n isRetryableWriteError,\n isNetworkErrorBeforeHandshake\n};\n","'use strict';\n\nlet BSON = require('bson');\nconst require_optional = require('require_optional');\nconst EJSON = require('./utils').retrieveEJSON();\n\ntry {\n // Attempt to grab the native BSON parser\n const BSONNative = require_optional('bson-ext');\n // If we got the native parser, use it instead of the\n // Javascript one\n if (BSONNative) {\n BSON = BSONNative;\n }\n} catch (err) {} // eslint-disable-line\n\nmodule.exports = {\n // Errors\n MongoError: require('./error').MongoError,\n MongoNetworkError: require('./error').MongoNetworkError,\n MongoParseError: require('./error').MongoParseError,\n MongoTimeoutError: require('./error').MongoTimeoutError,\n MongoServerSelectionError: require('./error').MongoServerSelectionError,\n MongoWriteConcernError: require('./error').MongoWriteConcernError,\n // Core\n Connection: require('./connection/connection'),\n Server: require('./topologies/server'),\n ReplSet: require('./topologies/replset'),\n Mongos: require('./topologies/mongos'),\n Logger: require('./connection/logger'),\n Cursor: require('./cursor').CoreCursor,\n ReadPreference: require('./topologies/read_preference'),\n Sessions: require('./sessions'),\n BSON: BSON,\n EJSON: EJSON,\n Topology: require('./sdam/topology').Topology,\n // Raw operations\n Query: require('./connection/commands').Query,\n // Auth mechanisms\n MongoCredentials: require('./auth/mongo_credentials').MongoCredentials,\n defaultAuthProviders: require('./auth/defaultAuthProviders').defaultAuthProviders,\n MongoCR: require('./auth/mongocr'),\n X509: require('./auth/x509'),\n Plain: require('./auth/plain'),\n GSSAPI: require('./auth/gssapi'),\n ScramSHA1: require('./auth/scram').ScramSHA1,\n ScramSHA256: require('./auth/scram').ScramSHA256,\n // Utilities\n parseConnectionString: require('./uri_parser')\n};\n","'use strict';\n\n// shared state names\nconst STATE_CLOSING = 'closing';\nconst STATE_CLOSED = 'closed';\nconst STATE_CONNECTING = 'connecting';\nconst STATE_CONNECTED = 'connected';\n\n// An enumeration of topology types we know about\nconst TopologyType = {\n Single: 'Single',\n ReplicaSetNoPrimary: 'ReplicaSetNoPrimary',\n ReplicaSetWithPrimary: 'ReplicaSetWithPrimary',\n Sharded: 'Sharded',\n Unknown: 'Unknown'\n};\n\n// An enumeration of server types we know about\nconst ServerType = {\n Standalone: 'Standalone',\n Mongos: 'Mongos',\n PossiblePrimary: 'PossiblePrimary',\n RSPrimary: 'RSPrimary',\n RSSecondary: 'RSSecondary',\n RSArbiter: 'RSArbiter',\n RSOther: 'RSOther',\n RSGhost: 'RSGhost',\n Unknown: 'Unknown'\n};\n\n// helper to get a server's type that works for both legacy and unified topologies\nfunction serverType(server) {\n let description = server.s.description || server.s.serverDescription;\n if (description.topologyType === TopologyType.Single) return description.servers[0].type;\n return description.type;\n}\n\nconst TOPOLOGY_DEFAULTS = {\n useUnifiedTopology: true,\n localThresholdMS: 15,\n serverSelectionTimeoutMS: 30000,\n heartbeatFrequencyMS: 10000,\n minHeartbeatFrequencyMS: 500\n};\n\nfunction drainTimerQueue(queue) {\n queue.forEach(clearTimeout);\n queue.clear();\n}\n\nfunction clearAndRemoveTimerFrom(timer, timers) {\n clearTimeout(timer);\n return timers.delete(timer);\n}\n\nmodule.exports = {\n STATE_CLOSING,\n STATE_CLOSED,\n STATE_CONNECTING,\n STATE_CONNECTED,\n TOPOLOGY_DEFAULTS,\n TopologyType,\n ServerType,\n serverType,\n drainTimerQueue,\n clearAndRemoveTimerFrom\n};\n","'use strict';\n\n/**\n * Published when server description changes, but does NOT include changes to the RTT.\n *\n * @property {Object} topologyId A unique identifier for the topology\n * @property {ServerAddress} address The address (host/port pair) of the server\n * @property {ServerDescription} previousDescription The previous server description\n * @property {ServerDescription} newDescription The new server description\n */\nclass ServerDescriptionChangedEvent {\n constructor(topologyId, address, previousDescription, newDescription) {\n Object.assign(this, { topologyId, address, previousDescription, newDescription });\n }\n}\n\n/**\n * Published when server is initialized.\n *\n * @property {Object} topologyId A unique identifier for the topology\n * @property {ServerAddress} address The address (host/port pair) of the server\n */\nclass ServerOpeningEvent {\n constructor(topologyId, address) {\n Object.assign(this, { topologyId, address });\n }\n}\n\n/**\n * Published when server is closed.\n *\n * @property {ServerAddress} address The address (host/port pair) of the server\n * @property {Object} topologyId A unique identifier for the topology\n */\nclass ServerClosedEvent {\n constructor(topologyId, address) {\n Object.assign(this, { topologyId, address });\n }\n}\n\n/**\n * Published when topology description changes.\n *\n * @property {Object} topologyId\n * @property {TopologyDescription} previousDescription The old topology description\n * @property {TopologyDescription} newDescription The new topology description\n */\nclass TopologyDescriptionChangedEvent {\n constructor(topologyId, previousDescription, newDescription) {\n Object.assign(this, { topologyId, previousDescription, newDescription });\n }\n}\n\n/**\n * Published when topology is initialized.\n *\n * @param {Object} topologyId A unique identifier for the topology\n */\nclass TopologyOpeningEvent {\n constructor(topologyId) {\n Object.assign(this, { topologyId });\n }\n}\n\n/**\n * Published when topology is closed.\n *\n * @param {Object} topologyId A unique identifier for the topology\n */\nclass TopologyClosedEvent {\n constructor(topologyId) {\n Object.assign(this, { topologyId });\n }\n}\n\n/**\n * Fired when the server monitor’s ismaster command is started - immediately before\n * the ismaster command is serialized into raw BSON and written to the socket.\n *\n * @property {Object} connectionId The connection id for the command\n */\nclass ServerHeartbeatStartedEvent {\n constructor(connectionId) {\n Object.assign(this, { connectionId });\n }\n}\n\n/**\n * Fired when the server monitor’s ismaster succeeds.\n *\n * @param {Number} duration The execution time of the event in ms\n * @param {Object} reply The command reply\n * @param {Object} connectionId The connection id for the command\n */\nclass ServerHeartbeatSucceededEvent {\n constructor(duration, reply, connectionId) {\n Object.assign(this, { connectionId, duration, reply });\n }\n}\n\n/**\n * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception.\n *\n * @param {Number} duration The execution time of the event in ms\n * @param {MongoError|Object} failure The command failure\n * @param {Object} connectionId The connection id for the command\n */\nclass ServerHeartbeatFailedEvent {\n constructor(duration, failure, connectionId) {\n Object.assign(this, { connectionId, duration, failure });\n }\n}\n\nmodule.exports = {\n ServerDescriptionChangedEvent,\n ServerOpeningEvent,\n ServerClosedEvent,\n TopologyDescriptionChangedEvent,\n TopologyOpeningEvent,\n TopologyClosedEvent,\n ServerHeartbeatStartedEvent,\n ServerHeartbeatSucceededEvent,\n ServerHeartbeatFailedEvent\n};\n","'use strict';\n\nconst ServerType = require('./common').ServerType;\nconst EventEmitter = require('events');\nconst connect = require('../connection/connect');\nconst Connection = require('../../cmap/connection').Connection;\nconst common = require('./common');\nconst makeStateMachine = require('../utils').makeStateMachine;\nconst MongoNetworkError = require('../error').MongoNetworkError;\nconst BSON = require('../connection/utils').retrieveBSON();\nconst makeInterruptableAsyncInterval = require('../../utils').makeInterruptableAsyncInterval;\nconst calculateDurationInMs = require('../../utils').calculateDurationInMs;\nconst now = require('../../utils').now;\n\nconst sdamEvents = require('./events');\nconst ServerHeartbeatStartedEvent = sdamEvents.ServerHeartbeatStartedEvent;\nconst ServerHeartbeatSucceededEvent = sdamEvents.ServerHeartbeatSucceededEvent;\nconst ServerHeartbeatFailedEvent = sdamEvents.ServerHeartbeatFailedEvent;\n\nconst kServer = Symbol('server');\nconst kMonitorId = Symbol('monitorId');\nconst kConnection = Symbol('connection');\nconst kCancellationToken = Symbol('cancellationToken');\nconst kRTTPinger = Symbol('rttPinger');\nconst kRoundTripTime = Symbol('roundTripTime');\n\nconst STATE_CLOSED = common.STATE_CLOSED;\nconst STATE_CLOSING = common.STATE_CLOSING;\nconst STATE_IDLE = 'idle';\nconst STATE_MONITORING = 'monitoring';\nconst stateTransition = makeStateMachine({\n [STATE_CLOSING]: [STATE_CLOSING, STATE_IDLE, STATE_CLOSED],\n [STATE_CLOSED]: [STATE_CLOSED, STATE_MONITORING],\n [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, STATE_CLOSING],\n [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, STATE_CLOSING]\n});\n\nconst INVALID_REQUEST_CHECK_STATES = new Set([STATE_CLOSING, STATE_CLOSED, STATE_MONITORING]);\n\nfunction isInCloseState(monitor) {\n return monitor.s.state === STATE_CLOSED || monitor.s.state === STATE_CLOSING;\n}\n\nclass Monitor extends EventEmitter {\n constructor(server, options) {\n super(options);\n\n this[kServer] = server;\n this[kConnection] = undefined;\n this[kCancellationToken] = new EventEmitter();\n this[kCancellationToken].setMaxListeners(Infinity);\n this[kMonitorId] = null;\n this.s = {\n state: STATE_CLOSED\n };\n\n this.address = server.description.address;\n this.options = Object.freeze({\n connectTimeoutMS:\n typeof options.connectionTimeout === 'number'\n ? options.connectionTimeout\n : typeof options.connectTimeoutMS === 'number'\n ? options.connectTimeoutMS\n : 10000,\n heartbeatFrequencyMS:\n typeof options.heartbeatFrequencyMS === 'number' ? options.heartbeatFrequencyMS : 10000,\n minHeartbeatFrequencyMS:\n typeof options.minHeartbeatFrequencyMS === 'number' ? options.minHeartbeatFrequencyMS : 500\n });\n\n // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration\n const connectOptions = Object.assign(\n {\n id: '',\n host: server.description.host,\n port: server.description.port,\n bson: server.s.bson,\n connectionType: Connection\n },\n server.s.options,\n this.options,\n\n // force BSON serialization options\n {\n raw: false,\n promoteLongs: true,\n promoteValues: true,\n promoteBuffers: true\n }\n );\n\n // ensure no authentication is used for monitoring\n delete connectOptions.credentials;\n this.connectOptions = Object.freeze(connectOptions);\n }\n\n connect() {\n if (this.s.state !== STATE_CLOSED) {\n return;\n }\n\n // start\n const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS;\n const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS;\n this[kMonitorId] = makeInterruptableAsyncInterval(monitorServer(this), {\n interval: heartbeatFrequencyMS,\n minInterval: minHeartbeatFrequencyMS,\n immediate: true\n });\n }\n\n requestCheck() {\n if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) {\n return;\n }\n\n this[kMonitorId].wake();\n }\n\n reset() {\n if (isInCloseState(this)) {\n return;\n }\n\n stateTransition(this, STATE_CLOSING);\n resetMonitorState(this);\n\n // restart monitor\n stateTransition(this, STATE_IDLE);\n\n // restart monitoring\n const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS;\n const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS;\n this[kMonitorId] = makeInterruptableAsyncInterval(monitorServer(this), {\n interval: heartbeatFrequencyMS,\n minInterval: minHeartbeatFrequencyMS\n });\n }\n\n close() {\n if (isInCloseState(this)) {\n return;\n }\n\n stateTransition(this, STATE_CLOSING);\n resetMonitorState(this);\n\n // close monitor\n this.emit('close');\n stateTransition(this, STATE_CLOSED);\n }\n}\n\nfunction resetMonitorState(monitor) {\n stateTransition(monitor, STATE_CLOSING);\n if (monitor[kMonitorId]) {\n monitor[kMonitorId].stop();\n monitor[kMonitorId] = null;\n }\n\n if (monitor[kRTTPinger]) {\n monitor[kRTTPinger].close();\n monitor[kRTTPinger] = undefined;\n }\n\n monitor[kCancellationToken].emit('cancel');\n if (monitor[kMonitorId]) {\n clearTimeout(monitor[kMonitorId]);\n monitor[kMonitorId] = undefined;\n }\n\n if (monitor[kConnection]) {\n monitor[kConnection].destroy({ force: true });\n }\n}\n\nfunction checkServer(monitor, callback) {\n let start = now();\n monitor.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(monitor.address));\n\n function failureHandler(err) {\n if (monitor[kConnection]) {\n monitor[kConnection].destroy({ force: true });\n monitor[kConnection] = undefined;\n }\n\n monitor.emit(\n 'serverHeartbeatFailed',\n new ServerHeartbeatFailedEvent(calculateDurationInMs(start), err, monitor.address)\n );\n\n monitor.emit('resetServer', err);\n monitor.emit('resetConnectionPool');\n callback(err);\n }\n\n if (monitor[kConnection] != null && !monitor[kConnection].closed) {\n const connectTimeoutMS = monitor.options.connectTimeoutMS;\n const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS;\n const topologyVersion = monitor[kServer].description.topologyVersion;\n const isAwaitable = topologyVersion != null;\n\n const cmd = isAwaitable\n ? { ismaster: true, maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) }\n : { ismaster: true };\n\n const options = isAwaitable\n ? { socketTimeout: connectTimeoutMS + maxAwaitTimeMS, exhaustAllowed: true }\n : { socketTimeout: connectTimeoutMS };\n\n if (isAwaitable && monitor[kRTTPinger] == null) {\n monitor[kRTTPinger] = new RTTPinger(monitor[kCancellationToken], monitor.connectOptions);\n }\n\n monitor[kConnection].command('admin.$cmd', cmd, options, (err, result) => {\n if (err) {\n failureHandler(err);\n return;\n }\n\n const isMaster = result.result;\n const duration = isAwaitable\n ? monitor[kRTTPinger].roundTripTime\n : calculateDurationInMs(start);\n\n monitor.emit(\n 'serverHeartbeatSucceeded',\n new ServerHeartbeatSucceededEvent(duration, isMaster, monitor.address)\n );\n\n // if we are using the streaming protocol then we immediately issue another `started`\n // event, otherwise the \"check\" is complete and return to the main monitor loop\n if (isAwaitable && isMaster.topologyVersion) {\n monitor.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(monitor.address));\n start = now();\n } else {\n if (monitor[kRTTPinger]) {\n monitor[kRTTPinger].close();\n monitor[kRTTPinger] = undefined;\n }\n\n callback(undefined, isMaster);\n }\n });\n\n return;\n }\n\n // connecting does an implicit `ismaster`\n connect(monitor.connectOptions, monitor[kCancellationToken], (err, conn) => {\n if (conn && isInCloseState(monitor)) {\n conn.destroy({ force: true });\n return;\n }\n\n if (err) {\n monitor[kConnection] = undefined;\n\n // we already reset the connection pool on network errors in all cases\n if (!(err instanceof MongoNetworkError)) {\n monitor.emit('resetConnectionPool');\n }\n\n failureHandler(err);\n return;\n }\n\n monitor[kConnection] = conn;\n monitor.emit(\n 'serverHeartbeatSucceeded',\n new ServerHeartbeatSucceededEvent(\n calculateDurationInMs(start),\n conn.ismaster,\n monitor.address\n )\n );\n\n callback(undefined, conn.ismaster);\n });\n}\n\nfunction monitorServer(monitor) {\n return callback => {\n stateTransition(monitor, STATE_MONITORING);\n function done() {\n if (!isInCloseState(monitor)) {\n stateTransition(monitor, STATE_IDLE);\n }\n\n callback();\n }\n\n // TODO: the next line is a legacy event, remove in v4\n process.nextTick(() => monitor.emit('monitoring', monitor[kServer]));\n\n checkServer(monitor, (err, isMaster) => {\n if (err) {\n // otherwise an error occured on initial discovery, also bail\n if (monitor[kServer].description.type === ServerType.Unknown) {\n monitor.emit('resetServer', err);\n return done();\n }\n }\n\n // if the check indicates streaming is supported, immediately reschedule monitoring\n if (isMaster && isMaster.topologyVersion) {\n setTimeout(() => {\n if (!isInCloseState(monitor)) {\n monitor[kMonitorId].wake();\n }\n });\n }\n\n done();\n });\n };\n}\n\nfunction makeTopologyVersion(tv) {\n return {\n processId: tv.processId,\n counter: BSON.Long.fromNumber(tv.counter)\n };\n}\n\nclass RTTPinger {\n constructor(cancellationToken, options) {\n this[kConnection] = null;\n this[kCancellationToken] = cancellationToken;\n this[kRoundTripTime] = 0;\n this.closed = false;\n\n const heartbeatFrequencyMS = options.heartbeatFrequencyMS;\n this[kMonitorId] = setTimeout(() => measureRoundTripTime(this, options), heartbeatFrequencyMS);\n }\n\n get roundTripTime() {\n return this[kRoundTripTime];\n }\n\n close() {\n this.closed = true;\n\n clearTimeout(this[kMonitorId]);\n this[kMonitorId] = undefined;\n\n if (this[kConnection]) {\n this[kConnection].destroy({ force: true });\n }\n }\n}\n\nfunction measureRoundTripTime(rttPinger, options) {\n const start = now();\n const cancellationToken = rttPinger[kCancellationToken];\n const heartbeatFrequencyMS = options.heartbeatFrequencyMS;\n if (rttPinger.closed) {\n return;\n }\n\n function measureAndReschedule(conn) {\n if (rttPinger.closed) {\n conn.destroy({ force: true });\n return;\n }\n\n if (rttPinger[kConnection] == null) {\n rttPinger[kConnection] = conn;\n }\n\n rttPinger[kRoundTripTime] = calculateDurationInMs(start);\n rttPinger[kMonitorId] = setTimeout(\n () => measureRoundTripTime(rttPinger, options),\n heartbeatFrequencyMS\n );\n }\n\n if (rttPinger[kConnection] == null) {\n connect(options, cancellationToken, (err, conn) => {\n if (err) {\n rttPinger[kConnection] = undefined;\n rttPinger[kRoundTripTime] = 0;\n return;\n }\n\n measureAndReschedule(conn);\n });\n\n return;\n }\n\n rttPinger[kConnection].command('admin.$cmd', { ismaster: 1 }, err => {\n if (err) {\n rttPinger[kConnection] = undefined;\n rttPinger[kRoundTripTime] = 0;\n return;\n }\n\n measureAndReschedule();\n });\n}\n\nmodule.exports = {\n Monitor\n};\n","'use strict';\nconst EventEmitter = require('events');\nconst ConnectionPool = require('../../cmap/connection_pool').ConnectionPool;\nconst CMAP_EVENT_NAMES = require('../../cmap/events').CMAP_EVENT_NAMES;\nconst MongoError = require('../error').MongoError;\nconst relayEvents = require('../utils').relayEvents;\nconst BSON = require('../connection/utils').retrieveBSON();\nconst Logger = require('../connection/logger');\nconst ServerDescription = require('./server_description').ServerDescription;\nconst compareTopologyVersion = require('./server_description').compareTopologyVersion;\nconst ReadPreference = require('../topologies/read_preference');\nconst Monitor = require('./monitor').Monitor;\nconst MongoNetworkError = require('../error').MongoNetworkError;\nconst MongoNetworkTimeoutError = require('../error').MongoNetworkTimeoutError;\nconst collationNotSupported = require('../utils').collationNotSupported;\nconst debugOptions = require('../connection/utils').debugOptions;\nconst isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError;\nconst isRetryableWriteError = require('../error').isRetryableWriteError;\nconst isNodeShuttingDownError = require('../error').isNodeShuttingDownError;\nconst isNetworkErrorBeforeHandshake = require('../error').isNetworkErrorBeforeHandshake;\nconst maxWireVersion = require('../utils').maxWireVersion;\nconst makeStateMachine = require('../utils').makeStateMachine;\nconst common = require('./common');\nconst ServerType = common.ServerType;\nconst isTransactionCommand = require('../transactions').isTransactionCommand;\n\n// Used for filtering out fields for logging\nconst DEBUG_FIELDS = [\n 'reconnect',\n 'reconnectTries',\n 'reconnectInterval',\n 'emitError',\n 'cursorFactory',\n 'host',\n 'port',\n 'size',\n 'keepAlive',\n 'keepAliveInitialDelay',\n 'noDelay',\n 'connectionTimeout',\n 'checkServerIdentity',\n 'socketTimeout',\n 'ssl',\n 'ca',\n 'crl',\n 'cert',\n 'key',\n 'rejectUnauthorized',\n 'promoteLongs',\n 'promoteValues',\n 'promoteBuffers',\n 'servername'\n];\n\nconst STATE_CLOSING = common.STATE_CLOSING;\nconst STATE_CLOSED = common.STATE_CLOSED;\nconst STATE_CONNECTING = common.STATE_CONNECTING;\nconst STATE_CONNECTED = common.STATE_CONNECTED;\nconst stateTransition = makeStateMachine({\n [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING],\n [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED],\n [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED],\n [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED]\n});\n\nconst kMonitor = Symbol('monitor');\n\n/**\n *\n * @fires Server#serverHeartbeatStarted\n * @fires Server#serverHeartbeatSucceeded\n * @fires Server#serverHeartbeatFailed\n */\nclass Server extends EventEmitter {\n /**\n * Create a server\n *\n * @param {ServerDescription} description\n * @param {Object} options\n */\n constructor(description, options, topology) {\n super();\n\n this.s = {\n // the server description\n description,\n // a saved copy of the incoming options\n options,\n // the server logger\n logger: Logger('Server', options),\n // the bson parser\n bson:\n options.bson ||\n new BSON([\n BSON.Binary,\n BSON.Code,\n BSON.DBRef,\n BSON.Decimal128,\n BSON.Double,\n BSON.Int32,\n BSON.Long,\n BSON.Map,\n BSON.MaxKey,\n BSON.MinKey,\n BSON.ObjectId,\n BSON.BSONRegExp,\n BSON.Symbol,\n BSON.Timestamp\n ]),\n // the server state\n state: STATE_CLOSED,\n credentials: options.credentials,\n topology\n };\n\n // create the connection pool\n // NOTE: this used to happen in `connect`, we supported overriding pool options there\n const poolOptions = Object.assign(\n { host: this.description.host, port: this.description.port, bson: this.s.bson },\n options\n );\n\n this.s.pool = new ConnectionPool(poolOptions);\n relayEvents(\n this.s.pool,\n this,\n ['commandStarted', 'commandSucceeded', 'commandFailed'].concat(CMAP_EVENT_NAMES)\n );\n\n this.s.pool.on('clusterTimeReceived', clusterTime => {\n this.clusterTime = clusterTime;\n });\n\n // create the monitor\n this[kMonitor] = new Monitor(this, this.s.options);\n relayEvents(this[kMonitor], this, [\n 'serverHeartbeatStarted',\n 'serverHeartbeatSucceeded',\n 'serverHeartbeatFailed',\n\n // legacy events\n 'monitoring'\n ]);\n\n this[kMonitor].on('resetConnectionPool', () => {\n this.s.pool.clear();\n });\n\n this[kMonitor].on('resetServer', error => markServerUnknown(this, error));\n this[kMonitor].on('serverHeartbeatSucceeded', event => {\n this.emit(\n 'descriptionReceived',\n new ServerDescription(this.description.address, event.reply, {\n roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration)\n })\n );\n\n if (this.s.state === STATE_CONNECTING) {\n stateTransition(this, STATE_CONNECTED);\n this.emit('connect', this);\n }\n });\n }\n\n get description() {\n return this.s.description;\n }\n\n get name() {\n return this.s.description.address;\n }\n\n get autoEncrypter() {\n if (this.s.options && this.s.options.autoEncrypter) {\n return this.s.options.autoEncrypter;\n }\n return null;\n }\n\n /**\n * Initiate server connect\n */\n connect() {\n if (this.s.state !== STATE_CLOSED) {\n return;\n }\n\n stateTransition(this, STATE_CONNECTING);\n this[kMonitor].connect();\n }\n\n /**\n * Destroy the server connection\n *\n * @param {object} [options] Optional settings\n * @param {Boolean} [options.force=false] Force destroy the pool\n */\n destroy(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = Object.assign({}, { force: false }, options);\n\n if (this.s.state === STATE_CLOSED) {\n if (typeof callback === 'function') {\n callback();\n }\n\n return;\n }\n\n stateTransition(this, STATE_CLOSING);\n\n this[kMonitor].close();\n this.s.pool.close(options, err => {\n stateTransition(this, STATE_CLOSED);\n this.emit('closed');\n if (typeof callback === 'function') {\n callback(err);\n }\n });\n }\n\n /**\n * Immediately schedule monitoring of this server. If there already an attempt being made\n * this will be a no-op.\n */\n requestCheck() {\n this[kMonitor].requestCheck();\n }\n\n /**\n * Execute a command\n *\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object} cmd The command hash\n * @param {object} [options] Optional settings\n * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document.\n * @param {ClientSession} [options.session] Session to use for the operation\n * @param {opResultCallback} callback A callback function\n */\n command(ns, cmd, options, callback) {\n if (typeof options === 'function') {\n (callback = options), (options = {}), (options = options || {});\n }\n\n if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) {\n callback(new MongoError('server is closed'));\n return;\n }\n\n const error = basicReadValidations(this, options);\n if (error) {\n return callback(error);\n }\n\n // Clone the options\n options = Object.assign({}, options, { wireProtocolCommand: false });\n\n // Debug log\n if (this.s.logger.isDebug()) {\n this.s.logger.debug(\n `executing command [${JSON.stringify({\n ns,\n cmd,\n options: debugOptions(DEBUG_FIELDS, options)\n })}] against ${this.name}`\n );\n }\n\n // error if collation not supported\n if (collationNotSupported(this, cmd)) {\n callback(new MongoError(`server ${this.name} does not support collation`));\n return;\n }\n\n this.s.pool.withConnection((err, conn, cb) => {\n if (err) {\n markServerUnknown(this, err);\n return cb(err);\n }\n\n conn.command(ns, cmd, options, makeOperationHandler(this, conn, cmd, options, cb));\n }, callback);\n }\n\n /**\n * Execute a query against the server\n *\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object} cmd The command document for the query\n * @param {object} options Optional settings\n * @param {function} callback\n */\n query(ns, cmd, cursorState, options, callback) {\n if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) {\n callback(new MongoError('server is closed'));\n return;\n }\n\n this.s.pool.withConnection((err, conn, cb) => {\n if (err) {\n markServerUnknown(this, err);\n return cb(err);\n }\n\n conn.query(ns, cmd, cursorState, options, makeOperationHandler(this, conn, cmd, options, cb));\n }, callback);\n }\n\n /**\n * Execute a `getMore` against the server\n *\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object} cursorState State data associated with the cursor calling this method\n * @param {object} options Optional settings\n * @param {function} callback\n */\n getMore(ns, cursorState, batchSize, options, callback) {\n if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) {\n callback(new MongoError('server is closed'));\n return;\n }\n\n this.s.pool.withConnection((err, conn, cb) => {\n if (err) {\n markServerUnknown(this, err);\n return cb(err);\n }\n\n conn.getMore(\n ns,\n cursorState,\n batchSize,\n options,\n makeOperationHandler(this, conn, null, options, cb)\n );\n }, callback);\n }\n\n /**\n * Execute a `killCursors` command against the server\n *\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object} cursorState State data associated with the cursor calling this method\n * @param {function} callback\n */\n killCursors(ns, cursorState, callback) {\n if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) {\n if (typeof callback === 'function') {\n callback(new MongoError('server is closed'));\n }\n\n return;\n }\n\n this.s.pool.withConnection((err, conn, cb) => {\n if (err) {\n markServerUnknown(this, err);\n return cb(err);\n }\n\n conn.killCursors(ns, cursorState, makeOperationHandler(this, conn, null, undefined, cb));\n }, callback);\n }\n\n /**\n * Insert one or more documents\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of documents to insert\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] Session to use for the operation\n * @param {opResultCallback} callback A callback function\n */\n insert(ns, ops, options, callback) {\n executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback);\n }\n\n /**\n * Perform one or more update operations\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of updates\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] Session to use for the operation\n * @param {opResultCallback} callback A callback function\n */\n update(ns, ops, options, callback) {\n executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback);\n }\n\n /**\n * Perform one or more remove operations\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of removes\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session] Session to use for the operation\n * @param {opResultCallback} callback A callback function\n */\n remove(ns, ops, options, callback) {\n executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback);\n }\n}\n\nObject.defineProperty(Server.prototype, 'clusterTime', {\n get: function() {\n return this.s.topology.clusterTime;\n },\n set: function(clusterTime) {\n this.s.topology.clusterTime = clusterTime;\n }\n});\n\nfunction supportsRetryableWrites(server) {\n return (\n server.description.maxWireVersion >= 6 &&\n server.description.logicalSessionTimeoutMinutes &&\n server.description.type !== ServerType.Standalone\n );\n}\n\nfunction calculateRoundTripTime(oldRtt, duration) {\n if (oldRtt === -1) {\n return duration;\n }\n\n const alpha = 0.2;\n return alpha * duration + (1 - alpha) * oldRtt;\n}\n\nfunction basicReadValidations(server, options) {\n if (options.readPreference && !(options.readPreference instanceof ReadPreference)) {\n return new MongoError('readPreference must be an instance of ReadPreference');\n }\n}\n\nfunction executeWriteOperation(args, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n // TODO: once we drop Node 4, use destructuring either here or in arguments.\n const server = args.server;\n const op = args.op;\n const ns = args.ns;\n const ops = Array.isArray(args.ops) ? args.ops : [args.ops];\n\n if (server.s.state === STATE_CLOSING || server.s.state === STATE_CLOSED) {\n callback(new MongoError('server is closed'));\n return;\n }\n\n if (collationNotSupported(server, options)) {\n callback(new MongoError(`server ${server.name} does not support collation`));\n return;\n }\n const unacknowledgedWrite = options.writeConcern && options.writeConcern.w === 0;\n if (unacknowledgedWrite || maxWireVersion(server) < 5) {\n if ((op === 'update' || op === 'remove') && ops.find(o => o.hint)) {\n callback(new MongoError(`servers < 3.4 do not support hint on ${op}`));\n return;\n }\n }\n\n server.s.pool.withConnection((err, conn, cb) => {\n if (err) {\n markServerUnknown(server, err);\n return cb(err);\n }\n\n conn[op](ns, ops, options, makeOperationHandler(server, conn, ops, options, cb));\n }, callback);\n}\n\nfunction markServerUnknown(server, error) {\n if (error instanceof MongoNetworkError && !(error instanceof MongoNetworkTimeoutError)) {\n server[kMonitor].reset();\n }\n\n server.emit(\n 'descriptionReceived',\n new ServerDescription(server.description.address, null, {\n error,\n topologyVersion:\n error && error.topologyVersion ? error.topologyVersion : server.description.topologyVersion\n })\n );\n}\n\nfunction connectionIsStale(pool, connection) {\n return connection.generation !== pool.generation;\n}\n\nfunction shouldHandleStateChangeError(server, err) {\n const etv = err.topologyVersion;\n const stv = server.description.topologyVersion;\n\n return compareTopologyVersion(stv, etv) < 0;\n}\n\nfunction inActiveTransaction(session, cmd) {\n return session && session.inTransaction() && !isTransactionCommand(cmd);\n}\n\nfunction makeOperationHandler(server, connection, cmd, options, callback) {\n const session = options && options.session;\n\n return function handleOperationResult(err, result) {\n if (err && !connectionIsStale(server.s.pool, connection)) {\n if (err instanceof MongoNetworkError) {\n if (session && !session.hasEnded) {\n session.serverSession.isDirty = true;\n }\n\n if (supportsRetryableWrites(server) && !inActiveTransaction(session, cmd)) {\n err.addErrorLabel('RetryableWriteError');\n }\n\n if (!(err instanceof MongoNetworkTimeoutError) || isNetworkErrorBeforeHandshake(err)) {\n markServerUnknown(server, err);\n server.s.pool.clear();\n }\n } else {\n // if pre-4.4 server, then add error label if its a retryable write error\n if (\n maxWireVersion(server) < 9 &&\n isRetryableWriteError(err) &&\n !inActiveTransaction(session, cmd)\n ) {\n err.addErrorLabel('RetryableWriteError');\n }\n\n if (isSDAMUnrecoverableError(err)) {\n if (shouldHandleStateChangeError(server, err)) {\n if (maxWireVersion(server) <= 7 || isNodeShuttingDownError(err)) {\n server.s.pool.clear();\n }\n\n markServerUnknown(server, err);\n process.nextTick(() => server.requestCheck());\n }\n }\n }\n }\n\n callback(err, result);\n };\n}\n\nmodule.exports = {\n Server\n};\n","'use strict';\n\nconst arrayStrictEqual = require('../utils').arrayStrictEqual;\nconst tagsStrictEqual = require('../utils').tagsStrictEqual;\nconst errorStrictEqual = require('../utils').errorStrictEqual;\nconst ServerType = require('./common').ServerType;\nconst now = require('../../utils').now;\n\nconst WRITABLE_SERVER_TYPES = new Set([\n ServerType.RSPrimary,\n ServerType.Standalone,\n ServerType.Mongos\n]);\n\nconst DATA_BEARING_SERVER_TYPES = new Set([\n ServerType.RSPrimary,\n ServerType.RSSecondary,\n ServerType.Mongos,\n ServerType.Standalone\n]);\n\nconst ISMASTER_FIELDS = [\n 'minWireVersion',\n 'maxWireVersion',\n 'maxBsonObjectSize',\n 'maxMessageSizeBytes',\n 'maxWriteBatchSize',\n 'compression',\n 'me',\n 'hosts',\n 'passives',\n 'arbiters',\n 'tags',\n 'setName',\n 'setVersion',\n 'electionId',\n 'primary',\n 'logicalSessionTimeoutMinutes',\n 'saslSupportedMechs',\n '__nodejs_mock_server__',\n '$clusterTime'\n];\n\n/**\n * The client's view of a single server, based on the most recent ismaster outcome.\n *\n * Internal type, not meant to be directly instantiated\n */\nclass ServerDescription {\n /**\n * Create a ServerDescription\n * @param {String} address The address of the server\n * @param {Object} [ismaster] An optional ismaster response for this server\n * @param {Object} [options] Optional settings\n * @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms)\n * @param {Error} [options.error] An Error used for better reporting debugging\n * @param {any} [options.topologyVersion] The topologyVersion\n */\n constructor(address, ismaster, options) {\n options = options || {};\n ismaster = Object.assign(\n {\n minWireVersion: 0,\n maxWireVersion: 0,\n hosts: [],\n passives: [],\n arbiters: [],\n tags: []\n },\n ismaster\n );\n\n this.address = address;\n this.error = options.error;\n this.roundTripTime = options.roundTripTime || -1;\n this.lastUpdateTime = now();\n this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null;\n this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null;\n this.type = parseServerType(ismaster);\n this.topologyVersion = options.topologyVersion || ismaster.topologyVersion;\n\n // direct mappings\n ISMASTER_FIELDS.forEach(field => {\n if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field];\n });\n\n // normalize case for hosts\n if (this.me) this.me = this.me.toLowerCase();\n this.hosts = this.hosts.map(host => host.toLowerCase());\n this.passives = this.passives.map(host => host.toLowerCase());\n this.arbiters = this.arbiters.map(host => host.toLowerCase());\n }\n\n get allHosts() {\n return this.hosts.concat(this.arbiters).concat(this.passives);\n }\n\n /**\n * @return {Boolean} Is this server available for reads\n */\n get isReadable() {\n return this.type === ServerType.RSSecondary || this.isWritable;\n }\n\n /**\n * @return {Boolean} Is this server data bearing\n */\n get isDataBearing() {\n return DATA_BEARING_SERVER_TYPES.has(this.type);\n }\n\n /**\n * @return {Boolean} Is this server available for writes\n */\n get isWritable() {\n return WRITABLE_SERVER_TYPES.has(this.type);\n }\n\n get host() {\n const chopLength = `:${this.port}`.length;\n return this.address.slice(0, -chopLength);\n }\n\n get port() {\n const port = this.address.split(':').pop();\n return port ? Number.parseInt(port, 10) : port;\n }\n\n /**\n * Determines if another `ServerDescription` is equal to this one per the rules defined\n * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec}\n *\n * @param {ServerDescription} other\n * @return {Boolean}\n */\n equals(other) {\n const topologyVersionsEqual =\n this.topologyVersion === other.topologyVersion ||\n compareTopologyVersion(this.topologyVersion, other.topologyVersion) === 0;\n\n return (\n other != null &&\n errorStrictEqual(this.error, other.error) &&\n this.type === other.type &&\n this.minWireVersion === other.minWireVersion &&\n this.me === other.me &&\n arrayStrictEqual(this.hosts, other.hosts) &&\n tagsStrictEqual(this.tags, other.tags) &&\n this.setName === other.setName &&\n this.setVersion === other.setVersion &&\n (this.electionId\n ? other.electionId && this.electionId.equals(other.electionId)\n : this.electionId === other.electionId) &&\n this.primary === other.primary &&\n this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes &&\n topologyVersionsEqual\n );\n }\n}\n\n/**\n * Parses an `ismaster` message and determines the server type\n *\n * @param {Object} ismaster The `ismaster` message to parse\n * @return {ServerType}\n */\nfunction parseServerType(ismaster) {\n if (!ismaster || !ismaster.ok) {\n return ServerType.Unknown;\n }\n\n if (ismaster.isreplicaset) {\n return ServerType.RSGhost;\n }\n\n if (ismaster.msg && ismaster.msg === 'isdbgrid') {\n return ServerType.Mongos;\n }\n\n if (ismaster.setName) {\n if (ismaster.hidden) {\n return ServerType.RSOther;\n } else if (ismaster.ismaster) {\n return ServerType.RSPrimary;\n } else if (ismaster.secondary) {\n return ServerType.RSSecondary;\n } else if (ismaster.arbiterOnly) {\n return ServerType.RSArbiter;\n } else {\n return ServerType.RSOther;\n }\n }\n\n return ServerType.Standalone;\n}\n\n/**\n * Compares two topology versions.\n *\n * @param {object} lhs\n * @param {object} rhs\n * @returns A negative number if `lhs` is older than `rhs`; positive if `lhs` is newer than `rhs`; 0 if they are equivalent.\n */\nfunction compareTopologyVersion(lhs, rhs) {\n if (lhs == null || rhs == null) {\n return -1;\n }\n\n if (lhs.processId.equals(rhs.processId)) {\n // TODO: handle counters as Longs\n if (lhs.counter === rhs.counter) {\n return 0;\n } else if (lhs.counter < rhs.counter) {\n return -1;\n }\n\n return 1;\n }\n\n return -1;\n}\n\nmodule.exports = {\n ServerDescription,\n parseServerType,\n compareTopologyVersion\n};\n","'use strict';\nconst ServerType = require('./common').ServerType;\nconst TopologyType = require('./common').TopologyType;\nconst ReadPreference = require('../topologies/read_preference');\nconst MongoError = require('../error').MongoError;\n\n// max staleness constants\nconst IDLE_WRITE_PERIOD = 10000;\nconst SMALLEST_MAX_STALENESS_SECONDS = 90;\n\n/**\n * Returns a server selector that selects for writable servers\n */\nfunction writableServerSelector() {\n return function(topologyDescription, servers) {\n return latencyWindowReducer(\n topologyDescription,\n servers.filter(s => s.isWritable)\n );\n };\n}\n\n/**\n * Reduces the passed in array of servers by the rules of the \"Max Staleness\" specification\n * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst\n *\n * @param {ReadPreference} readPreference The read preference providing max staleness guidance\n * @param {topologyDescription} topologyDescription The topology description\n * @param {ServerDescription[]} servers The list of server descriptions to be reduced\n * @return {ServerDescription[]} The list of servers that satisfy the requirements of max staleness\n */\nfunction maxStalenessReducer(readPreference, topologyDescription, servers) {\n if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) {\n return servers;\n }\n\n const maxStaleness = readPreference.maxStalenessSeconds;\n const maxStalenessVariance =\n (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000;\n if (maxStaleness < maxStalenessVariance) {\n throw new MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`);\n }\n\n if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) {\n throw new MongoError(\n `maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`\n );\n }\n\n if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) {\n const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0];\n return servers.reduce((result, server) => {\n const stalenessMS =\n server.lastUpdateTime -\n server.lastWriteDate -\n (primary.lastUpdateTime - primary.lastWriteDate) +\n topologyDescription.heartbeatFrequencyMS;\n\n const staleness = stalenessMS / 1000;\n if (staleness <= readPreference.maxStalenessSeconds) result.push(server);\n return result;\n }, []);\n }\n\n if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) {\n if (servers.length === 0) {\n return servers;\n }\n\n const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max));\n return servers.reduce((result, server) => {\n const stalenessMS =\n sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS;\n\n const staleness = stalenessMS / 1000;\n if (staleness <= readPreference.maxStalenessSeconds) result.push(server);\n return result;\n }, []);\n }\n\n return servers;\n}\n\n/**\n * Determines whether a server's tags match a given set of tags\n *\n * @param {String[]} tagSet The requested tag set to match\n * @param {String[]} serverTags The server's tags\n */\nfunction tagSetMatch(tagSet, serverTags) {\n const keys = Object.keys(tagSet);\n const serverTagKeys = Object.keys(serverTags);\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Reduces a set of server descriptions based on tags requested by the read preference\n *\n * @param {ReadPreference} readPreference The read preference providing the requested tags\n * @param {ServerDescription[]} servers The list of server descriptions to reduce\n * @return {ServerDescription[]} The list of servers matching the requested tags\n */\nfunction tagSetReducer(readPreference, servers) {\n if (\n readPreference.tags == null ||\n (Array.isArray(readPreference.tags) && readPreference.tags.length === 0)\n ) {\n return servers;\n }\n\n for (let i = 0; i < readPreference.tags.length; ++i) {\n const tagSet = readPreference.tags[i];\n const serversMatchingTagset = servers.reduce((matched, server) => {\n if (tagSetMatch(tagSet, server.tags)) matched.push(server);\n return matched;\n }, []);\n\n if (serversMatchingTagset.length) {\n return serversMatchingTagset;\n }\n }\n\n return [];\n}\n\n/**\n * Reduces a list of servers to ensure they fall within an acceptable latency window. This is\n * further specified in the \"Server Selection\" specification, found here:\n * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst\n *\n * @param {topologyDescription} topologyDescription The topology description\n * @param {ServerDescription[]} servers The list of servers to reduce\n * @returns {ServerDescription[]} The servers which fall within an acceptable latency window\n */\nfunction latencyWindowReducer(topologyDescription, servers) {\n const low = servers.reduce(\n (min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)),\n -1\n );\n\n const high = low + topologyDescription.localThresholdMS;\n\n return servers.reduce((result, server) => {\n if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server);\n return result;\n }, []);\n}\n\n// filters\nfunction primaryFilter(server) {\n return server.type === ServerType.RSPrimary;\n}\n\nfunction secondaryFilter(server) {\n return server.type === ServerType.RSSecondary;\n}\n\nfunction nearestFilter(server) {\n return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary;\n}\n\nfunction knownFilter(server) {\n return server.type !== ServerType.Unknown;\n}\n\n/**\n * Returns a function which selects servers based on a provided read preference\n *\n * @param {ReadPreference} readPreference The read preference to select with\n */\nfunction readPreferenceServerSelector(readPreference) {\n if (!readPreference.isValid()) {\n throw new TypeError('Invalid read preference specified');\n }\n\n return function(topologyDescription, servers) {\n const commonWireVersion = topologyDescription.commonWireVersion;\n if (\n commonWireVersion &&\n readPreference.minWireVersion &&\n readPreference.minWireVersion > commonWireVersion\n ) {\n throw new MongoError(\n `Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'`\n );\n }\n\n if (topologyDescription.type === TopologyType.Unknown) {\n return [];\n }\n\n if (\n topologyDescription.type === TopologyType.Single ||\n topologyDescription.type === TopologyType.Sharded\n ) {\n return latencyWindowReducer(topologyDescription, servers.filter(knownFilter));\n }\n\n const mode = readPreference.mode;\n if (mode === ReadPreference.PRIMARY) {\n return servers.filter(primaryFilter);\n }\n\n if (mode === ReadPreference.PRIMARY_PREFERRED) {\n const result = servers.filter(primaryFilter);\n if (result.length) {\n return result;\n }\n }\n\n const filter = mode === ReadPreference.NEAREST ? nearestFilter : secondaryFilter;\n const selectedServers = latencyWindowReducer(\n topologyDescription,\n tagSetReducer(\n readPreference,\n maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter))\n )\n );\n\n if (mode === ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) {\n return servers.filter(primaryFilter);\n }\n\n return selectedServers;\n };\n}\n\nmodule.exports = {\n writableServerSelector,\n readPreferenceServerSelector\n};\n","'use strict';\n\nconst Logger = require('../connection/logger');\nconst EventEmitter = require('events').EventEmitter;\nconst dns = require('dns');\n/**\n * Determines whether a provided address matches the provided parent domain in order\n * to avoid certain attack vectors.\n *\n * @param {String} srvAddress The address to check against a domain\n * @param {String} parentDomain The domain to check the provided address against\n * @return {Boolean} Whether the provided address matches the parent domain\n */\nfunction matchesParentDomain(srvAddress, parentDomain) {\n const regex = /^.*?\\./;\n const srv = `.${srvAddress.replace(regex, '')}`;\n const parent = `.${parentDomain.replace(regex, '')}`;\n return srv.endsWith(parent);\n}\n\nclass SrvPollingEvent {\n constructor(srvRecords) {\n this.srvRecords = srvRecords;\n }\n\n addresses() {\n return new Set(this.srvRecords.map(record => `${record.name}:${record.port}`));\n }\n}\n\nclass SrvPoller extends EventEmitter {\n /**\n * @param {object} options\n * @param {string} options.srvHost\n * @param {number} [options.heartbeatFrequencyMS]\n * @param {function} [options.logger]\n * @param {string} [options.loggerLevel]\n */\n constructor(options) {\n super();\n\n if (!options || !options.srvHost) {\n throw new TypeError('options for SrvPoller must exist and include srvHost');\n }\n\n this.srvHost = options.srvHost;\n this.rescanSrvIntervalMS = 60000;\n this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000;\n this.logger = Logger('srvPoller', options);\n\n this.haMode = false;\n this.generation = 0;\n\n this._timeout = null;\n }\n\n get srvAddress() {\n return `_mongodb._tcp.${this.srvHost}`;\n }\n\n get intervalMS() {\n return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS;\n }\n\n start() {\n if (!this._timeout) {\n this.schedule();\n }\n }\n\n stop() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n this.generation += 1;\n this._timeout = null;\n }\n }\n\n schedule() {\n clearTimeout(this._timeout);\n this._timeout = setTimeout(() => this._poll(), this.intervalMS);\n }\n\n success(srvRecords) {\n this.haMode = false;\n this.schedule();\n this.emit('srvRecordDiscovery', new SrvPollingEvent(srvRecords));\n }\n\n failure(message, obj) {\n this.logger.warn(message, obj);\n this.haMode = true;\n this.schedule();\n }\n\n parentDomainMismatch(srvRecord) {\n this.logger.warn(\n `parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`,\n srvRecord\n );\n }\n\n _poll() {\n const generation = this.generation;\n dns.resolveSrv(this.srvAddress, (err, srvRecords) => {\n if (generation !== this.generation) {\n return;\n }\n\n if (err) {\n this.failure('DNS error', err);\n return;\n }\n\n const finalAddresses = [];\n srvRecords.forEach(record => {\n if (matchesParentDomain(record.name, this.srvHost)) {\n finalAddresses.push(record);\n } else {\n this.parentDomainMismatch(record);\n }\n });\n\n if (!finalAddresses.length) {\n this.failure('No valid addresses found at host');\n return;\n }\n\n this.success(finalAddresses);\n });\n }\n}\n\nmodule.exports.SrvPollingEvent = SrvPollingEvent;\nmodule.exports.SrvPoller = SrvPoller;\n","'use strict';\nconst Denque = require('denque');\nconst EventEmitter = require('events');\nconst ServerDescription = require('./server_description').ServerDescription;\nconst ServerType = require('./common').ServerType;\nconst TopologyDescription = require('./topology_description').TopologyDescription;\nconst TopologyType = require('./common').TopologyType;\nconst events = require('./events');\nconst Server = require('./server').Server;\nconst relayEvents = require('../utils').relayEvents;\nconst ReadPreference = require('../topologies/read_preference');\nconst isRetryableWritesSupported = require('../topologies/shared').isRetryableWritesSupported;\nconst CoreCursor = require('../cursor').CoreCursor;\nconst deprecate = require('util').deprecate;\nconst BSON = require('../connection/utils').retrieveBSON();\nconst createCompressionInfo = require('../topologies/shared').createCompressionInfo;\nconst ClientSession = require('../sessions').ClientSession;\nconst MongoError = require('../error').MongoError;\nconst MongoServerSelectionError = require('../error').MongoServerSelectionError;\nconst resolveClusterTime = require('../topologies/shared').resolveClusterTime;\nconst SrvPoller = require('./srv_polling').SrvPoller;\nconst getMMAPError = require('../topologies/shared').getMMAPError;\nconst makeStateMachine = require('../utils').makeStateMachine;\nconst eachAsync = require('../utils').eachAsync;\nconst emitDeprecationWarning = require('../../utils').emitDeprecationWarning;\nconst ServerSessionPool = require('../sessions').ServerSessionPool;\nconst makeClientMetadata = require('../utils').makeClientMetadata;\nconst CMAP_EVENT_NAMES = require('../../cmap/events').CMAP_EVENT_NAMES;\nconst compareTopologyVersion = require('./server_description').compareTopologyVersion;\n\nconst common = require('./common');\nconst drainTimerQueue = common.drainTimerQueue;\nconst clearAndRemoveTimerFrom = common.clearAndRemoveTimerFrom;\n\nconst serverSelection = require('./server_selection');\nconst readPreferenceServerSelector = serverSelection.readPreferenceServerSelector;\nconst writableServerSelector = serverSelection.writableServerSelector;\n\n// Global state\nlet globalTopologyCounter = 0;\n\n// events that we relay to the `Topology`\nconst SERVER_RELAY_EVENTS = [\n 'serverHeartbeatStarted',\n 'serverHeartbeatSucceeded',\n 'serverHeartbeatFailed',\n 'commandStarted',\n 'commandSucceeded',\n 'commandFailed',\n\n // NOTE: Legacy events\n 'monitoring'\n].concat(CMAP_EVENT_NAMES);\n\n// all events we listen to from `Server` instances\nconst LOCAL_SERVER_EVENTS = ['connect', 'descriptionReceived', 'close', 'ended'];\n\nconst STATE_CLOSING = common.STATE_CLOSING;\nconst STATE_CLOSED = common.STATE_CLOSED;\nconst STATE_CONNECTING = common.STATE_CONNECTING;\nconst STATE_CONNECTED = common.STATE_CONNECTED;\nconst stateTransition = makeStateMachine({\n [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING],\n [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED],\n [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED],\n [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED]\n});\n\nconst DEPRECATED_OPTIONS = new Set([\n 'autoReconnect',\n 'reconnectTries',\n 'reconnectInterval',\n 'bufferMaxEntries'\n]);\n\nconst kCancelled = Symbol('cancelled');\nconst kWaitQueue = Symbol('waitQueue');\n\n/**\n * A container of server instances representing a connection to a MongoDB topology.\n *\n * @fires Topology#serverOpening\n * @fires Topology#serverClosed\n * @fires Topology#serverDescriptionChanged\n * @fires Topology#topologyOpening\n * @fires Topology#topologyClosed\n * @fires Topology#topologyDescriptionChanged\n * @fires Topology#serverHeartbeatStarted\n * @fires Topology#serverHeartbeatSucceeded\n * @fires Topology#serverHeartbeatFailed\n */\nclass Topology extends EventEmitter {\n /**\n * Create a topology\n *\n * @param {Array|String} [seedlist] a string list, or array of Server instances to connect to\n * @param {Object} [options] Optional settings\n * @param {Number} [options.localThresholdMS=15] The size of the latency window for selecting among multiple suitable servers\n * @param {Number} [options.serverSelectionTimeoutMS=30000] How long to block for server selection before throwing an error\n * @param {Number} [options.heartbeatFrequencyMS=10000] The frequency with which topology updates are scheduled\n */\n constructor(seedlist, options) {\n super();\n if (typeof options === 'undefined' && typeof seedlist !== 'string') {\n options = seedlist;\n seedlist = [];\n\n // this is for legacy single server constructor support\n if (options.host) {\n seedlist.push({ host: options.host, port: options.port });\n }\n }\n\n seedlist = seedlist || [];\n if (typeof seedlist === 'string') {\n seedlist = parseStringSeedlist(seedlist);\n }\n\n options = Object.assign({}, common.TOPOLOGY_DEFAULTS, options);\n options = Object.freeze(\n Object.assign(options, {\n metadata: makeClientMetadata(options),\n compression: { compressors: createCompressionInfo(options) }\n })\n );\n\n DEPRECATED_OPTIONS.forEach(optionName => {\n if (options[optionName]) {\n emitDeprecationWarning(\n `The option \\`${optionName}\\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,\n 'DeprecationWarning'\n );\n }\n });\n\n const topologyType = topologyTypeFromSeedlist(seedlist, options);\n const topologyId = globalTopologyCounter++;\n const serverDescriptions = seedlist.reduce((result, seed) => {\n if (seed.domain_socket) seed.host = seed.domain_socket;\n const address = seed.port ? `${seed.host}:${seed.port}` : `${seed.host}:27017`;\n result.set(address, new ServerDescription(address));\n return result;\n }, new Map());\n\n this[kWaitQueue] = new Denque();\n this.s = {\n // the id of this topology\n id: topologyId,\n // passed in options\n options,\n // initial seedlist of servers to connect to\n seedlist: seedlist,\n // initial state\n state: STATE_CLOSED,\n // the topology description\n description: new TopologyDescription(\n topologyType,\n serverDescriptions,\n options.replicaSet,\n null,\n null,\n null,\n options\n ),\n serverSelectionTimeoutMS: options.serverSelectionTimeoutMS,\n heartbeatFrequencyMS: options.heartbeatFrequencyMS,\n minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS,\n // allow users to override the cursor factory\n Cursor: options.cursorFactory || CoreCursor,\n // the bson parser\n bson:\n options.bson ||\n new BSON([\n BSON.Binary,\n BSON.Code,\n BSON.DBRef,\n BSON.Decimal128,\n BSON.Double,\n BSON.Int32,\n BSON.Long,\n BSON.Map,\n BSON.MaxKey,\n BSON.MinKey,\n BSON.ObjectId,\n BSON.BSONRegExp,\n BSON.Symbol,\n BSON.Timestamp\n ]),\n // a map of server instances to normalized addresses\n servers: new Map(),\n // Server Session Pool\n sessionPool: new ServerSessionPool(this),\n // Active client sessions\n sessions: new Set(),\n // Promise library\n promiseLibrary: options.promiseLibrary || Promise,\n credentials: options.credentials,\n clusterTime: null,\n\n // timer management\n connectionTimers: new Set()\n };\n\n if (options.srvHost) {\n this.s.srvPoller =\n options.srvPoller ||\n new SrvPoller({\n heartbeatFrequencyMS: this.s.heartbeatFrequencyMS,\n srvHost: options.srvHost, // TODO: GET THIS\n logger: options.logger,\n loggerLevel: options.loggerLevel\n });\n this.s.detectTopologyDescriptionChange = ev => {\n const previousType = ev.previousDescription.type;\n const newType = ev.newDescription.type;\n\n if (previousType !== TopologyType.Sharded && newType === TopologyType.Sharded) {\n this.s.handleSrvPolling = srvPollingHandler(this);\n this.s.srvPoller.on('srvRecordDiscovery', this.s.handleSrvPolling);\n this.s.srvPoller.start();\n }\n };\n\n this.on('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange);\n }\n\n // NOTE: remove this when NODE-1709 is resolved\n this.setMaxListeners(Infinity);\n }\n\n /**\n * @return A `TopologyDescription` for this topology\n */\n get description() {\n return this.s.description;\n }\n\n get parserType() {\n return BSON.native ? 'c++' : 'js';\n }\n\n /**\n * Initiate server connect\n *\n * @param {Object} [options] Optional settings\n * @param {Array} [options.auth=null] Array of auth options to apply on connect\n * @param {function} [callback] An optional callback called once on the first connected server\n */\n connect(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n if (this.s.state === STATE_CONNECTED) {\n if (typeof callback === 'function') {\n callback();\n }\n\n return;\n }\n\n stateTransition(this, STATE_CONNECTING);\n\n // emit SDAM monitoring events\n this.emit('topologyOpening', new events.TopologyOpeningEvent(this.s.id));\n\n // emit an event for the topology change\n this.emit(\n 'topologyDescriptionChanged',\n new events.TopologyDescriptionChangedEvent(\n this.s.id,\n new TopologyDescription(TopologyType.Unknown), // initial is always Unknown\n this.s.description\n )\n );\n\n // connect all known servers, then attempt server selection to connect\n connectServers(this, Array.from(this.s.description.servers.values()));\n\n ReadPreference.translate(options);\n const readPreference = options.readPreference || ReadPreference.primary;\n const connectHandler = err => {\n if (err) {\n this.close();\n\n if (typeof callback === 'function') {\n callback(err);\n } else {\n this.emit('error', err);\n }\n\n return;\n }\n\n stateTransition(this, STATE_CONNECTED);\n this.emit('open', err, this);\n this.emit('connect', this);\n\n if (typeof callback === 'function') callback(err, this);\n };\n\n // TODO: NODE-2471\n if (this.s.credentials) {\n this.command('admin.$cmd', { ping: 1 }, { readPreference }, connectHandler);\n return;\n }\n\n this.selectServer(readPreferenceServerSelector(readPreference), options, connectHandler);\n }\n\n /**\n * Close this topology\n */\n close(options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n if (typeof options === 'boolean') {\n options = { force: options };\n }\n\n options = options || {};\n if (this.s.state === STATE_CLOSED || this.s.state === STATE_CLOSING) {\n if (typeof callback === 'function') {\n callback();\n }\n\n return;\n }\n\n stateTransition(this, STATE_CLOSING);\n\n drainWaitQueue(this[kWaitQueue], new MongoError('Topology closed'));\n drainTimerQueue(this.s.connectionTimers);\n\n if (this.s.srvPoller) {\n this.s.srvPoller.stop();\n if (this.s.handleSrvPolling) {\n this.s.srvPoller.removeListener('srvRecordDiscovery', this.s.handleSrvPolling);\n delete this.s.handleSrvPolling;\n }\n }\n\n if (this.s.detectTopologyDescriptionChange) {\n this.removeListener('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange);\n delete this.s.detectTopologyDescriptionChange;\n }\n\n this.s.sessions.forEach(session => session.endSession());\n this.s.sessionPool.endAllPooledSessions(() => {\n eachAsync(\n Array.from(this.s.servers.values()),\n (server, cb) => destroyServer(server, this, options, cb),\n err => {\n this.s.servers.clear();\n\n // emit an event for close\n this.emit('topologyClosed', new events.TopologyClosedEvent(this.s.id));\n\n stateTransition(this, STATE_CLOSED);\n this.emit('close');\n\n if (typeof callback === 'function') {\n callback(err);\n }\n }\n );\n });\n }\n\n /**\n * Selects a server according to the selection predicate provided\n *\n * @param {function} [selector] An optional selector to select servers by, defaults to a random selection within a latency window\n * @param {object} [options] Optional settings related to server selection\n * @param {number} [options.serverSelectionTimeoutMS] How long to block for server selection before throwing an error\n * @param {function} callback The callback used to indicate success or failure\n * @return {Server} An instance of a `Server` meeting the criteria of the predicate provided\n */\n selectServer(selector, options, callback) {\n if (typeof options === 'function') {\n callback = options;\n if (typeof selector !== 'function') {\n options = selector;\n\n let readPreference;\n if (selector instanceof ReadPreference) {\n readPreference = selector;\n } else if (typeof selector === 'string') {\n readPreference = new ReadPreference(selector);\n } else {\n ReadPreference.translate(options);\n readPreference = options.readPreference || ReadPreference.primary;\n }\n\n selector = readPreferenceServerSelector(readPreference);\n } else {\n options = {};\n }\n }\n\n options = Object.assign(\n {},\n { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS },\n options\n );\n\n const isSharded = this.description.type === TopologyType.Sharded;\n const session = options.session;\n const transaction = session && session.transaction;\n\n if (isSharded && transaction && transaction.server) {\n callback(undefined, transaction.server);\n return;\n }\n\n // support server selection by options with readPreference\n let serverSelector = selector;\n if (typeof selector === 'object') {\n const readPreference = selector.readPreference\n ? selector.readPreference\n : ReadPreference.primary;\n\n serverSelector = readPreferenceServerSelector(readPreference);\n }\n\n const waitQueueMember = {\n serverSelector,\n transaction,\n callback\n };\n\n const serverSelectionTimeoutMS = options.serverSelectionTimeoutMS;\n if (serverSelectionTimeoutMS) {\n waitQueueMember.timer = setTimeout(() => {\n waitQueueMember[kCancelled] = true;\n waitQueueMember.timer = undefined;\n const timeoutError = new MongoServerSelectionError(\n `Server selection timed out after ${serverSelectionTimeoutMS} ms`,\n this.description\n );\n\n waitQueueMember.callback(timeoutError);\n }, serverSelectionTimeoutMS);\n }\n\n this[kWaitQueue].push(waitQueueMember);\n processWaitQueue(this);\n }\n\n // Sessions related methods\n\n /**\n * @return Whether the topology should initiate selection to determine session support\n */\n shouldCheckForSessionSupport() {\n if (this.description.type === TopologyType.Single) {\n return !this.description.hasKnownServers;\n }\n\n return !this.description.hasDataBearingServers;\n }\n\n /**\n * @return Whether sessions are supported on the current topology\n */\n hasSessionSupport() {\n return this.description.logicalSessionTimeoutMinutes != null;\n }\n\n /**\n * Start a logical session\n */\n startSession(options, clientOptions) {\n const session = new ClientSession(this, this.s.sessionPool, options, clientOptions);\n session.once('ended', () => {\n this.s.sessions.delete(session);\n });\n\n this.s.sessions.add(session);\n return session;\n }\n\n /**\n * Send endSessions command(s) with the given session ids\n *\n * @param {Array} sessions The sessions to end\n * @param {function} [callback]\n */\n endSessions(sessions, callback) {\n if (!Array.isArray(sessions)) {\n sessions = [sessions];\n }\n\n this.command(\n 'admin.$cmd',\n { endSessions: sessions },\n { readPreference: ReadPreference.primaryPreferred, noResponse: true },\n () => {\n // intentionally ignored, per spec\n if (typeof callback === 'function') callback();\n }\n );\n }\n\n /**\n * Update the internal TopologyDescription with a ServerDescription\n *\n * @param {object} serverDescription The server to update in the internal list of server descriptions\n */\n serverUpdateHandler(serverDescription) {\n if (!this.s.description.hasServer(serverDescription.address)) {\n return;\n }\n\n // ignore this server update if its from an outdated topologyVersion\n if (isStaleServerDescription(this.s.description, serverDescription)) {\n return;\n }\n\n // these will be used for monitoring events later\n const previousTopologyDescription = this.s.description;\n const previousServerDescription = this.s.description.servers.get(serverDescription.address);\n\n // Driver Sessions Spec: \"Whenever a driver receives a cluster time from\n // a server it MUST compare it to the current highest seen cluster time\n // for the deployment. If the new cluster time is higher than the\n // highest seen cluster time it MUST become the new highest seen cluster\n // time. Two cluster times are compared using only the BsonTimestamp\n // value of the clusterTime embedded field.\"\n const clusterTime = serverDescription.$clusterTime;\n if (clusterTime) {\n resolveClusterTime(this, clusterTime);\n }\n\n // If we already know all the information contained in this updated description, then\n // we don't need to emit SDAM events, but still need to update the description, in order\n // to keep client-tracked attributes like last update time and round trip time up to date\n const equalDescriptions =\n previousServerDescription && previousServerDescription.equals(serverDescription);\n\n // first update the TopologyDescription\n this.s.description = this.s.description.update(serverDescription);\n if (this.s.description.compatibilityError) {\n this.emit('error', new MongoError(this.s.description.compatibilityError));\n return;\n }\n\n // emit monitoring events for this change\n if (!equalDescriptions) {\n this.emit(\n 'serverDescriptionChanged',\n new events.ServerDescriptionChangedEvent(\n this.s.id,\n serverDescription.address,\n previousServerDescription,\n this.s.description.servers.get(serverDescription.address)\n )\n );\n }\n\n // update server list from updated descriptions\n updateServers(this, serverDescription);\n\n // attempt to resolve any outstanding server selection attempts\n if (this[kWaitQueue].length > 0) {\n processWaitQueue(this);\n }\n\n if (!equalDescriptions) {\n this.emit(\n 'topologyDescriptionChanged',\n new events.TopologyDescriptionChangedEvent(\n this.s.id,\n previousTopologyDescription,\n this.s.description\n )\n );\n }\n }\n\n auth(credentials, callback) {\n if (typeof credentials === 'function') (callback = credentials), (credentials = null);\n if (typeof callback === 'function') callback(null, true);\n }\n\n logout(callback) {\n if (typeof callback === 'function') callback(null, true);\n }\n\n // Basic operation support. Eventually this should be moved into command construction\n // during the command refactor.\n\n /**\n * Insert one or more documents\n *\n * @param {String} ns The full qualified namespace for this operation\n * @param {Array} ops An array of documents to insert\n * @param {Boolean} [options.ordered=true] Execute in order or out of order\n * @param {Object} [options.writeConcern] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields\n * @param {ClientSession} [options.session] Session to use for the operation\n * @param {boolean} [options.retryWrites] Enable retryable writes for this operation\n * @param {opResultCallback} callback A callback function\n */\n insert(ns, ops, options, callback) {\n executeWriteOperation({ topology: this, op: 'insert', ns, ops }, options, callback);\n }\n\n /**\n * Perform one or more update operations\n *\n * @param {string} ns The fully qualified namespace for this operation\n * @param {array} ops An array of updates\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields\n * @param {ClientSession} [options.session] Session to use for the operation\n * @param {boolean} [options.retryWrites] Enable retryable writes for this operation\n * @param {opResultCallback} callback A callback function\n */\n update(ns, ops, options, callback) {\n executeWriteOperation({ topology: this, op: 'update', ns, ops }, options, callback);\n }\n\n /**\n * Perform one or more remove operations\n *\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of removes\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {boolean} [options.retryWrites] Enable retryable writes for this operation\n * @param {opResultCallback} callback A callback function\n */\n remove(ns, ops, options, callback) {\n executeWriteOperation({ topology: this, op: 'remove', ns, ops }, options, callback);\n }\n\n /**\n * Execute a command\n *\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object} cmd The command hash\n * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it\n * @param {Connection} [options.connection] Specify connection object to execute command against\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {opResultCallback} callback A callback function\n */\n command(ns, cmd, options, callback) {\n if (typeof options === 'function') {\n (callback = options), (options = {}), (options = options || {});\n }\n\n ReadPreference.translate(options);\n const readPreference = options.readPreference || ReadPreference.primary;\n\n this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => {\n if (err) {\n callback(err);\n return;\n }\n\n const willRetryWrite =\n !options.retrying &&\n !!options.retryWrites &&\n options.session &&\n isRetryableWritesSupported(this) &&\n !options.session.inTransaction() &&\n isWriteCommand(cmd);\n\n const cb = (err, result) => {\n if (!err) return callback(null, result);\n if (!shouldRetryOperation(err)) {\n return callback(err);\n }\n\n if (willRetryWrite) {\n const newOptions = Object.assign({}, options, { retrying: true });\n return this.command(ns, cmd, newOptions, callback);\n }\n\n return callback(err);\n };\n\n // increment and assign txnNumber\n if (willRetryWrite) {\n options.session.incrementTransactionNumber();\n options.willRetryWrite = willRetryWrite;\n }\n\n server.command(ns, cmd, options, cb);\n });\n }\n\n /**\n * Create a new cursor\n *\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId\n * @param {object} [options] Options for the cursor\n * @param {object} [options.batchSize=0] Batchsize for the operation\n * @param {array} [options.documents=[]] Initial documents list for cursor\n * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {object} [options.topology] The internal topology of the created cursor\n * @returns {Cursor}\n */\n cursor(ns, cmd, options) {\n options = options || {};\n const topology = options.topology || this;\n const CursorClass = options.cursorFactory || this.s.Cursor;\n ReadPreference.translate(options);\n\n return new CursorClass(topology, ns, cmd, options);\n }\n\n get clientMetadata() {\n return this.s.options.metadata;\n }\n\n isConnected() {\n return this.s.state === STATE_CONNECTED;\n }\n\n isDestroyed() {\n return this.s.state === STATE_CLOSED;\n }\n\n unref() {\n console.log('not implemented: `unref`');\n }\n\n // NOTE: There are many places in code where we explicitly check the last isMaster\n // to do feature support detection. This should be done any other way, but for\n // now we will just return the first isMaster seen, which should suffice.\n lastIsMaster() {\n const serverDescriptions = Array.from(this.description.servers.values());\n if (serverDescriptions.length === 0) return {};\n\n const sd = serverDescriptions.filter(sd => sd.type !== ServerType.Unknown)[0];\n const result = sd || { maxWireVersion: this.description.commonWireVersion };\n return result;\n }\n\n get logicalSessionTimeoutMinutes() {\n return this.description.logicalSessionTimeoutMinutes;\n }\n\n get bson() {\n return this.s.bson;\n }\n}\n\nObject.defineProperty(Topology.prototype, 'clusterTime', {\n enumerable: true,\n get: function() {\n return this.s.clusterTime;\n },\n set: function(clusterTime) {\n this.s.clusterTime = clusterTime;\n }\n});\n\n// legacy aliases\nTopology.prototype.destroy = deprecate(\n Topology.prototype.close,\n 'destroy() is deprecated, please use close() instead'\n);\n\nconst RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete'];\nfunction isWriteCommand(command) {\n return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]);\n}\n\nfunction isStaleServerDescription(topologyDescription, incomingServerDescription) {\n const currentServerDescription = topologyDescription.servers.get(\n incomingServerDescription.address\n );\n const currentTopologyVersion = currentServerDescription.topologyVersion;\n return (\n compareTopologyVersion(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0\n );\n}\n\n/**\n * Destroys a server, and removes all event listeners from the instance\n *\n * @param {Server} server\n */\nfunction destroyServer(server, topology, options, callback) {\n options = options || {};\n LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event));\n\n server.destroy(options, () => {\n topology.emit(\n 'serverClosed',\n new events.ServerClosedEvent(topology.s.id, server.description.address)\n );\n\n SERVER_RELAY_EVENTS.forEach(event => server.removeAllListeners(event));\n if (typeof callback === 'function') {\n callback();\n }\n });\n}\n\n/**\n * Parses a basic seedlist in string form\n *\n * @param {string} seedlist The seedlist to parse\n */\nfunction parseStringSeedlist(seedlist) {\n return seedlist.split(',').map(seed => ({\n host: seed.split(':')[0],\n port: seed.split(':')[1] || 27017\n }));\n}\n\nfunction topologyTypeFromSeedlist(seedlist, options) {\n if (options.directConnection) {\n return TopologyType.Single;\n }\n\n const replicaSet = options.replicaSet || options.setName || options.rs_name;\n if (replicaSet == null) {\n return TopologyType.Unknown;\n }\n\n return TopologyType.ReplicaSetNoPrimary;\n}\n\nfunction randomSelection(array) {\n return array[Math.floor(Math.random() * array.length)];\n}\n\nfunction createAndConnectServer(topology, serverDescription, connectDelay) {\n topology.emit(\n 'serverOpening',\n new events.ServerOpeningEvent(topology.s.id, serverDescription.address)\n );\n\n const server = new Server(serverDescription, topology.s.options, topology);\n relayEvents(server, topology, SERVER_RELAY_EVENTS);\n\n server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology));\n\n if (connectDelay) {\n const connectTimer = setTimeout(() => {\n clearAndRemoveTimerFrom(connectTimer, topology.s.connectionTimers);\n server.connect();\n }, connectDelay);\n\n topology.s.connectionTimers.add(connectTimer);\n return server;\n }\n\n server.connect();\n return server;\n}\n\n/**\n * Create `Server` instances for all initially known servers, connect them, and assign\n * them to the passed in `Topology`.\n *\n * @param {Topology} topology The topology responsible for the servers\n * @param {ServerDescription[]} serverDescriptions A list of server descriptions to connect\n */\nfunction connectServers(topology, serverDescriptions) {\n topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => {\n const server = createAndConnectServer(topology, serverDescription);\n servers.set(serverDescription.address, server);\n return servers;\n }, new Map());\n}\n\nfunction updateServers(topology, incomingServerDescription) {\n // update the internal server's description\n if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) {\n const server = topology.s.servers.get(incomingServerDescription.address);\n server.s.description = incomingServerDescription;\n }\n\n // add new servers for all descriptions we currently don't know about locally\n for (const serverDescription of topology.description.servers.values()) {\n if (!topology.s.servers.has(serverDescription.address)) {\n const server = createAndConnectServer(topology, serverDescription);\n topology.s.servers.set(serverDescription.address, server);\n }\n }\n\n // for all servers no longer known, remove their descriptions and destroy their instances\n for (const entry of topology.s.servers) {\n const serverAddress = entry[0];\n if (topology.description.hasServer(serverAddress)) {\n continue;\n }\n\n const server = topology.s.servers.get(serverAddress);\n topology.s.servers.delete(serverAddress);\n\n // prepare server for garbage collection\n destroyServer(server, topology);\n }\n}\n\nfunction executeWriteOperation(args, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n // TODO: once we drop Node 4, use destructuring either here or in arguments.\n const topology = args.topology;\n const op = args.op;\n const ns = args.ns;\n const ops = args.ops;\n\n const willRetryWrite =\n !args.retrying &&\n !!options.retryWrites &&\n options.session &&\n isRetryableWritesSupported(topology) &&\n !options.session.inTransaction();\n\n topology.selectServer(writableServerSelector(), options, (err, server) => {\n if (err) {\n callback(err, null);\n return;\n }\n\n const handler = (err, result) => {\n if (!err) return callback(null, result);\n if (!shouldRetryOperation(err)) {\n err = getMMAPError(err);\n return callback(err);\n }\n\n if (willRetryWrite) {\n const newArgs = Object.assign({}, args, { retrying: true });\n return executeWriteOperation(newArgs, options, callback);\n }\n\n return callback(err);\n };\n\n if (callback.operationId) {\n handler.operationId = callback.operationId;\n }\n\n // increment and assign txnNumber\n if (willRetryWrite) {\n options.session.incrementTransactionNumber();\n options.willRetryWrite = willRetryWrite;\n }\n\n // execute the write operation\n server[op](ns, ops, options, handler);\n });\n}\n\nfunction shouldRetryOperation(err) {\n return err instanceof MongoError && err.hasErrorLabel('RetryableWriteError');\n}\n\nfunction srvPollingHandler(topology) {\n return function handleSrvPolling(ev) {\n const previousTopologyDescription = topology.s.description;\n topology.s.description = topology.s.description.updateFromSrvPollingEvent(ev);\n if (topology.s.description === previousTopologyDescription) {\n // Nothing changed, so return\n return;\n }\n\n updateServers(topology);\n\n topology.emit(\n 'topologyDescriptionChanged',\n new events.TopologyDescriptionChangedEvent(\n topology.s.id,\n previousTopologyDescription,\n topology.s.description\n )\n );\n };\n}\n\nfunction drainWaitQueue(queue, err) {\n while (queue.length) {\n const waitQueueMember = queue.shift();\n clearTimeout(waitQueueMember.timer);\n if (!waitQueueMember[kCancelled]) {\n waitQueueMember.callback(err);\n }\n }\n}\n\nfunction processWaitQueue(topology) {\n if (topology.s.state === STATE_CLOSED) {\n drainWaitQueue(topology[kWaitQueue], new MongoError('Topology is closed, please connect'));\n return;\n }\n\n const serverDescriptions = Array.from(topology.description.servers.values());\n const membersToProcess = topology[kWaitQueue].length;\n for (let i = 0; i < membersToProcess && topology[kWaitQueue].length; ++i) {\n const waitQueueMember = topology[kWaitQueue].shift();\n if (waitQueueMember[kCancelled]) {\n continue;\n }\n\n let selectedDescriptions;\n try {\n const serverSelector = waitQueueMember.serverSelector;\n selectedDescriptions = serverSelector\n ? serverSelector(topology.description, serverDescriptions)\n : serverDescriptions;\n } catch (e) {\n clearTimeout(waitQueueMember.timer);\n waitQueueMember.callback(e);\n continue;\n }\n\n if (selectedDescriptions.length === 0) {\n topology[kWaitQueue].push(waitQueueMember);\n continue;\n }\n\n const selectedServerDescription = randomSelection(selectedDescriptions);\n const selectedServer = topology.s.servers.get(selectedServerDescription.address);\n const transaction = waitQueueMember.transaction;\n const isSharded = topology.description.type === TopologyType.Sharded;\n if (isSharded && transaction && transaction.isActive) {\n transaction.pinServer(selectedServer);\n }\n\n clearTimeout(waitQueueMember.timer);\n waitQueueMember.callback(undefined, selectedServer);\n }\n\n if (topology[kWaitQueue].length > 0) {\n // ensure all server monitors attempt monitoring soon\n topology.s.servers.forEach(server => process.nextTick(() => server.requestCheck()));\n }\n}\n\n/**\n * A server opening SDAM monitoring event\n *\n * @event Topology#serverOpening\n * @type {ServerOpeningEvent}\n */\n\n/**\n * A server closed SDAM monitoring event\n *\n * @event Topology#serverClosed\n * @type {ServerClosedEvent}\n */\n\n/**\n * A server description SDAM change monitoring event\n *\n * @event Topology#serverDescriptionChanged\n * @type {ServerDescriptionChangedEvent}\n */\n\n/**\n * A topology open SDAM event\n *\n * @event Topology#topologyOpening\n * @type {TopologyOpeningEvent}\n */\n\n/**\n * A topology closed SDAM event\n *\n * @event Topology#topologyClosed\n * @type {TopologyClosedEvent}\n */\n\n/**\n * A topology structure SDAM change event\n *\n * @event Topology#topologyDescriptionChanged\n * @type {TopologyDescriptionChangedEvent}\n */\n\n/**\n * A topology serverHeartbeatStarted SDAM event\n *\n * @event Topology#serverHeartbeatStarted\n * @type {ServerHeartbeatStartedEvent}\n */\n\n/**\n * A topology serverHeartbeatFailed SDAM event\n *\n * @event Topology#serverHeartbeatFailed\n * @type {ServerHearbeatFailedEvent}\n */\n\n/**\n * A topology serverHeartbeatSucceeded SDAM change event\n *\n * @event Topology#serverHeartbeatSucceeded\n * @type {ServerHeartbeatSucceededEvent}\n */\n\n/**\n * An event emitted indicating a command was started, if command monitoring is enabled\n *\n * @event Topology#commandStarted\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command succeeded, if command monitoring is enabled\n *\n * @event Topology#commandSucceeded\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command failed, if command monitoring is enabled\n *\n * @event Topology#commandFailed\n * @type {object}\n */\n\nmodule.exports = {\n Topology\n};\n","'use strict';\nconst ServerType = require('./common').ServerType;\nconst ServerDescription = require('./server_description').ServerDescription;\nconst WIRE_CONSTANTS = require('../wireprotocol/constants');\nconst TopologyType = require('./common').TopologyType;\n\n// contstants related to compatability checks\nconst MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION;\nconst MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION;\nconst MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION;\nconst MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION;\n\n// Representation of a deployment of servers\nclass TopologyDescription {\n /**\n * Create a TopologyDescription\n *\n * @param {string} topologyType\n * @param {Map} serverDescriptions the a map of address to ServerDescription\n * @param {string} setName\n * @param {number} maxSetVersion\n * @param {ObjectId} maxElectionId\n */\n constructor(\n topologyType,\n serverDescriptions,\n setName,\n maxSetVersion,\n maxElectionId,\n commonWireVersion,\n options\n ) {\n options = options || {};\n\n // TODO: consider assigning all these values to a temporary value `s` which\n // we use `Object.freeze` on, ensuring the internal state of this type\n // is immutable.\n this.type = topologyType || TopologyType.Unknown;\n this.setName = setName || null;\n this.maxSetVersion = maxSetVersion || null;\n this.maxElectionId = maxElectionId || null;\n this.servers = serverDescriptions || new Map();\n this.stale = false;\n this.compatible = true;\n this.compatibilityError = null;\n this.logicalSessionTimeoutMinutes = null;\n this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0;\n this.localThresholdMS = options.localThresholdMS || 0;\n this.commonWireVersion = commonWireVersion || null;\n\n // save this locally, but don't display when printing the instance out\n Object.defineProperty(this, 'options', { value: options, enumberable: false });\n\n // determine server compatibility\n for (const serverDescription of this.servers.values()) {\n if (serverDescription.type === ServerType.Unknown) continue;\n\n if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) {\n this.compatible = false;\n this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`;\n }\n\n if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) {\n this.compatible = false;\n this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`;\n break;\n }\n }\n\n // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set\n // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes\n // value among ServerDescriptions of all data-bearing server types. If any have a null\n // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be\n // set to null.\n const readableServers = Array.from(this.servers.values()).filter(s => s.isReadable);\n this.logicalSessionTimeoutMinutes = readableServers.reduce((result, server) => {\n if (server.logicalSessionTimeoutMinutes == null) return null;\n if (result == null) return server.logicalSessionTimeoutMinutes;\n return Math.min(result, server.logicalSessionTimeoutMinutes);\n }, null);\n }\n\n /**\n * Returns a new TopologyDescription based on the SrvPollingEvent\n * @param {SrvPollingEvent} ev The event\n */\n updateFromSrvPollingEvent(ev) {\n const newAddresses = ev.addresses();\n const serverDescriptions = new Map(this.servers);\n for (const server of this.servers) {\n if (newAddresses.has(server[0])) {\n newAddresses.delete(server[0]);\n } else {\n serverDescriptions.delete(server[0]);\n }\n }\n\n if (serverDescriptions.size === this.servers.size && newAddresses.size === 0) {\n return this;\n }\n\n for (const address of newAddresses) {\n serverDescriptions.set(address, new ServerDescription(address));\n }\n\n return new TopologyDescription(\n this.type,\n serverDescriptions,\n this.setName,\n this.maxSetVersion,\n this.maxElectionId,\n this.commonWireVersion,\n this.options,\n null\n );\n }\n\n /**\n * Returns a copy of this description updated with a given ServerDescription\n *\n * @param {ServerDescription} serverDescription\n */\n update(serverDescription) {\n const address = serverDescription.address;\n // NOTE: there are a number of prime targets for refactoring here\n // once we support destructuring assignments\n\n // potentially mutated values\n let topologyType = this.type;\n let setName = this.setName;\n let maxSetVersion = this.maxSetVersion;\n let maxElectionId = this.maxElectionId;\n let commonWireVersion = this.commonWireVersion;\n\n if (serverDescription.setName && setName && serverDescription.setName !== setName) {\n serverDescription = new ServerDescription(address, null);\n }\n\n const serverType = serverDescription.type;\n let serverDescriptions = new Map(this.servers);\n\n // update common wire version\n if (serverDescription.maxWireVersion !== 0) {\n if (commonWireVersion == null) {\n commonWireVersion = serverDescription.maxWireVersion;\n } else {\n commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion);\n }\n }\n\n // update the actual server description\n serverDescriptions.set(address, serverDescription);\n\n if (topologyType === TopologyType.Single) {\n // once we are defined as single, that never changes\n return new TopologyDescription(\n TopologyType.Single,\n serverDescriptions,\n setName,\n maxSetVersion,\n maxElectionId,\n commonWireVersion,\n this.options\n );\n }\n\n if (topologyType === TopologyType.Unknown) {\n if (serverType === ServerType.Standalone && this.servers.size !== 1) {\n serverDescriptions.delete(address);\n } else {\n topologyType = topologyTypeForServerType(serverType);\n }\n }\n\n if (topologyType === TopologyType.Sharded) {\n if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) {\n serverDescriptions.delete(address);\n }\n }\n\n if (topologyType === TopologyType.ReplicaSetNoPrimary) {\n if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) {\n serverDescriptions.delete(address);\n }\n\n if (serverType === ServerType.RSPrimary) {\n const result = updateRsFromPrimary(\n serverDescriptions,\n setName,\n serverDescription,\n maxSetVersion,\n maxElectionId\n );\n\n (topologyType = result[0]),\n (setName = result[1]),\n (maxSetVersion = result[2]),\n (maxElectionId = result[3]);\n } else if (\n [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0\n ) {\n const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription);\n (topologyType = result[0]), (setName = result[1]);\n }\n }\n\n if (topologyType === TopologyType.ReplicaSetWithPrimary) {\n if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) {\n serverDescriptions.delete(address);\n topologyType = checkHasPrimary(serverDescriptions);\n } else if (serverType === ServerType.RSPrimary) {\n const result = updateRsFromPrimary(\n serverDescriptions,\n setName,\n serverDescription,\n maxSetVersion,\n maxElectionId\n );\n\n (topologyType = result[0]),\n (setName = result[1]),\n (maxSetVersion = result[2]),\n (maxElectionId = result[3]);\n } else if (\n [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0\n ) {\n topologyType = updateRsWithPrimaryFromMember(\n serverDescriptions,\n setName,\n serverDescription\n );\n } else {\n topologyType = checkHasPrimary(serverDescriptions);\n }\n }\n\n return new TopologyDescription(\n topologyType,\n serverDescriptions,\n setName,\n maxSetVersion,\n maxElectionId,\n commonWireVersion,\n this.options\n );\n }\n\n get error() {\n const descriptionsWithError = Array.from(this.servers.values()).filter(sd => sd.error);\n if (descriptionsWithError.length > 0) {\n return descriptionsWithError[0].error;\n }\n }\n\n /**\n * Determines if the topology description has any known servers\n */\n get hasKnownServers() {\n return Array.from(this.servers.values()).some(sd => sd.type !== ServerType.Unknown);\n }\n\n /**\n * Determines if this topology description has a data-bearing server available.\n */\n get hasDataBearingServers() {\n return Array.from(this.servers.values()).some(sd => sd.isDataBearing);\n }\n\n /**\n * Determines if the topology has a definition for the provided address\n *\n * @param {String} address\n * @return {Boolean} Whether the topology knows about this server\n */\n hasServer(address) {\n return this.servers.has(address);\n }\n}\n\nfunction topologyTypeForServerType(serverType) {\n if (serverType === ServerType.Standalone) {\n return TopologyType.Single;\n }\n\n if (serverType === ServerType.Mongos) {\n return TopologyType.Sharded;\n }\n\n if (serverType === ServerType.RSPrimary) {\n return TopologyType.ReplicaSetWithPrimary;\n }\n\n if (serverType === ServerType.RSGhost || serverType === ServerType.Unknown) {\n return TopologyType.Unknown;\n }\n\n return TopologyType.ReplicaSetNoPrimary;\n}\n\nfunction compareObjectId(oid1, oid2) {\n if (oid1 == null) {\n return -1;\n }\n\n if (oid2 == null) {\n return 1;\n }\n\n if (oid1.id instanceof Buffer && oid2.id instanceof Buffer) {\n const oid1Buffer = oid1.id;\n const oid2Buffer = oid2.id;\n return oid1Buffer.compare(oid2Buffer);\n }\n\n const oid1String = oid1.toString();\n const oid2String = oid2.toString();\n return oid1String.localeCompare(oid2String);\n}\n\nfunction updateRsFromPrimary(\n serverDescriptions,\n setName,\n serverDescription,\n maxSetVersion,\n maxElectionId\n) {\n setName = setName || serverDescription.setName;\n if (setName !== serverDescription.setName) {\n serverDescriptions.delete(serverDescription.address);\n return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];\n }\n\n const electionId = serverDescription.electionId ? serverDescription.electionId : null;\n if (serverDescription.setVersion && electionId) {\n if (maxSetVersion && maxElectionId) {\n if (\n maxSetVersion > serverDescription.setVersion ||\n compareObjectId(maxElectionId, electionId) > 0\n ) {\n // this primary is stale, we must remove it\n serverDescriptions.set(\n serverDescription.address,\n new ServerDescription(serverDescription.address)\n );\n\n return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];\n }\n }\n\n maxElectionId = serverDescription.electionId;\n }\n\n if (\n serverDescription.setVersion != null &&\n (maxSetVersion == null || serverDescription.setVersion > maxSetVersion)\n ) {\n maxSetVersion = serverDescription.setVersion;\n }\n\n // We've heard from the primary. Is it the same primary as before?\n for (const address of serverDescriptions.keys()) {\n const server = serverDescriptions.get(address);\n\n if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) {\n // Reset old primary's type to Unknown.\n serverDescriptions.set(address, new ServerDescription(server.address));\n\n // There can only be one primary\n break;\n }\n }\n\n // Discover new hosts from this primary's response.\n serverDescription.allHosts.forEach(address => {\n if (!serverDescriptions.has(address)) {\n serverDescriptions.set(address, new ServerDescription(address));\n }\n });\n\n // Remove hosts not in the response.\n const currentAddresses = Array.from(serverDescriptions.keys());\n const responseAddresses = serverDescription.allHosts;\n currentAddresses\n .filter(addr => responseAddresses.indexOf(addr) === -1)\n .forEach(address => {\n serverDescriptions.delete(address);\n });\n\n return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];\n}\n\nfunction updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) {\n if (setName == null) {\n throw new TypeError('setName is required');\n }\n\n if (\n setName !== serverDescription.setName ||\n (serverDescription.me && serverDescription.address !== serverDescription.me)\n ) {\n serverDescriptions.delete(serverDescription.address);\n }\n\n return checkHasPrimary(serverDescriptions);\n}\n\nfunction updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) {\n let topologyType = TopologyType.ReplicaSetNoPrimary;\n\n setName = setName || serverDescription.setName;\n if (setName !== serverDescription.setName) {\n serverDescriptions.delete(serverDescription.address);\n return [topologyType, setName];\n }\n\n serverDescription.allHosts.forEach(address => {\n if (!serverDescriptions.has(address)) {\n serverDescriptions.set(address, new ServerDescription(address));\n }\n });\n\n if (serverDescription.me && serverDescription.address !== serverDescription.me) {\n serverDescriptions.delete(serverDescription.address);\n }\n\n return [topologyType, setName];\n}\n\nfunction checkHasPrimary(serverDescriptions) {\n for (const addr of serverDescriptions.keys()) {\n if (serverDescriptions.get(addr).type === ServerType.RSPrimary) {\n return TopologyType.ReplicaSetWithPrimary;\n }\n }\n\n return TopologyType.ReplicaSetNoPrimary;\n}\n\nmodule.exports = {\n TopologyDescription\n};\n","'use strict';\n\nconst retrieveBSON = require('./connection/utils').retrieveBSON;\nconst EventEmitter = require('events');\nconst BSON = retrieveBSON();\nconst Binary = BSON.Binary;\nconst uuidV4 = require('./utils').uuidV4;\nconst MongoError = require('./error').MongoError;\nconst isRetryableError = require('././error').isRetryableError;\nconst MongoNetworkError = require('./error').MongoNetworkError;\nconst MongoWriteConcernError = require('./error').MongoWriteConcernError;\nconst Transaction = require('./transactions').Transaction;\nconst TxnState = require('./transactions').TxnState;\nconst isPromiseLike = require('./utils').isPromiseLike;\nconst ReadPreference = require('./topologies/read_preference');\nconst maybePromise = require('../utils').maybePromise;\nconst isTransactionCommand = require('./transactions').isTransactionCommand;\nconst resolveClusterTime = require('./topologies/shared').resolveClusterTime;\nconst isSharded = require('./wireprotocol/shared').isSharded;\nconst maxWireVersion = require('./utils').maxWireVersion;\nconst now = require('./../utils').now;\nconst calculateDurationInMs = require('./../utils').calculateDurationInMs;\nconst minWireVersionForShardedTransactions = 8;\n\nfunction assertAlive(session, callback) {\n if (session.serverSession == null) {\n const error = new MongoError('Cannot use a session that has ended');\n if (typeof callback === 'function') {\n callback(error, null);\n return false;\n }\n\n throw error;\n }\n\n return true;\n}\n\n/**\n * Options to pass when creating a Client Session\n * @typedef {Object} SessionOptions\n * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session\n * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session.\n */\n\n/**\n * A BSON document reflecting the lsid of a {@link ClientSession}\n * @typedef {Object} SessionId\n */\n\nconst kServerSession = Symbol('serverSession');\n\n/**\n * A class representing a client session on the server\n * WARNING: not meant to be instantiated directly.\n * @class\n * @hideconstructor\n */\nclass ClientSession extends EventEmitter {\n /**\n * Create a client session.\n * WARNING: not meant to be instantiated directly\n *\n * @param {Topology} topology The current client's topology (Internal Class)\n * @param {ServerSessionPool} sessionPool The server session pool (Internal Class)\n * @param {SessionOptions} [options] Optional settings\n * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver\n */\n constructor(topology, sessionPool, options, clientOptions) {\n super();\n\n if (topology == null) {\n throw new Error('ClientSession requires a topology');\n }\n\n if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) {\n throw new Error('ClientSession requires a ServerSessionPool');\n }\n\n options = options || {};\n clientOptions = clientOptions || {};\n\n this.topology = topology;\n this.sessionPool = sessionPool;\n this.hasEnded = false;\n this.clientOptions = clientOptions;\n this[kServerSession] = undefined;\n\n this.supports = {\n causalConsistency:\n typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true\n };\n\n this.clusterTime = options.initialClusterTime;\n\n this.operationTime = null;\n this.explicit = !!options.explicit;\n this.owner = options.owner;\n this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions);\n this.transaction = new Transaction();\n }\n\n /**\n * The server id associated with this session\n * @type {SessionId}\n */\n get id() {\n return this.serverSession.id;\n }\n\n get serverSession() {\n if (this[kServerSession] == null) {\n this[kServerSession] = this.sessionPool.acquire();\n }\n\n return this[kServerSession];\n }\n\n /**\n * Ends this session on the server\n *\n * @param {Object} [options] Optional settings. Currently reserved for future use\n * @param {Function} [callback] Optional callback for completion of this operation\n */\n endSession(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const session = this;\n return maybePromise(this, callback, done => {\n if (session.hasEnded) {\n return done();\n }\n\n function completeEndSession() {\n // release the server session back to the pool\n session.sessionPool.release(session.serverSession);\n session[kServerSession] = undefined;\n\n // mark the session as ended, and emit a signal\n session.hasEnded = true;\n session.emit('ended', session);\n\n // spec indicates that we should ignore all errors for `endSessions`\n done();\n }\n\n if (session.serverSession && session.inTransaction()) {\n session.abortTransaction(err => {\n if (err) return done(err);\n completeEndSession();\n });\n\n return;\n }\n\n completeEndSession();\n });\n }\n\n /**\n * Advances the operationTime for a ClientSession.\n *\n * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to\n */\n advanceOperationTime(operationTime) {\n if (this.operationTime == null) {\n this.operationTime = operationTime;\n return;\n }\n\n if (operationTime.greaterThan(this.operationTime)) {\n this.operationTime = operationTime;\n }\n }\n\n /**\n * Used to determine if this session equals another\n * @param {ClientSession} session\n * @return {boolean} true if the sessions are equal\n */\n equals(session) {\n if (!(session instanceof ClientSession)) {\n return false;\n }\n\n return this.id.id.buffer.equals(session.id.id.buffer);\n }\n\n /**\n * Increment the transaction number on the internal ServerSession\n */\n incrementTransactionNumber() {\n this.serverSession.txnNumber++;\n }\n\n /**\n * @returns {boolean} whether this session is currently in a transaction or not\n */\n inTransaction() {\n return this.transaction.isActive;\n }\n\n /**\n * Starts a new transaction with the given options.\n *\n * @param {TransactionOptions} options Options for the transaction\n */\n startTransaction(options) {\n assertAlive(this);\n if (this.inTransaction()) {\n throw new MongoError('Transaction already in progress');\n }\n\n const topologyMaxWireVersion = maxWireVersion(this.topology);\n if (\n isSharded(this.topology) &&\n topologyMaxWireVersion != null &&\n topologyMaxWireVersion < minWireVersionForShardedTransactions\n ) {\n throw new MongoError('Transactions are not supported on sharded clusters in MongoDB < 4.2.');\n }\n\n // increment txnNumber\n this.incrementTransactionNumber();\n\n // create transaction state\n this.transaction = new Transaction(\n Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions)\n );\n\n this.transaction.transition(TxnState.STARTING_TRANSACTION);\n }\n\n /**\n * Commits the currently active transaction in this session.\n *\n * @param {Function} [callback] optional callback for completion of this operation\n * @return {Promise} A promise is returned if no callback is provided\n */\n commitTransaction(callback) {\n return maybePromise(this, callback, done => endTransaction(this, 'commitTransaction', done));\n }\n\n /**\n * Aborts the currently active transaction in this session.\n *\n * @param {Function} [callback] optional callback for completion of this operation\n * @return {Promise} A promise is returned if no callback is provided\n */\n abortTransaction(callback) {\n return maybePromise(this, callback, done => endTransaction(this, 'abortTransaction', done));\n }\n\n /**\n * This is here to ensure that ClientSession is never serialized to BSON.\n * @ignore\n */\n toBSON() {\n throw new Error('ClientSession cannot be serialized to BSON.');\n }\n\n /**\n * A user provided function to be run within a transaction\n *\n * @callback WithTransactionCallback\n * @param {ClientSession} session The parent session of the transaction running the operation. This should be passed into each operation within the lambda.\n * @returns {Promise} The resulting Promise of operations run within this transaction\n */\n\n /**\n * Runs a provided lambda within a transaction, retrying either the commit operation\n * or entire transaction as needed (and when the error permits) to better ensure that\n * the transaction can complete successfully.\n *\n * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not\n * return a Promise will result in undefined behavior.\n *\n * @param {WithTransactionCallback} fn\n * @param {TransactionOptions} [options] Optional settings for the transaction\n */\n withTransaction(fn, options) {\n const startTime = now();\n return attemptTransaction(this, startTime, fn, options);\n }\n}\n\nconst MAX_WITH_TRANSACTION_TIMEOUT = 120000;\nconst UNSATISFIABLE_WRITE_CONCERN_CODE = 100;\nconst UNKNOWN_REPL_WRITE_CONCERN_CODE = 79;\nconst MAX_TIME_MS_EXPIRED_CODE = 50;\nconst NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([\n 'CannotSatisfyWriteConcern',\n 'UnknownReplWriteConcern',\n 'UnsatisfiableWriteConcern'\n]);\n\nfunction hasNotTimedOut(startTime, max) {\n return calculateDurationInMs(startTime) < max;\n}\n\nfunction isUnknownTransactionCommitResult(err) {\n return (\n isMaxTimeMSExpiredError(err) ||\n (!NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName) &&\n err.code !== UNSATISFIABLE_WRITE_CONCERN_CODE &&\n err.code !== UNKNOWN_REPL_WRITE_CONCERN_CODE)\n );\n}\n\nfunction isMaxTimeMSExpiredError(err) {\n if (err == null) return false;\n return (\n err.code === MAX_TIME_MS_EXPIRED_CODE ||\n (err.writeConcernError && err.writeConcernError.code === MAX_TIME_MS_EXPIRED_CODE)\n );\n}\n\nfunction attemptTransactionCommit(session, startTime, fn, options) {\n return session.commitTransaction().catch(err => {\n if (\n err instanceof MongoError &&\n hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) &&\n !isMaxTimeMSExpiredError(err)\n ) {\n if (err.hasErrorLabel('UnknownTransactionCommitResult')) {\n return attemptTransactionCommit(session, startTime, fn, options);\n }\n\n if (err.hasErrorLabel('TransientTransactionError')) {\n return attemptTransaction(session, startTime, fn, options);\n }\n }\n\n throw err;\n });\n}\n\nconst USER_EXPLICIT_TXN_END_STATES = new Set([\n TxnState.NO_TRANSACTION,\n TxnState.TRANSACTION_COMMITTED,\n TxnState.TRANSACTION_ABORTED\n]);\n\nfunction userExplicitlyEndedTransaction(session) {\n return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state);\n}\n\nfunction attemptTransaction(session, startTime, fn, options) {\n session.startTransaction(options);\n\n let promise;\n try {\n promise = fn(session);\n } catch (err) {\n promise = Promise.reject(err);\n }\n\n if (!isPromiseLike(promise)) {\n session.abortTransaction();\n throw new TypeError('Function provided to `withTransaction` must return a Promise');\n }\n\n return promise\n .then(() => {\n if (userExplicitlyEndedTransaction(session)) {\n return;\n }\n\n return attemptTransactionCommit(session, startTime, fn, options);\n })\n .catch(err => {\n function maybeRetryOrThrow(err) {\n if (\n err instanceof MongoError &&\n err.hasErrorLabel('TransientTransactionError') &&\n hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT)\n ) {\n return attemptTransaction(session, startTime, fn, options);\n }\n\n if (isMaxTimeMSExpiredError(err)) {\n err.addErrorLabel('UnknownTransactionCommitResult');\n }\n\n throw err;\n }\n\n if (session.transaction.isActive) {\n return session.abortTransaction().then(() => maybeRetryOrThrow(err));\n }\n\n return maybeRetryOrThrow(err);\n });\n}\n\nfunction endTransaction(session, commandName, callback) {\n if (!assertAlive(session, callback)) {\n // checking result in case callback was called\n return;\n }\n\n // handle any initial problematic cases\n let txnState = session.transaction.state;\n\n if (txnState === TxnState.NO_TRANSACTION) {\n callback(new MongoError('No transaction started'));\n return;\n }\n\n if (commandName === 'commitTransaction') {\n if (\n txnState === TxnState.STARTING_TRANSACTION ||\n txnState === TxnState.TRANSACTION_COMMITTED_EMPTY\n ) {\n // the transaction was never started, we can safely exit here\n session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY);\n callback(null, null);\n return;\n }\n\n if (txnState === TxnState.TRANSACTION_ABORTED) {\n callback(new MongoError('Cannot call commitTransaction after calling abortTransaction'));\n return;\n }\n } else {\n if (txnState === TxnState.STARTING_TRANSACTION) {\n // the transaction was never started, we can safely exit here\n session.transaction.transition(TxnState.TRANSACTION_ABORTED);\n callback(null, null);\n return;\n }\n\n if (txnState === TxnState.TRANSACTION_ABORTED) {\n callback(new MongoError('Cannot call abortTransaction twice'));\n return;\n }\n\n if (\n txnState === TxnState.TRANSACTION_COMMITTED ||\n txnState === TxnState.TRANSACTION_COMMITTED_EMPTY\n ) {\n callback(new MongoError('Cannot call abortTransaction after calling commitTransaction'));\n return;\n }\n }\n\n // construct and send the command\n const command = { [commandName]: 1 };\n\n // apply a writeConcern if specified\n let writeConcern;\n if (session.transaction.options.writeConcern) {\n writeConcern = Object.assign({}, session.transaction.options.writeConcern);\n } else if (session.clientOptions && session.clientOptions.w) {\n writeConcern = { w: session.clientOptions.w };\n }\n\n if (txnState === TxnState.TRANSACTION_COMMITTED) {\n writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' });\n }\n\n if (writeConcern) {\n Object.assign(command, { writeConcern });\n }\n\n if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) {\n Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS });\n }\n\n function commandHandler(e, r) {\n if (commandName === 'commitTransaction') {\n session.transaction.transition(TxnState.TRANSACTION_COMMITTED);\n\n if (\n e &&\n (e instanceof MongoNetworkError ||\n e instanceof MongoWriteConcernError ||\n isRetryableError(e) ||\n isMaxTimeMSExpiredError(e))\n ) {\n if (isUnknownTransactionCommitResult(e)) {\n e.addErrorLabel('UnknownTransactionCommitResult');\n\n // per txns spec, must unpin session in this case\n session.transaction.unpinServer();\n }\n }\n } else {\n session.transaction.transition(TxnState.TRANSACTION_ABORTED);\n }\n\n callback(e, r);\n }\n\n // The spec indicates that we should ignore all errors on `abortTransaction`\n function transactionError(err) {\n return commandName === 'commitTransaction' ? err : null;\n }\n\n if (\n // Assumption here that commandName is \"commitTransaction\" or \"abortTransaction\"\n session.transaction.recoveryToken &&\n supportsRecoveryToken(session)\n ) {\n command.recoveryToken = session.transaction.recoveryToken;\n }\n\n // send the command\n session.topology.command('admin.$cmd', command, { session }, (err, reply) => {\n if (err && isRetryableError(err)) {\n // SPEC-1185: apply majority write concern when retrying commitTransaction\n if (command.commitTransaction) {\n // per txns spec, must unpin session in this case\n session.transaction.unpinServer();\n\n command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, {\n w: 'majority'\n });\n }\n\n return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) =>\n commandHandler(transactionError(_err), _reply)\n );\n }\n\n commandHandler(transactionError(err), reply);\n });\n}\n\nfunction supportsRecoveryToken(session) {\n const topology = session.topology;\n return !!topology.s.options.useRecoveryToken;\n}\n\n/**\n * Reflects the existence of a session on the server. Can be reused by the session pool.\n * WARNING: not meant to be instantiated directly. For internal use only.\n * @ignore\n */\nclass ServerSession {\n constructor() {\n this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) };\n this.lastUse = now();\n this.txnNumber = 0;\n this.isDirty = false;\n }\n\n /**\n * Determines if the server session has timed out.\n * @ignore\n * @param {Date} sessionTimeoutMinutes The server's \"logicalSessionTimeoutMinutes\"\n * @return {boolean} true if the session has timed out.\n */\n hasTimedOut(sessionTimeoutMinutes) {\n // Take the difference of the lastUse timestamp and now, which will result in a value in\n // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes`\n const idleTimeMinutes = Math.round(\n ((calculateDurationInMs(this.lastUse) % 86400000) % 3600000) / 60000\n );\n\n return idleTimeMinutes > sessionTimeoutMinutes - 1;\n }\n}\n\n/**\n * Maintains a pool of Server Sessions.\n * For internal use only\n * @ignore\n */\nclass ServerSessionPool {\n constructor(topology) {\n if (topology == null) {\n throw new Error('ServerSessionPool requires a topology');\n }\n\n this.topology = topology;\n this.sessions = [];\n }\n\n /**\n * Ends all sessions in the session pool.\n * @ignore\n */\n endAllPooledSessions(callback) {\n if (this.sessions.length) {\n this.topology.endSessions(\n this.sessions.map(session => session.id),\n () => {\n this.sessions = [];\n if (typeof callback === 'function') {\n callback();\n }\n }\n );\n\n return;\n }\n\n if (typeof callback === 'function') {\n callback();\n }\n }\n\n /**\n * Acquire a Server Session from the pool.\n * Iterates through each session in the pool, removing any stale sessions\n * along the way. The first non-stale session found is removed from the\n * pool and returned. If no non-stale session is found, a new ServerSession\n * is created.\n * @ignore\n * @returns {ServerSession}\n */\n acquire() {\n const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes;\n while (this.sessions.length) {\n const session = this.sessions.shift();\n if (!session.hasTimedOut(sessionTimeoutMinutes)) {\n return session;\n }\n }\n\n return new ServerSession();\n }\n\n /**\n * Release a session to the session pool\n * Adds the session back to the session pool if the session has not timed out yet.\n * This method also removes any stale sessions from the pool.\n * @ignore\n * @param {ServerSession} session The session to release to the pool\n */\n release(session) {\n const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes;\n while (this.sessions.length) {\n const pooledSession = this.sessions[this.sessions.length - 1];\n if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) {\n this.sessions.pop();\n } else {\n break;\n }\n }\n\n if (!session.hasTimedOut(sessionTimeoutMinutes)) {\n if (session.isDirty) {\n return;\n }\n\n // otherwise, readd this session to the session pool\n this.sessions.unshift(session);\n }\n }\n}\n\n// TODO: this should be codified in command construction\n// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern\nfunction commandSupportsReadConcern(command, options) {\n if (\n command.aggregate ||\n command.count ||\n command.distinct ||\n command.find ||\n command.parallelCollectionScan ||\n command.geoNear ||\n command.geoSearch\n ) {\n return true;\n }\n\n if (\n command.mapReduce &&\n options &&\n options.out &&\n (options.out.inline === 1 || options.out === 'inline')\n ) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Optionally decorate a command with sessions specific keys\n *\n * @ignore\n * @param {ClientSession} session the session tracking transaction state\n * @param {Object} command the command to decorate\n * @param {Object} topology the topology for tracking the cluster time\n * @param {Object} [options] Optional settings passed to calling operation\n * @return {MongoError|null} An error, if some error condition was met\n */\nfunction applySession(session, command, options) {\n if (session.hasEnded) {\n // TODO: merge this with `assertAlive`, did not want to throw a try/catch here\n return new MongoError('Cannot use a session that has ended');\n }\n\n // SPEC-1019: silently ignore explicit session with unacknowledged write for backwards compatibility\n if (options && options.writeConcern && options.writeConcern.w === 0) {\n return;\n }\n\n const serverSession = session.serverSession;\n serverSession.lastUse = now();\n command.lsid = serverSession.id;\n\n // first apply non-transaction-specific sessions data\n const inTransaction = session.inTransaction() || isTransactionCommand(command);\n const isRetryableWrite = options.willRetryWrite;\n const shouldApplyReadConcern = commandSupportsReadConcern(command, options);\n\n if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) {\n command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber);\n }\n\n // now attempt to apply transaction-specific sessions data\n if (!inTransaction) {\n if (session.transaction.state !== TxnState.NO_TRANSACTION) {\n session.transaction.transition(TxnState.NO_TRANSACTION);\n }\n\n // TODO: the following should only be applied to read operation per spec.\n // for causal consistency\n if (session.supports.causalConsistency && session.operationTime && shouldApplyReadConcern) {\n command.readConcern = command.readConcern || {};\n Object.assign(command.readConcern, { afterClusterTime: session.operationTime });\n }\n\n return;\n }\n\n if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) {\n return new MongoError(\n `Read preference in a transaction must be primary, not: ${options.readPreference.mode}`\n );\n }\n\n // `autocommit` must always be false to differentiate from retryable writes\n command.autocommit = false;\n\n if (session.transaction.state === TxnState.STARTING_TRANSACTION) {\n session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS);\n command.startTransaction = true;\n\n const readConcern =\n session.transaction.options.readConcern || session.clientOptions.readConcern;\n if (readConcern) {\n command.readConcern = readConcern;\n }\n\n if (session.supports.causalConsistency && session.operationTime) {\n command.readConcern = command.readConcern || {};\n Object.assign(command.readConcern, { afterClusterTime: session.operationTime });\n }\n }\n}\n\nfunction updateSessionFromResponse(session, document) {\n if (document.$clusterTime) {\n resolveClusterTime(session, document.$clusterTime);\n }\n\n if (document.operationTime && session && session.supports.causalConsistency) {\n session.advanceOperationTime(document.operationTime);\n }\n\n if (document.recoveryToken && session && session.inTransaction()) {\n session.transaction._recoveryToken = document.recoveryToken;\n }\n}\n\nmodule.exports = {\n ClientSession,\n ServerSession,\n ServerSessionPool,\n TxnState,\n applySession,\n updateSessionFromResponse,\n commandSupportsReadConcern\n};\n","'use strict';\n\nconst inherits = require('util').inherits;\nconst f = require('util').format;\nconst EventEmitter = require('events').EventEmitter;\nconst CoreCursor = require('../cursor').CoreCursor;\nconst Logger = require('../connection/logger');\nconst retrieveBSON = require('../connection/utils').retrieveBSON;\nconst MongoError = require('../error').MongoError;\nconst Server = require('./server');\nconst diff = require('./shared').diff;\nconst cloneOptions = require('./shared').cloneOptions;\nconst SessionMixins = require('./shared').SessionMixins;\nconst isRetryableWritesSupported = require('./shared').isRetryableWritesSupported;\nconst relayEvents = require('../utils').relayEvents;\nconst BSON = retrieveBSON();\nconst getMMAPError = require('./shared').getMMAPError;\nconst makeClientMetadata = require('../utils').makeClientMetadata;\nconst legacyIsRetryableWriteError = require('./shared').legacyIsRetryableWriteError;\n\n/**\n * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is\n * used to construct connections.\n */\n\n//\n// States\nvar DISCONNECTED = 'disconnected';\nvar CONNECTING = 'connecting';\nvar CONNECTED = 'connected';\nvar UNREFERENCED = 'unreferenced';\nvar DESTROYING = 'destroying';\nvar DESTROYED = 'destroyed';\n\nfunction stateTransition(self, newState) {\n var legalTransitions = {\n disconnected: [CONNECTING, DESTROYING, DESTROYED, DISCONNECTED],\n connecting: [CONNECTING, DESTROYING, DESTROYED, CONNECTED, DISCONNECTED],\n connected: [CONNECTED, DISCONNECTED, DESTROYING, DESTROYED, UNREFERENCED],\n unreferenced: [UNREFERENCED, DESTROYING, DESTROYED],\n destroyed: [DESTROYED]\n };\n\n // Get current state\n var legalStates = legalTransitions[self.state];\n if (legalStates && legalStates.indexOf(newState) !== -1) {\n self.state = newState;\n } else {\n self.s.logger.error(\n f(\n 'Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]',\n self.id,\n self.state,\n newState,\n legalStates\n )\n );\n }\n}\n\n//\n// ReplSet instance id\nvar id = 1;\nvar handlers = ['connect', 'close', 'error', 'timeout', 'parseError'];\n\n/**\n * Creates a new Mongos instance\n * @class\n * @param {array} seedlist A list of seeds for the replicaset\n * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry\n * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors\n * @param {number} [options.size=5] Server connection pool size\n * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled\n * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled\n * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection\n * @param {boolean} [options.noDelay=true] TCP Connection no delay\n * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting\n * @param {number} [options.socketTimeout=0] TCP Socket timeout setting\n * @param {boolean} [options.ssl=false] Use SSL for connection\n * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.\n * @param {Buffer} [options.ca] SSL Certificate store binary buffer\n * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer\n * @param {Buffer} [options.cert] SSL Certificate binary buffer\n * @param {Buffer} [options.key] SSL Key file binary buffer\n * @param {string} [options.passphrase] SSL Certificate pass phrase\n * @param {string} [options.servername=null] String containing the server name requested via TLS SNI.\n * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates\n * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits\n * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.\n * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.\n * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.\n * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology\n * @return {Mongos} A cursor instance\n * @fires Mongos#connect\n * @fires Mongos#reconnect\n * @fires Mongos#joined\n * @fires Mongos#left\n * @fires Mongos#failed\n * @fires Mongos#fullsetup\n * @fires Mongos#all\n * @fires Mongos#serverHeartbeatStarted\n * @fires Mongos#serverHeartbeatSucceeded\n * @fires Mongos#serverHeartbeatFailed\n * @fires Mongos#topologyOpening\n * @fires Mongos#topologyClosed\n * @fires Mongos#topologyDescriptionChanged\n * @property {string} type the topology type.\n * @property {string} parserType the parser type used (c++ or js).\n */\nvar Mongos = function(seedlist, options) {\n options = options || {};\n\n // Get replSet Id\n this.id = id++;\n\n // deduplicate seedlist\n if (Array.isArray(seedlist)) {\n seedlist = seedlist.reduce((seeds, seed) => {\n if (seeds.find(s => s.host === seed.host && s.port === seed.port)) {\n return seeds;\n }\n\n seeds.push(seed);\n return seeds;\n }, []);\n }\n\n // Internal state\n this.s = {\n options: Object.assign({ metadata: makeClientMetadata(options) }, options),\n // BSON instance\n bson:\n options.bson ||\n new BSON([\n BSON.Binary,\n BSON.Code,\n BSON.DBRef,\n BSON.Decimal128,\n BSON.Double,\n BSON.Int32,\n BSON.Long,\n BSON.Map,\n BSON.MaxKey,\n BSON.MinKey,\n BSON.ObjectId,\n BSON.BSONRegExp,\n BSON.Symbol,\n BSON.Timestamp\n ]),\n // Factory overrides\n Cursor: options.cursorFactory || CoreCursor,\n // Logger instance\n logger: Logger('Mongos', options),\n // Seedlist\n seedlist: seedlist,\n // Ha interval\n haInterval: options.haInterval ? options.haInterval : 10000,\n // Disconnect handler\n disconnectHandler: options.disconnectHandler,\n // Server selection index\n index: 0,\n // Connect function options passed in\n connectOptions: {},\n // Are we running in debug mode\n debug: typeof options.debug === 'boolean' ? options.debug : false,\n // localThresholdMS\n localThresholdMS: options.localThresholdMS || 15\n };\n\n // Log info warning if the socketTimeout < haInterval as it will cause\n // a lot of recycled connections to happen.\n if (\n this.s.logger.isWarn() &&\n this.s.options.socketTimeout !== 0 &&\n this.s.options.socketTimeout < this.s.haInterval\n ) {\n this.s.logger.warn(\n f(\n 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts',\n this.s.options.socketTimeout,\n this.s.haInterval\n )\n );\n }\n\n // Disconnected state\n this.state = DISCONNECTED;\n\n // Current proxies we are connecting to\n this.connectingProxies = [];\n // Currently connected proxies\n this.connectedProxies = [];\n // Disconnected proxies\n this.disconnectedProxies = [];\n // Index of proxy to run operations against\n this.index = 0;\n // High availability timeout id\n this.haTimeoutId = null;\n // Last ismaster\n this.ismaster = null;\n\n // Description of the Replicaset\n this.topologyDescription = {\n topologyType: 'Unknown',\n servers: []\n };\n\n // Highest clusterTime seen in responses from the current deployment\n this.clusterTime = null;\n\n // Add event listener\n EventEmitter.call(this);\n};\n\ninherits(Mongos, EventEmitter);\nObject.assign(Mongos.prototype, SessionMixins);\n\nObject.defineProperty(Mongos.prototype, 'type', {\n enumerable: true,\n get: function() {\n return 'mongos';\n }\n});\n\nObject.defineProperty(Mongos.prototype, 'parserType', {\n enumerable: true,\n get: function() {\n return BSON.native ? 'c++' : 'js';\n }\n});\n\nObject.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', {\n enumerable: true,\n get: function() {\n if (!this.ismaster) return null;\n return this.ismaster.logicalSessionTimeoutMinutes || null;\n }\n});\n\n/**\n * Emit event if it exists\n * @method\n */\nfunction emitSDAMEvent(self, event, description) {\n if (self.listeners(event).length > 0) {\n self.emit(event, description);\n }\n}\n\nconst SERVER_EVENTS = ['serverDescriptionChanged', 'error', 'close', 'timeout', 'parseError'];\nfunction destroyServer(server, options, callback) {\n options = options || {};\n SERVER_EVENTS.forEach(event => server.removeAllListeners(event));\n server.destroy(options, callback);\n}\n\n/**\n * Initiate server connect\n */\nMongos.prototype.connect = function(options) {\n var self = this;\n // Add any connect level options to the internal state\n this.s.connectOptions = options || {};\n\n // Set connecting state\n stateTransition(this, CONNECTING);\n\n // Create server instances\n var servers = this.s.seedlist.map(function(x) {\n const server = new Server(\n Object.assign({}, self.s.options, x, options, {\n reconnect: false,\n monitoring: false,\n parent: self\n })\n );\n\n relayEvents(server, self, ['serverDescriptionChanged']);\n return server;\n });\n\n // Emit the topology opening event\n emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id });\n\n // Start all server connections\n connectProxies(self, servers);\n};\n\n/**\n * Authenticate the topology.\n * @method\n * @param {MongoCredentials} credentials The credentials for authentication we are using\n * @param {authResultCallback} callback A callback function\n */\nMongos.prototype.auth = function(credentials, callback) {\n if (typeof callback === 'function') callback(null, null);\n};\n\nfunction handleEvent(self) {\n return function() {\n if (self.state === DESTROYED || self.state === DESTROYING) {\n return;\n }\n\n // Move to list of disconnectedProxies\n moveServerFrom(self.connectedProxies, self.disconnectedProxies, this);\n // Emit the initial topology\n emitTopologyDescriptionChanged(self);\n // Emit the left signal\n self.emit('left', 'mongos', this);\n // Emit the sdam event\n self.emit('serverClosed', {\n topologyId: self.id,\n address: this.name\n });\n };\n}\n\nfunction handleInitialConnectEvent(self, event) {\n return function() {\n var _this = this;\n\n // Destroy the instance\n if (self.state === DESTROYED) {\n // Emit the initial topology\n emitTopologyDescriptionChanged(self);\n // Move from connectingProxies\n moveServerFrom(self.connectingProxies, self.disconnectedProxies, this);\n return this.destroy();\n }\n\n // Check the type of server\n if (event === 'connect') {\n // Get last known ismaster\n self.ismaster = _this.lastIsMaster();\n\n // Is this not a proxy, remove t\n if (self.ismaster.msg === 'isdbgrid') {\n // Add to the connectd list\n for (let i = 0; i < self.connectedProxies.length; i++) {\n if (self.connectedProxies[i].name === _this.name) {\n // Move from connectingProxies\n moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this);\n // Emit the initial topology\n emitTopologyDescriptionChanged(self);\n _this.destroy();\n return self.emit('failed', _this);\n }\n }\n\n // Remove the handlers\n for (let i = 0; i < handlers.length; i++) {\n _this.removeAllListeners(handlers[i]);\n }\n\n // Add stable state handlers\n _this.on('error', handleEvent(self, 'error'));\n _this.on('close', handleEvent(self, 'close'));\n _this.on('timeout', handleEvent(self, 'timeout'));\n _this.on('parseError', handleEvent(self, 'parseError'));\n\n // Move from connecting proxies connected\n moveServerFrom(self.connectingProxies, self.connectedProxies, _this);\n // Emit the joined event\n self.emit('joined', 'mongos', _this);\n } else {\n // Print warning if we did not find a mongos proxy\n if (self.s.logger.isWarn()) {\n var message = 'expected mongos proxy, but found replicaset member mongod for server %s';\n // We have a standalone server\n if (!self.ismaster.hosts) {\n message = 'expected mongos proxy, but found standalone mongod for server %s';\n }\n\n self.s.logger.warn(f(message, _this.name));\n }\n\n // This is not a mongos proxy, destroy and remove it completely\n _this.destroy(true);\n removeProxyFrom(self.connectingProxies, _this);\n // Emit the left event\n self.emit('left', 'server', _this);\n // Emit failed event\n self.emit('failed', _this);\n }\n } else {\n moveServerFrom(self.connectingProxies, self.disconnectedProxies, this);\n // Emit the left event\n self.emit('left', 'mongos', this);\n // Emit failed event\n self.emit('failed', this);\n }\n\n // Emit the initial topology\n emitTopologyDescriptionChanged(self);\n\n // Trigger topologyMonitor\n if (self.connectingProxies.length === 0) {\n // Emit connected if we are connected\n if (self.connectedProxies.length > 0 && self.state === CONNECTING) {\n // Set the state to connected\n stateTransition(self, CONNECTED);\n // Emit the connect event\n self.emit('connect', self);\n self.emit('fullsetup', self);\n self.emit('all', self);\n } else if (self.disconnectedProxies.length === 0) {\n // Print warning if we did not find a mongos proxy\n if (self.s.logger.isWarn()) {\n self.s.logger.warn(\n f('no mongos proxies found in seed list, did you mean to connect to a replicaset')\n );\n }\n\n // Emit the error that no proxies were found\n return self.emit('error', new MongoError('no mongos proxies found in seed list'));\n }\n\n // Topology monitor\n topologyMonitor(self, { firstConnect: true });\n }\n };\n}\n\nfunction connectProxies(self, servers) {\n // Update connectingProxies\n self.connectingProxies = self.connectingProxies.concat(servers);\n\n // Index used to interleaf the server connects, avoiding\n // runtime issues on io constrained vm's\n var timeoutInterval = 0;\n\n function connect(server, timeoutInterval) {\n setTimeout(function() {\n // Emit opening server event\n self.emit('serverOpening', {\n topologyId: self.id,\n address: server.name\n });\n\n // Emit the initial topology\n emitTopologyDescriptionChanged(self);\n\n // Add event handlers\n server.once('close', handleInitialConnectEvent(self, 'close'));\n server.once('timeout', handleInitialConnectEvent(self, 'timeout'));\n server.once('parseError', handleInitialConnectEvent(self, 'parseError'));\n server.once('error', handleInitialConnectEvent(self, 'error'));\n server.once('connect', handleInitialConnectEvent(self, 'connect'));\n\n // Command Monitoring events\n relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']);\n\n // Start connection\n server.connect(self.s.connectOptions);\n }, timeoutInterval);\n }\n\n // Start all the servers\n servers.forEach(server => connect(server, timeoutInterval++));\n}\n\nfunction pickProxy(self, session) {\n // TODO: Destructure :)\n const transaction = session && session.transaction;\n\n if (transaction && transaction.server) {\n if (transaction.server.isConnected()) {\n return transaction.server;\n } else {\n transaction.unpinServer();\n }\n }\n\n // Get the currently connected Proxies\n var connectedProxies = self.connectedProxies.slice(0);\n\n // Set lower bound\n var lowerBoundLatency = Number.MAX_VALUE;\n\n // Determine the lower bound for the Proxies\n for (var i = 0; i < connectedProxies.length; i++) {\n if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) {\n lowerBoundLatency = connectedProxies[i].lastIsMasterMS;\n }\n }\n\n // Filter out the possible servers\n connectedProxies = connectedProxies.filter(function(server) {\n if (\n server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS &&\n server.isConnected()\n ) {\n return true;\n }\n });\n\n let proxy;\n\n // We have no connectedProxies pick first of the connected ones\n if (connectedProxies.length === 0) {\n proxy = self.connectedProxies[0];\n } else {\n // Get proxy\n proxy = connectedProxies[self.index % connectedProxies.length];\n // Update the index\n self.index = (self.index + 1) % connectedProxies.length;\n }\n\n if (transaction && transaction.isActive && proxy && proxy.isConnected()) {\n transaction.pinServer(proxy);\n }\n\n // Return the proxy\n return proxy;\n}\n\nfunction moveServerFrom(from, to, proxy) {\n for (var i = 0; i < from.length; i++) {\n if (from[i].name === proxy.name) {\n from.splice(i, 1);\n }\n }\n\n for (i = 0; i < to.length; i++) {\n if (to[i].name === proxy.name) {\n to.splice(i, 1);\n }\n }\n\n to.push(proxy);\n}\n\nfunction removeProxyFrom(from, proxy) {\n for (var i = 0; i < from.length; i++) {\n if (from[i].name === proxy.name) {\n from.splice(i, 1);\n }\n }\n}\n\nfunction reconnectProxies(self, proxies, callback) {\n // Count lefts\n var count = proxies.length;\n\n // Handle events\n var _handleEvent = function(self, event) {\n return function() {\n var _self = this;\n count = count - 1;\n\n // Destroyed\n if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) {\n moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self);\n return this.destroy();\n }\n\n if (event === 'connect') {\n // Destroyed\n if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) {\n moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self);\n return _self.destroy();\n }\n\n // Remove the handlers\n for (var i = 0; i < handlers.length; i++) {\n _self.removeAllListeners(handlers[i]);\n }\n\n // Add stable state handlers\n _self.on('error', handleEvent(self, 'error'));\n _self.on('close', handleEvent(self, 'close'));\n _self.on('timeout', handleEvent(self, 'timeout'));\n _self.on('parseError', handleEvent(self, 'parseError'));\n\n // Move to the connected servers\n moveServerFrom(self.connectingProxies, self.connectedProxies, _self);\n // Emit topology Change\n emitTopologyDescriptionChanged(self);\n // Emit joined event\n self.emit('joined', 'mongos', _self);\n } else {\n // Move from connectingProxies\n moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self);\n this.destroy();\n }\n\n // Are we done finish up callback\n if (count === 0) {\n callback();\n }\n };\n };\n\n // No new servers\n if (count === 0) {\n return callback();\n }\n\n // Execute method\n function execute(_server, i) {\n setTimeout(function() {\n // Destroyed\n if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) {\n return;\n }\n\n // Create a new server instance\n var server = new Server(\n Object.assign({}, self.s.options, {\n host: _server.name.split(':')[0],\n port: parseInt(_server.name.split(':')[1], 10),\n reconnect: false,\n monitoring: false,\n parent: self\n })\n );\n\n destroyServer(_server, { force: true });\n removeProxyFrom(self.disconnectedProxies, _server);\n\n // Relay the server description change\n relayEvents(server, self, ['serverDescriptionChanged']);\n\n // Emit opening server event\n self.emit('serverOpening', {\n topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id,\n address: server.name\n });\n\n // Add temp handlers\n server.once('connect', _handleEvent(self, 'connect'));\n server.once('close', _handleEvent(self, 'close'));\n server.once('timeout', _handleEvent(self, 'timeout'));\n server.once('error', _handleEvent(self, 'error'));\n server.once('parseError', _handleEvent(self, 'parseError'));\n\n // Command Monitoring events\n relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']);\n\n // Connect to proxy\n self.connectingProxies.push(server);\n server.connect(self.s.connectOptions);\n }, i);\n }\n\n // Create new instances\n for (var i = 0; i < proxies.length; i++) {\n execute(proxies[i], i);\n }\n}\n\nfunction topologyMonitor(self, options) {\n options = options || {};\n\n // no need to set up the monitor if we're already closed\n if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) {\n return;\n }\n\n // Set momitoring timeout\n self.haTimeoutId = setTimeout(function() {\n if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) {\n return;\n }\n\n // If we have a primary and a disconnect handler, execute\n // buffered operations\n if (self.isConnected() && self.s.disconnectHandler) {\n self.s.disconnectHandler.execute();\n }\n\n // Get the connectingServers\n var proxies = self.connectedProxies.slice(0);\n // Get the count\n var count = proxies.length;\n\n // If the count is zero schedule a new fast\n function pingServer(_self, _server, cb) {\n // Measure running time\n var start = new Date().getTime();\n\n // Emit the server heartbeat start\n emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name });\n\n // Execute ismaster\n _server.command(\n 'admin.$cmd',\n {\n ismaster: true\n },\n {\n monitoring: true,\n socketTimeout: self.s.options.connectionTimeout || 2000\n },\n function(err, r) {\n if (\n self.state === DESTROYED ||\n self.state === DESTROYING ||\n self.state === UNREFERENCED\n ) {\n // Move from connectingProxies\n moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server);\n _server.destroy();\n return cb(err, r);\n }\n\n // Calculate latency\n var latencyMS = new Date().getTime() - start;\n\n // We had an error, remove it from the state\n if (err) {\n // Emit the server heartbeat failure\n emitSDAMEvent(self, 'serverHeartbeatFailed', {\n durationMS: latencyMS,\n failure: err,\n connectionId: _server.name\n });\n // Move from connected proxies to disconnected proxies\n moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server);\n } else {\n // Update the server ismaster\n _server.ismaster = r.result;\n _server.lastIsMasterMS = latencyMS;\n\n // Server heart beat event\n emitSDAMEvent(self, 'serverHeartbeatSucceeded', {\n durationMS: latencyMS,\n reply: r.result,\n connectionId: _server.name\n });\n }\n\n cb(err, r);\n }\n );\n }\n\n // No proxies initiate monitor again\n if (proxies.length === 0) {\n // Emit close event if any listeners registered\n if (self.listeners('close').length > 0 && self.state === CONNECTING) {\n self.emit('error', new MongoError('no mongos proxy available'));\n } else {\n self.emit('close', self);\n }\n\n // Attempt to connect to any unknown servers\n return reconnectProxies(self, self.disconnectedProxies, function() {\n if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) {\n return;\n }\n\n // Are we connected ? emit connect event\n if (self.state === CONNECTING && options.firstConnect) {\n self.emit('connect', self);\n self.emit('fullsetup', self);\n self.emit('all', self);\n } else if (self.isConnected()) {\n self.emit('reconnect', self);\n } else if (!self.isConnected() && self.listeners('close').length > 0) {\n self.emit('close', self);\n }\n\n // Perform topology monitor\n topologyMonitor(self);\n });\n }\n\n // Ping all servers\n for (var i = 0; i < proxies.length; i++) {\n pingServer(self, proxies[i], function() {\n count = count - 1;\n\n if (count === 0) {\n if (\n self.state === DESTROYED ||\n self.state === DESTROYING ||\n self.state === UNREFERENCED\n ) {\n return;\n }\n\n // Attempt to connect to any unknown servers\n reconnectProxies(self, self.disconnectedProxies, function() {\n if (\n self.state === DESTROYED ||\n self.state === DESTROYING ||\n self.state === UNREFERENCED\n ) {\n return;\n }\n\n // Perform topology monitor\n topologyMonitor(self);\n });\n }\n });\n }\n }, self.s.haInterval);\n}\n\n/**\n * Returns the last known ismaster document for this server\n * @method\n * @return {object}\n */\nMongos.prototype.lastIsMaster = function() {\n return this.ismaster;\n};\n\n/**\n * Unref all connections belong to this server\n * @method\n */\nMongos.prototype.unref = function() {\n // Transition state\n stateTransition(this, UNREFERENCED);\n // Get all proxies\n var proxies = this.connectedProxies.concat(this.connectingProxies);\n proxies.forEach(function(x) {\n x.unref();\n });\n\n clearTimeout(this.haTimeoutId);\n};\n\n/**\n * Destroy the server connection\n * @param {boolean} [options.force=false] Force destroy the pool\n * @method\n */\nMongos.prototype.destroy = function(options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n options = options || {};\n\n stateTransition(this, DESTROYING);\n if (this.haTimeoutId) {\n clearTimeout(this.haTimeoutId);\n }\n\n const proxies = this.connectedProxies.concat(this.connectingProxies);\n let serverCount = proxies.length;\n const serverDestroyed = () => {\n serverCount--;\n if (serverCount > 0) {\n return;\n }\n\n emitTopologyDescriptionChanged(this);\n emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id });\n stateTransition(this, DESTROYED);\n if (typeof callback === 'function') {\n callback(null, null);\n }\n };\n\n if (serverCount === 0) {\n serverDestroyed();\n return;\n }\n\n // Destroy all connecting servers\n proxies.forEach(server => {\n // Emit the sdam event\n this.emit('serverClosed', {\n topologyId: this.id,\n address: server.name\n });\n\n destroyServer(server, options, serverDestroyed);\n moveServerFrom(this.connectedProxies, this.disconnectedProxies, server);\n });\n};\n\n/**\n * Figure out if the server is connected\n * @method\n * @return {boolean}\n */\nMongos.prototype.isConnected = function() {\n return this.connectedProxies.length > 0;\n};\n\n/**\n * Figure out if the server instance was destroyed by calling destroy\n * @method\n * @return {boolean}\n */\nMongos.prototype.isDestroyed = function() {\n return this.state === DESTROYED;\n};\n\n//\n// Operations\n//\n\nfunction executeWriteOperation(args, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n // TODO: once we drop Node 4, use destructuring either here or in arguments.\n const self = args.self;\n const op = args.op;\n const ns = args.ns;\n const ops = args.ops;\n\n // Pick a server\n let server = pickProxy(self, options.session);\n // No server found error out\n if (!server) return callback(new MongoError('no mongos proxy available'));\n\n const willRetryWrite =\n !args.retrying &&\n !!options.retryWrites &&\n options.session &&\n isRetryableWritesSupported(self) &&\n !options.session.inTransaction();\n\n const handler = (err, result) => {\n if (!err) return callback(null, result);\n if (!legacyIsRetryableWriteError(err, self) || !willRetryWrite) {\n err = getMMAPError(err);\n return callback(err);\n }\n\n // Pick another server\n server = pickProxy(self, options.session);\n\n // No server found error out with original error\n if (!server) {\n return callback(err);\n }\n\n const newArgs = Object.assign({}, args, { retrying: true });\n return executeWriteOperation(newArgs, options, callback);\n };\n\n if (callback.operationId) {\n handler.operationId = callback.operationId;\n }\n\n // increment and assign txnNumber\n if (willRetryWrite) {\n options.session.incrementTransactionNumber();\n options.willRetryWrite = willRetryWrite;\n }\n\n // rerun the operation\n server[op](ns, ops, options, handler);\n}\n\n/**\n * Insert one or more documents\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of documents to insert\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {boolean} [options.retryWrites] Enable retryable writes for this operation\n * @param {opResultCallback} callback A callback function\n */\nMongos.prototype.insert = function(ns, ops, options, callback) {\n if (typeof options === 'function') {\n (callback = options), (options = {}), (options = options || {});\n }\n\n if (this.state === DESTROYED) {\n return callback(new MongoError(f('topology was destroyed')));\n }\n\n // Not connected but we have a disconnecthandler\n if (!this.isConnected() && this.s.disconnectHandler != null) {\n return this.s.disconnectHandler.add('insert', ns, ops, options, callback);\n }\n\n // No mongos proxy available\n if (!this.isConnected()) {\n return callback(new MongoError('no mongos proxy available'));\n }\n\n // Execute write operation\n executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback);\n};\n\n/**\n * Perform one or more update operations\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of updates\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {boolean} [options.retryWrites] Enable retryable writes for this operation\n * @param {opResultCallback} callback A callback function\n */\nMongos.prototype.update = function(ns, ops, options, callback) {\n if (typeof options === 'function') {\n (callback = options), (options = {}), (options = options || {});\n }\n\n if (this.state === DESTROYED) {\n return callback(new MongoError(f('topology was destroyed')));\n }\n\n // Not connected but we have a disconnecthandler\n if (!this.isConnected() && this.s.disconnectHandler != null) {\n return this.s.disconnectHandler.add('update', ns, ops, options, callback);\n }\n\n // No mongos proxy available\n if (!this.isConnected()) {\n return callback(new MongoError('no mongos proxy available'));\n }\n\n // Execute write operation\n executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback);\n};\n\n/**\n * Perform one or more remove operations\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of removes\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {boolean} [options.retryWrites] Enable retryable writes for this operation\n * @param {opResultCallback} callback A callback function\n */\nMongos.prototype.remove = function(ns, ops, options, callback) {\n if (typeof options === 'function') {\n (callback = options), (options = {}), (options = options || {});\n }\n\n if (this.state === DESTROYED) {\n return callback(new MongoError(f('topology was destroyed')));\n }\n\n // Not connected but we have a disconnecthandler\n if (!this.isConnected() && this.s.disconnectHandler != null) {\n return this.s.disconnectHandler.add('remove', ns, ops, options, callback);\n }\n\n // No mongos proxy available\n if (!this.isConnected()) {\n return callback(new MongoError('no mongos proxy available'));\n }\n\n // Execute write operation\n executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback);\n};\n\nconst RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete'];\n\nfunction isWriteCommand(command) {\n return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]);\n}\n\n/**\n * Execute a command\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object} cmd The command hash\n * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it\n * @param {Connection} [options.connection] Specify connection object to execute command against\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {opResultCallback} callback A callback function\n */\nMongos.prototype.command = function(ns, cmd, options, callback) {\n if (typeof options === 'function') {\n (callback = options), (options = {}), (options = options || {});\n }\n\n if (this.state === DESTROYED) {\n return callback(new MongoError(f('topology was destroyed')));\n }\n\n var self = this;\n\n // Pick a proxy\n var server = pickProxy(self, options.session);\n\n // Topology is not connected, save the call in the provided store to be\n // Executed at some point when the handler deems it's reconnected\n if ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) {\n return this.s.disconnectHandler.add('command', ns, cmd, options, callback);\n }\n\n // No server returned we had an error\n if (server == null) {\n return callback(new MongoError('no mongos proxy available'));\n }\n\n // Cloned options\n var clonedOptions = cloneOptions(options);\n clonedOptions.topology = self;\n\n const willRetryWrite =\n !options.retrying &&\n options.retryWrites &&\n options.session &&\n isRetryableWritesSupported(self) &&\n !options.session.inTransaction() &&\n isWriteCommand(cmd);\n\n const cb = (err, result) => {\n if (!err) return callback(null, result);\n if (!legacyIsRetryableWriteError(err, self)) {\n return callback(err);\n }\n\n if (willRetryWrite) {\n const newOptions = Object.assign({}, clonedOptions, { retrying: true });\n return this.command(ns, cmd, newOptions, callback);\n }\n\n return callback(err);\n };\n\n // increment and assign txnNumber\n if (willRetryWrite) {\n clonedOptions.session.incrementTransactionNumber();\n clonedOptions.willRetryWrite = willRetryWrite;\n }\n\n // Execute the command\n server.command(ns, cmd, clonedOptions, cb);\n};\n\n/**\n * Get a new cursor\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId\n * @param {object} [options] Options for the cursor\n * @param {object} [options.batchSize=0] Batchsize for the operation\n * @param {array} [options.documents=[]] Initial documents list for cursor\n * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {object} [options.topology] The internal topology of the created cursor\n * @returns {Cursor}\n */\nMongos.prototype.cursor = function(ns, cmd, options) {\n options = options || {};\n const topology = options.topology || this;\n\n // Set up final cursor type\n var FinalCursor = options.cursorFactory || this.s.Cursor;\n\n // Return the cursor\n return new FinalCursor(topology, ns, cmd, options);\n};\n\n/**\n * Selects a server\n *\n * @method\n * @param {function} selector Unused\n * @param {ReadPreference} [options.readPreference] Unused\n * @param {ClientSession} [options.session] Specify a session if it is being used\n * @param {function} callback\n */\nMongos.prototype.selectServer = function(selector, options, callback) {\n if (typeof selector === 'function' && typeof callback === 'undefined')\n (callback = selector), (selector = undefined), (options = {});\n if (typeof options === 'function')\n (callback = options), (options = selector), (selector = undefined);\n options = options || {};\n\n const server = pickProxy(this, options.session);\n if (server == null) {\n callback(new MongoError('server selection failed'));\n return;\n }\n\n if (this.s.debug) this.emit('pickedServer', null, server);\n callback(null, server);\n};\n\n/**\n * All raw connections\n * @method\n * @return {Connection[]}\n */\nMongos.prototype.connections = function() {\n var connections = [];\n\n for (var i = 0; i < this.connectedProxies.length; i++) {\n connections = connections.concat(this.connectedProxies[i].connections());\n }\n\n return connections;\n};\n\nfunction emitTopologyDescriptionChanged(self) {\n if (self.listeners('topologyDescriptionChanged').length > 0) {\n var topology = 'Unknown';\n if (self.connectedProxies.length > 0) {\n topology = 'Sharded';\n }\n\n // Generate description\n var description = {\n topologyType: topology,\n servers: []\n };\n\n // All proxies\n var proxies = self.disconnectedProxies.concat(self.connectingProxies);\n\n // Add all the disconnected proxies\n description.servers = description.servers.concat(\n proxies.map(function(x) {\n var description = x.getDescription();\n description.type = 'Unknown';\n return description;\n })\n );\n\n // Add all the connected proxies\n description.servers = description.servers.concat(\n self.connectedProxies.map(function(x) {\n var description = x.getDescription();\n description.type = 'Mongos';\n return description;\n })\n );\n\n // Get the diff\n var diffResult = diff(self.topologyDescription, description);\n\n // Create the result\n var result = {\n topologyId: self.id,\n previousDescription: self.topologyDescription,\n newDescription: description,\n diff: diffResult\n };\n\n // Emit the topologyDescription change\n if (diffResult.servers.length > 0) {\n self.emit('topologyDescriptionChanged', result);\n }\n\n // Set the new description\n self.topologyDescription = description;\n }\n}\n\n/**\n * A mongos connect event, used to verify that the connection is up and running\n *\n * @event Mongos#connect\n * @type {Mongos}\n */\n\n/**\n * A mongos reconnect event, used to verify that the mongos topology has reconnected\n *\n * @event Mongos#reconnect\n * @type {Mongos}\n */\n\n/**\n * A mongos fullsetup event, used to signal that all topology members have been contacted.\n *\n * @event Mongos#fullsetup\n * @type {Mongos}\n */\n\n/**\n * A mongos all event, used to signal that all topology members have been contacted.\n *\n * @event Mongos#all\n * @type {Mongos}\n */\n\n/**\n * A server member left the mongos list\n *\n * @event Mongos#left\n * @type {Mongos}\n * @param {string} type The type of member that left (mongos)\n * @param {Server} server The server object that left\n */\n\n/**\n * A server member joined the mongos list\n *\n * @event Mongos#joined\n * @type {Mongos}\n * @param {string} type The type of member that left (mongos)\n * @param {Server} server The server object that joined\n */\n\n/**\n * A server opening SDAM monitoring event\n *\n * @event Mongos#serverOpening\n * @type {object}\n */\n\n/**\n * A server closed SDAM monitoring event\n *\n * @event Mongos#serverClosed\n * @type {object}\n */\n\n/**\n * A server description SDAM change monitoring event\n *\n * @event Mongos#serverDescriptionChanged\n * @type {object}\n */\n\n/**\n * A topology open SDAM event\n *\n * @event Mongos#topologyOpening\n * @type {object}\n */\n\n/**\n * A topology closed SDAM event\n *\n * @event Mongos#topologyClosed\n * @type {object}\n */\n\n/**\n * A topology structure SDAM change event\n *\n * @event Mongos#topologyDescriptionChanged\n * @type {object}\n */\n\n/**\n * A topology serverHeartbeatStarted SDAM event\n *\n * @event Mongos#serverHeartbeatStarted\n * @type {object}\n */\n\n/**\n * A topology serverHeartbeatFailed SDAM event\n *\n * @event Mongos#serverHeartbeatFailed\n * @type {object}\n */\n\n/**\n * A topology serverHeartbeatSucceeded SDAM change event\n *\n * @event Mongos#serverHeartbeatSucceeded\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command was started, if command monitoring is enabled\n *\n * @event Mongos#commandStarted\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command succeeded, if command monitoring is enabled\n *\n * @event Mongos#commandSucceeded\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command failed, if command monitoring is enabled\n *\n * @event Mongos#commandFailed\n * @type {object}\n */\n\nmodule.exports = Mongos;\n","'use strict';\n\n/**\n * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is\n * used to construct connections.\n * @class\n * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest)\n * @param {array} tags The tags object\n * @param {object} [options] Additional read preference options\n * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds.\n * @param {object} [options.hedge] Server mode in which the same query is dispatched in parallel to multiple replica set members.\n * @param {boolean} [options.hedge.enabled] Explicitly enable or disable hedged reads.\n * @see https://docs.mongodb.com/manual/core/read-preference/\n * @return {ReadPreference}\n */\nconst ReadPreference = function(mode, tags, options) {\n if (!ReadPreference.isValid(mode)) {\n throw new TypeError(`Invalid read preference mode ${mode}`);\n }\n\n // TODO(major): tags MUST be an array of tagsets\n if (tags && !Array.isArray(tags)) {\n console.warn(\n 'ReadPreference tags must be an array, this will change in the next major version'\n );\n\n const tagsHasMaxStalenessSeconds = typeof tags.maxStalenessSeconds !== 'undefined';\n const tagsHasHedge = typeof tags.hedge !== 'undefined';\n const tagsHasOptions = tagsHasMaxStalenessSeconds || tagsHasHedge;\n if (tagsHasOptions) {\n // this is likely an options object\n options = tags;\n tags = undefined;\n } else {\n tags = [tags];\n }\n }\n\n this.mode = mode;\n this.tags = tags;\n this.hedge = options && options.hedge;\n\n options = options || {};\n if (options.maxStalenessSeconds != null) {\n if (options.maxStalenessSeconds <= 0) {\n throw new TypeError('maxStalenessSeconds must be a positive integer');\n }\n\n this.maxStalenessSeconds = options.maxStalenessSeconds;\n\n // NOTE: The minimum required wire version is 5 for this read preference. If the existing\n // topology has a lower value then a MongoError will be thrown during server selection.\n this.minWireVersion = 5;\n }\n\n if (this.mode === ReadPreference.PRIMARY) {\n if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) {\n throw new TypeError('Primary read preference cannot be combined with tags');\n }\n\n if (this.maxStalenessSeconds) {\n throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds');\n }\n\n if (this.hedge) {\n throw new TypeError('Primary read preference cannot be combined with hedge');\n }\n }\n};\n\n// Support the deprecated `preference` property introduced in the porcelain layer\nObject.defineProperty(ReadPreference.prototype, 'preference', {\n enumerable: true,\n get: function() {\n return this.mode;\n }\n});\n\n/*\n * Read preference mode constants\n */\nReadPreference.PRIMARY = 'primary';\nReadPreference.PRIMARY_PREFERRED = 'primaryPreferred';\nReadPreference.SECONDARY = 'secondary';\nReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred';\nReadPreference.NEAREST = 'nearest';\n\nconst VALID_MODES = [\n ReadPreference.PRIMARY,\n ReadPreference.PRIMARY_PREFERRED,\n ReadPreference.SECONDARY,\n ReadPreference.SECONDARY_PREFERRED,\n ReadPreference.NEAREST,\n null\n];\n\n/**\n * Construct a ReadPreference given an options object.\n *\n * @param {object} options The options object from which to extract the read preference.\n * @return {ReadPreference}\n */\nReadPreference.fromOptions = function(options) {\n if (!options) return null;\n const readPreference = options.readPreference;\n if (!readPreference) return null;\n const readPreferenceTags = options.readPreferenceTags;\n const maxStalenessSeconds = options.maxStalenessSeconds;\n if (typeof readPreference === 'string') {\n return new ReadPreference(readPreference, readPreferenceTags);\n } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') {\n const mode = readPreference.mode || readPreference.preference;\n if (mode && typeof mode === 'string') {\n return new ReadPreference(mode, readPreference.tags, {\n maxStalenessSeconds: readPreference.maxStalenessSeconds || maxStalenessSeconds,\n hedge: readPreference.hedge\n });\n }\n }\n\n return readPreference;\n};\n\n/**\n * Resolves a read preference based on well-defined inheritance rules. This method will not only\n * determine the read preference (if there is one), but will also ensure the returned value is a\n * properly constructed instance of `ReadPreference`.\n *\n * @param {Collection|Db|MongoClient} parent The parent of the operation on which to determine the read\n * preference, used for determining the inherited read preference.\n * @param {object} options The options passed into the method, potentially containing a read preference\n * @returns {(ReadPreference|null)} The resolved read preference\n */\nReadPreference.resolve = function(parent, options) {\n options = options || {};\n const session = options.session;\n\n const inheritedReadPreference = parent && parent.readPreference;\n\n let readPreference;\n if (options.readPreference) {\n readPreference = ReadPreference.fromOptions(options);\n } else if (session && session.inTransaction() && session.transaction.options.readPreference) {\n // The transaction’s read preference MUST override all other user configurable read preferences.\n readPreference = session.transaction.options.readPreference;\n } else if (inheritedReadPreference != null) {\n readPreference = inheritedReadPreference;\n } else {\n readPreference = ReadPreference.primary;\n }\n\n return typeof readPreference === 'string' ? new ReadPreference(readPreference) : readPreference;\n};\n\n/**\n * Replaces options.readPreference with a ReadPreference instance\n */\nReadPreference.translate = function(options) {\n if (options.readPreference == null) return options;\n const r = options.readPreference;\n\n if (typeof r === 'string') {\n options.readPreference = new ReadPreference(r);\n } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') {\n const mode = r.mode || r.preference;\n if (mode && typeof mode === 'string') {\n options.readPreference = new ReadPreference(mode, r.tags, {\n maxStalenessSeconds: r.maxStalenessSeconds\n });\n }\n } else if (!(r instanceof ReadPreference)) {\n throw new TypeError('Invalid read preference: ' + r);\n }\n\n return options;\n};\n\n/**\n * Validate if a mode is legal\n *\n * @method\n * @param {string} mode The string representing the read preference mode.\n * @return {boolean} True if a mode is valid\n */\nReadPreference.isValid = function(mode) {\n return VALID_MODES.indexOf(mode) !== -1;\n};\n\n/**\n * Validate if a mode is legal\n *\n * @method\n * @param {string} mode The string representing the read preference mode.\n * @return {boolean} True if a mode is valid\n */\nReadPreference.prototype.isValid = function(mode) {\n return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode);\n};\n\nconst needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest'];\n\n/**\n * Indicates that this readPreference needs the \"slaveOk\" bit when sent over the wire\n * @method\n * @return {boolean}\n * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query\n */\nReadPreference.prototype.slaveOk = function() {\n return needSlaveOk.indexOf(this.mode) !== -1;\n};\n\n/**\n * Are the two read preference equal\n * @method\n * @param {ReadPreference} readPreference The read preference with which to check equality\n * @return {boolean} True if the two ReadPreferences are equivalent\n */\nReadPreference.prototype.equals = function(readPreference) {\n return readPreference.mode === this.mode;\n};\n\n/**\n * Return JSON representation\n * @method\n * @return {Object} A JSON representation of the ReadPreference\n */\nReadPreference.prototype.toJSON = function() {\n const readPreference = { mode: this.mode };\n if (Array.isArray(this.tags)) readPreference.tags = this.tags;\n if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds;\n if (this.hedge) readPreference.hedge = this.hedge;\n return readPreference;\n};\n\n/**\n * Primary read preference\n * @member\n * @type {ReadPreference}\n */\nReadPreference.primary = new ReadPreference('primary');\n/**\n * Primary Preferred read preference\n * @member\n * @type {ReadPreference}\n */\nReadPreference.primaryPreferred = new ReadPreference('primaryPreferred');\n/**\n * Secondary read preference\n * @member\n * @type {ReadPreference}\n */\nReadPreference.secondary = new ReadPreference('secondary');\n/**\n * Secondary Preferred read preference\n * @member\n * @type {ReadPreference}\n */\nReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred');\n/**\n * Nearest read preference\n * @member\n * @type {ReadPreference}\n */\nReadPreference.nearest = new ReadPreference('nearest');\n\nmodule.exports = ReadPreference;\n","'use strict';\n\nconst inherits = require('util').inherits;\nconst f = require('util').format;\nconst EventEmitter = require('events').EventEmitter;\nconst ReadPreference = require('./read_preference');\nconst CoreCursor = require('../cursor').CoreCursor;\nconst retrieveBSON = require('../connection/utils').retrieveBSON;\nconst Logger = require('../connection/logger');\nconst MongoError = require('../error').MongoError;\nconst Server = require('./server');\nconst ReplSetState = require('./replset_state');\nconst Timeout = require('./shared').Timeout;\nconst Interval = require('./shared').Interval;\nconst SessionMixins = require('./shared').SessionMixins;\nconst isRetryableWritesSupported = require('./shared').isRetryableWritesSupported;\nconst relayEvents = require('../utils').relayEvents;\nconst BSON = retrieveBSON();\nconst getMMAPError = require('./shared').getMMAPError;\nconst makeClientMetadata = require('../utils').makeClientMetadata;\nconst legacyIsRetryableWriteError = require('./shared').legacyIsRetryableWriteError;\nconst now = require('../../utils').now;\nconst calculateDurationInMs = require('../../utils').calculateDurationInMs;\n\n//\n// States\nvar DISCONNECTED = 'disconnected';\nvar CONNECTING = 'connecting';\nvar CONNECTED = 'connected';\nvar UNREFERENCED = 'unreferenced';\nvar DESTROYED = 'destroyed';\n\nfunction stateTransition(self, newState) {\n var legalTransitions = {\n disconnected: [CONNECTING, DESTROYED, DISCONNECTED],\n connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED],\n connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED],\n unreferenced: [UNREFERENCED, DESTROYED],\n destroyed: [DESTROYED]\n };\n\n // Get current state\n var legalStates = legalTransitions[self.state];\n if (legalStates && legalStates.indexOf(newState) !== -1) {\n self.state = newState;\n } else {\n self.s.logger.error(\n f(\n 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]',\n self.id,\n self.state,\n newState,\n legalStates\n )\n );\n }\n}\n\n//\n// ReplSet instance id\nvar id = 1;\nvar handlers = ['connect', 'close', 'error', 'timeout', 'parseError'];\n\n/**\n * Creates a new Replset instance\n * @class\n * @param {array} seedlist A list of seeds for the replicaset\n * @param {boolean} options.setName The Replicaset set name\n * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset\n * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry\n * @param {boolean} [options.emitError=false] Server will emit errors events\n * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors\n * @param {number} [options.size=5] Server connection pool size\n * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled\n * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled\n * @param {boolean} [options.noDelay=true] TCP Connection no delay\n * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting\n * @param {number} [options.socketTimeout=0] TCP Socket timeout setting\n * @param {boolean} [options.ssl=false] Use SSL for connection\n * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.\n * @param {Buffer} [options.ca] SSL Certificate store binary buffer\n * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer\n * @param {Buffer} [options.cert] SSL Certificate binary buffer\n * @param {Buffer} [options.key] SSL Key file binary buffer\n * @param {string} [options.passphrase] SSL Certificate pass phrase\n * @param {string} [options.servername=null] String containing the server name requested via TLS SNI.\n * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates\n * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits\n * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.\n * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.\n * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers\n * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection\n * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.\n * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology\n * @return {ReplSet} A cursor instance\n * @fires ReplSet#connect\n * @fires ReplSet#ha\n * @fires ReplSet#joined\n * @fires ReplSet#left\n * @fires ReplSet#failed\n * @fires ReplSet#fullsetup\n * @fires ReplSet#all\n * @fires ReplSet#error\n * @fires ReplSet#serverHeartbeatStarted\n * @fires ReplSet#serverHeartbeatSucceeded\n * @fires ReplSet#serverHeartbeatFailed\n * @fires ReplSet#topologyOpening\n * @fires ReplSet#topologyClosed\n * @fires ReplSet#topologyDescriptionChanged\n * @property {string} type the topology type.\n * @property {string} parserType the parser type used (c++ or js).\n */\nvar ReplSet = function(seedlist, options) {\n var self = this;\n options = options || {};\n\n // Validate seedlist\n if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array');\n // Validate list\n if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry');\n // Validate entries\n seedlist.forEach(function(e) {\n if (typeof e.host !== 'string' || typeof e.port !== 'number')\n throw new MongoError('seedlist entry must contain a host and port');\n });\n\n // Add event listener\n EventEmitter.call(this);\n\n // Get replSet Id\n this.id = id++;\n\n // Get the localThresholdMS\n var localThresholdMS = options.localThresholdMS || 15;\n // Backward compatibility\n if (options.acceptableLatency) localThresholdMS = options.acceptableLatency;\n\n // Create a logger\n var logger = Logger('ReplSet', options);\n\n // Internal state\n this.s = {\n options: Object.assign({ metadata: makeClientMetadata(options) }, options),\n // BSON instance\n bson:\n options.bson ||\n new BSON([\n BSON.Binary,\n BSON.Code,\n BSON.DBRef,\n BSON.Decimal128,\n BSON.Double,\n BSON.Int32,\n BSON.Long,\n BSON.Map,\n BSON.MaxKey,\n BSON.MinKey,\n BSON.ObjectId,\n BSON.BSONRegExp,\n BSON.Symbol,\n BSON.Timestamp\n ]),\n // Factory overrides\n Cursor: options.cursorFactory || CoreCursor,\n // Logger instance\n logger: logger,\n // Seedlist\n seedlist: seedlist,\n // Replicaset state\n replicaSetState: new ReplSetState({\n id: this.id,\n setName: options.setName,\n acceptableLatency: localThresholdMS,\n heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000,\n logger: logger\n }),\n // Current servers we are connecting to\n connectingServers: [],\n // Ha interval\n haInterval: options.haInterval ? options.haInterval : 10000,\n // Minimum heartbeat frequency used if we detect a server close\n minHeartbeatFrequencyMS: 500,\n // Disconnect handler\n disconnectHandler: options.disconnectHandler,\n // Server selection index\n index: 0,\n // Connect function options passed in\n connectOptions: {},\n // Are we running in debug mode\n debug: typeof options.debug === 'boolean' ? options.debug : false\n };\n\n // Add handler for topology change\n this.s.replicaSetState.on('topologyDescriptionChanged', function(r) {\n self.emit('topologyDescriptionChanged', r);\n });\n\n // Log info warning if the socketTimeout < haInterval as it will cause\n // a lot of recycled connections to happen.\n if (\n this.s.logger.isWarn() &&\n this.s.options.socketTimeout !== 0 &&\n this.s.options.socketTimeout < this.s.haInterval\n ) {\n this.s.logger.warn(\n f(\n 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts',\n this.s.options.socketTimeout,\n this.s.haInterval\n )\n );\n }\n\n // Add forwarding of events from state handler\n var types = ['joined', 'left'];\n types.forEach(function(x) {\n self.s.replicaSetState.on(x, function(t, s) {\n self.emit(x, t, s);\n });\n });\n\n // Connect stat\n this.initialConnectState = {\n connect: false,\n fullsetup: false,\n all: false\n };\n\n // Disconnected state\n this.state = DISCONNECTED;\n this.haTimeoutId = null;\n // Last ismaster\n this.ismaster = null;\n // Contains the intervalId\n this.intervalIds = [];\n\n // Highest clusterTime seen in responses from the current deployment\n this.clusterTime = null;\n};\n\ninherits(ReplSet, EventEmitter);\nObject.assign(ReplSet.prototype, SessionMixins);\n\nObject.defineProperty(ReplSet.prototype, 'type', {\n enumerable: true,\n get: function() {\n return 'replset';\n }\n});\n\nObject.defineProperty(ReplSet.prototype, 'parserType', {\n enumerable: true,\n get: function() {\n return BSON.native ? 'c++' : 'js';\n }\n});\n\nObject.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', {\n enumerable: true,\n get: function() {\n return this.s.replicaSetState.logicalSessionTimeoutMinutes || null;\n }\n});\n\nfunction rexecuteOperations(self) {\n // If we have a primary and a disconnect handler, execute\n // buffered operations\n if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) {\n self.s.disconnectHandler.execute();\n } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) {\n self.s.disconnectHandler.execute({ executePrimary: true });\n } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) {\n self.s.disconnectHandler.execute({ executeSecondary: true });\n }\n}\n\nfunction connectNewServers(self, servers, callback) {\n // No new servers\n if (servers.length === 0) {\n return callback();\n }\n\n // Count lefts\n var count = servers.length;\n var error = null;\n\n function done() {\n count = count - 1;\n if (count === 0) {\n callback(error);\n }\n }\n\n // Handle events\n var _handleEvent = function(self, event) {\n return function(err) {\n var _self = this;\n\n // Destroyed\n if (self.state === DESTROYED || self.state === UNREFERENCED) {\n this.destroy({ force: true });\n return done();\n }\n\n if (event === 'connect') {\n // Update the state\n var result = self.s.replicaSetState.update(_self);\n // Update the state with the new server\n if (result) {\n // Primary lastIsMaster store it\n if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) {\n self.ismaster = _self.lastIsMaster();\n }\n\n // Remove the handlers\n for (let i = 0; i < handlers.length; i++) {\n _self.removeAllListeners(handlers[i]);\n }\n\n // Add stable state handlers\n _self.on('error', handleEvent(self, 'error'));\n _self.on('close', handleEvent(self, 'close'));\n _self.on('timeout', handleEvent(self, 'timeout'));\n _self.on('parseError', handleEvent(self, 'parseError'));\n\n // Enalbe the monitoring of the new server\n monitorServer(_self.lastIsMaster().me, self, {});\n\n // Rexecute any stalled operation\n rexecuteOperations(self);\n } else {\n _self.destroy({ force: true });\n }\n } else if (event === 'error') {\n error = err;\n }\n\n // Rexecute any stalled operation\n rexecuteOperations(self);\n done();\n };\n };\n\n // Execute method\n function execute(_server, i) {\n setTimeout(function() {\n // Destroyed\n if (self.state === DESTROYED || self.state === UNREFERENCED) {\n return;\n }\n\n // remove existing connecting server if it's failed to connect, otherwise\n // wait for that server to connect\n const existingServerIdx = self.s.connectingServers.findIndex(s => s.name === _server);\n if (existingServerIdx >= 0) {\n const connectingServer = self.s.connectingServers[existingServerIdx];\n connectingServer.destroy({ force: true });\n\n self.s.connectingServers.splice(existingServerIdx, 1);\n return done();\n }\n\n // Create a new server instance\n var server = new Server(\n Object.assign({}, self.s.options, {\n host: _server.split(':')[0],\n port: parseInt(_server.split(':')[1], 10),\n reconnect: false,\n monitoring: false,\n parent: self\n })\n );\n\n // Add temp handlers\n server.once('connect', _handleEvent(self, 'connect'));\n server.once('close', _handleEvent(self, 'close'));\n server.once('timeout', _handleEvent(self, 'timeout'));\n server.once('error', _handleEvent(self, 'error'));\n server.once('parseError', _handleEvent(self, 'parseError'));\n\n // SDAM Monitoring events\n server.on('serverOpening', e => self.emit('serverOpening', e));\n server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e));\n server.on('serverClosed', e => self.emit('serverClosed', e));\n\n // Command Monitoring events\n relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']);\n\n self.s.connectingServers.push(server);\n server.connect(self.s.connectOptions);\n }, i);\n }\n\n // Create new instances\n for (var i = 0; i < servers.length; i++) {\n execute(servers[i], i);\n }\n}\n\n// Ping the server\nvar pingServer = function(self, server, cb) {\n // Measure running time\n var start = new Date().getTime();\n\n // Emit the server heartbeat start\n emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name });\n\n // Execute ismaster\n // Set the socketTimeout for a monitoring message to a low number\n // Ensuring ismaster calls are timed out quickly\n server.command(\n 'admin.$cmd',\n {\n ismaster: true\n },\n {\n monitoring: true,\n socketTimeout: self.s.options.connectionTimeout || 2000\n },\n function(err, r) {\n if (self.state === DESTROYED || self.state === UNREFERENCED) {\n server.destroy({ force: true });\n return cb(err, r);\n }\n\n // Calculate latency\n var latencyMS = new Date().getTime() - start;\n\n // Set the last updatedTime\n server.lastUpdateTime = now();\n\n // We had an error, remove it from the state\n if (err) {\n // Emit the server heartbeat failure\n emitSDAMEvent(self, 'serverHeartbeatFailed', {\n durationMS: latencyMS,\n failure: err,\n connectionId: server.name\n });\n\n // Remove server from the state\n self.s.replicaSetState.remove(server);\n } else {\n // Update the server ismaster\n server.ismaster = r.result;\n\n // Check if we have a lastWriteDate convert it to MS\n // and store on the server instance for later use\n if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) {\n server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime();\n }\n\n // Do we have a brand new server\n if (server.lastIsMasterMS === -1) {\n server.lastIsMasterMS = latencyMS;\n } else if (server.lastIsMasterMS) {\n // After the first measurement, average RTT MUST be computed using an\n // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2.\n // If the prior average is denoted old_rtt, then the new average (new_rtt) is\n // computed from a new RTT measurement (x) using the following formula:\n // alpha = 0.2\n // new_rtt = alpha * x + (1 - alpha) * old_rtt\n server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS;\n }\n\n if (self.s.replicaSetState.update(server)) {\n // Primary lastIsMaster store it\n if (server.lastIsMaster() && server.lastIsMaster().ismaster) {\n self.ismaster = server.lastIsMaster();\n }\n }\n\n // Server heart beat event\n emitSDAMEvent(self, 'serverHeartbeatSucceeded', {\n durationMS: latencyMS,\n reply: r.result,\n connectionId: server.name\n });\n }\n\n // Calculate the staleness for this server\n self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval);\n\n // Callback\n cb(err, r);\n }\n );\n};\n\n// Each server is monitored in parallel in their own timeout loop\nvar monitorServer = function(host, self, options) {\n // If this is not the initial scan\n // Is this server already being monitoried, then skip monitoring\n if (!options.haInterval) {\n for (var i = 0; i < self.intervalIds.length; i++) {\n if (self.intervalIds[i].__host === host) {\n return;\n }\n }\n }\n\n // Get the haInterval\n var _process = options.haInterval ? Timeout : Interval;\n var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval;\n\n // Create the interval\n var intervalId = new _process(function() {\n if (self.state === DESTROYED || self.state === UNREFERENCED) {\n // clearInterval(intervalId);\n intervalId.stop();\n return;\n }\n\n // Do we already have server connection available for this host\n var _server = self.s.replicaSetState.get(host);\n\n // Check if we have a known server connection and reuse\n if (_server) {\n // Ping the server\n return pingServer(self, _server, function(err) {\n if (err) {\n // NOTE: should something happen here?\n return;\n }\n\n if (self.state === DESTROYED || self.state === UNREFERENCED) {\n intervalId.stop();\n return;\n }\n\n // Filter out all called intervaliIds\n self.intervalIds = self.intervalIds.filter(function(intervalId) {\n return intervalId.isRunning();\n });\n\n // Initial sweep\n if (_process === Timeout) {\n if (\n self.state === CONNECTING &&\n ((self.s.replicaSetState.hasSecondary() &&\n self.s.options.secondaryOnlyConnectionAllowed) ||\n self.s.replicaSetState.hasPrimary())\n ) {\n self.state = CONNECTED;\n\n // Emit connected sign\n process.nextTick(function() {\n self.emit('connect', self);\n });\n\n // Start topology interval check\n topologyMonitor(self, {});\n }\n } else {\n if (\n self.state === DISCONNECTED &&\n ((self.s.replicaSetState.hasSecondary() &&\n self.s.options.secondaryOnlyConnectionAllowed) ||\n self.s.replicaSetState.hasPrimary())\n ) {\n self.state = CONNECTED;\n\n // Rexecute any stalled operation\n rexecuteOperations(self);\n\n // Emit connected sign\n process.nextTick(function() {\n self.emit('reconnect', self);\n });\n }\n }\n\n if (\n self.initialConnectState.connect &&\n !self.initialConnectState.fullsetup &&\n self.s.replicaSetState.hasPrimaryAndSecondary()\n ) {\n // Set initial connect state\n self.initialConnectState.fullsetup = true;\n self.initialConnectState.all = true;\n\n process.nextTick(function() {\n self.emit('fullsetup', self);\n self.emit('all', self);\n });\n }\n });\n }\n }, _haInterval);\n\n // Start the interval\n intervalId.start();\n // Add the intervalId host name\n intervalId.__host = host;\n // Add the intervalId to our list of intervalIds\n self.intervalIds.push(intervalId);\n};\n\nfunction topologyMonitor(self, options) {\n if (self.state === DESTROYED || self.state === UNREFERENCED) return;\n options = options || {};\n\n // Get the servers\n var servers = Object.keys(self.s.replicaSetState.set);\n\n // Get the haInterval\n var _process = options.haInterval ? Timeout : Interval;\n var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval;\n\n if (_process === Timeout) {\n return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) {\n // Don't emit errors if the connection was already\n if (self.state === DESTROYED || self.state === UNREFERENCED) {\n return;\n }\n\n if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) {\n if (err) {\n return self.emit('error', err);\n }\n\n self.emit(\n 'error',\n new MongoError('no primary found in replicaset or invalid replica set name')\n );\n return self.destroy({ force: true });\n } else if (\n !self.s.replicaSetState.hasSecondary() &&\n self.s.options.secondaryOnlyConnectionAllowed\n ) {\n if (err) {\n return self.emit('error', err);\n }\n\n self.emit(\n 'error',\n new MongoError('no secondary found in replicaset or invalid replica set name')\n );\n return self.destroy({ force: true });\n }\n\n for (var i = 0; i < servers.length; i++) {\n monitorServer(servers[i], self, options);\n }\n });\n } else {\n for (var i = 0; i < servers.length; i++) {\n monitorServer(servers[i], self, options);\n }\n }\n\n // Run the reconnect process\n function executeReconnect(self) {\n return function() {\n if (self.state === DESTROYED || self.state === UNREFERENCED) {\n return;\n }\n\n connectNewServers(self, self.s.replicaSetState.unknownServers, function() {\n var monitoringFrequencey = self.s.replicaSetState.hasPrimary()\n ? _haInterval\n : self.s.minHeartbeatFrequencyMS;\n\n // Create a timeout\n self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start());\n });\n };\n }\n\n // Decide what kind of interval to use\n var intervalTime = !self.s.replicaSetState.hasPrimary()\n ? self.s.minHeartbeatFrequencyMS\n : _haInterval;\n\n self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start());\n}\n\nfunction addServerToList(list, server) {\n for (var i = 0; i < list.length; i++) {\n if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true;\n }\n\n list.push(server);\n}\n\nfunction handleEvent(self, event) {\n return function() {\n if (self.state === DESTROYED || self.state === UNREFERENCED) return;\n // Debug log\n if (self.s.logger.isDebug()) {\n self.s.logger.debug(\n f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id)\n );\n }\n\n // Remove from the replicaset state\n self.s.replicaSetState.remove(this);\n\n // Are we in a destroyed state return\n if (self.state === DESTROYED || self.state === UNREFERENCED) return;\n\n // If no primary and secondary available\n if (\n !self.s.replicaSetState.hasPrimary() &&\n !self.s.replicaSetState.hasSecondary() &&\n self.s.options.secondaryOnlyConnectionAllowed\n ) {\n stateTransition(self, DISCONNECTED);\n } else if (!self.s.replicaSetState.hasPrimary()) {\n stateTransition(self, DISCONNECTED);\n }\n\n addServerToList(self.s.connectingServers, this);\n };\n}\n\nfunction shouldTriggerConnect(self) {\n const isConnecting = self.state === CONNECTING;\n const hasPrimary = self.s.replicaSetState.hasPrimary();\n const hasSecondary = self.s.replicaSetState.hasSecondary();\n const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed;\n const readPreferenceSecondary =\n self.s.connectOptions.readPreference &&\n self.s.connectOptions.readPreference.equals(ReadPreference.secondary);\n\n return (\n (isConnecting &&\n ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) ||\n (hasSecondary && secondaryOnlyConnectionAllowed)\n );\n}\n\nfunction handleInitialConnectEvent(self, event) {\n return function() {\n var _this = this;\n // Debug log\n if (self.s.logger.isDebug()) {\n self.s.logger.debug(\n f(\n 'handleInitialConnectEvent %s from server %s in replset with id %s',\n event,\n this.name,\n self.id\n )\n );\n }\n\n // Destroy the instance\n if (self.state === DESTROYED || self.state === UNREFERENCED) {\n return this.destroy({ force: true });\n }\n\n // Check the type of server\n if (event === 'connect') {\n // Update the state\n var result = self.s.replicaSetState.update(_this);\n if (result === true) {\n // Primary lastIsMaster store it\n if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) {\n self.ismaster = _this.lastIsMaster();\n }\n\n // Debug log\n if (self.s.logger.isDebug()) {\n self.s.logger.debug(\n f(\n 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]',\n event,\n _this.name,\n self.id,\n JSON.stringify(self.s.replicaSetState.set)\n )\n );\n }\n\n // Remove the handlers\n for (let i = 0; i < handlers.length; i++) {\n _this.removeAllListeners(handlers[i]);\n }\n\n // Add stable state handlers\n _this.on('error', handleEvent(self, 'error'));\n _this.on('close', handleEvent(self, 'close'));\n _this.on('timeout', handleEvent(self, 'timeout'));\n _this.on('parseError', handleEvent(self, 'parseError'));\n\n // Do we have a primary or primaryAndSecondary\n if (shouldTriggerConnect(self)) {\n // We are connected\n self.state = CONNECTED;\n\n // Set initial connect state\n self.initialConnectState.connect = true;\n // Emit connect event\n process.nextTick(function() {\n self.emit('connect', self);\n });\n\n topologyMonitor(self, {});\n }\n } else if (result instanceof MongoError) {\n _this.destroy({ force: true });\n self.destroy({ force: true });\n return self.emit('error', result);\n } else {\n _this.destroy({ force: true });\n }\n } else {\n // Emit failure to connect\n self.emit('failed', this);\n\n addServerToList(self.s.connectingServers, this);\n // Remove from the state\n self.s.replicaSetState.remove(this);\n }\n\n if (\n self.initialConnectState.connect &&\n !self.initialConnectState.fullsetup &&\n self.s.replicaSetState.hasPrimaryAndSecondary()\n ) {\n // Set initial connect state\n self.initialConnectState.fullsetup = true;\n self.initialConnectState.all = true;\n\n process.nextTick(function() {\n self.emit('fullsetup', self);\n self.emit('all', self);\n });\n }\n\n // Remove from the list from connectingServers\n for (var i = 0; i < self.s.connectingServers.length; i++) {\n if (self.s.connectingServers[i].equals(this)) {\n self.s.connectingServers.splice(i, 1);\n }\n }\n\n // Trigger topologyMonitor\n if (self.s.connectingServers.length === 0 && self.state === CONNECTING) {\n topologyMonitor(self, { haInterval: 1 });\n }\n };\n}\n\nfunction connectServers(self, servers) {\n // Update connectingServers\n self.s.connectingServers = self.s.connectingServers.concat(servers);\n\n // Index used to interleaf the server connects, avoiding\n // runtime issues on io constrained vm's\n var timeoutInterval = 0;\n\n function connect(server, timeoutInterval) {\n setTimeout(function() {\n // Add the server to the state\n if (self.s.replicaSetState.update(server)) {\n // Primary lastIsMaster store it\n if (server.lastIsMaster() && server.lastIsMaster().ismaster) {\n self.ismaster = server.lastIsMaster();\n }\n }\n\n // Add event handlers\n server.once('close', handleInitialConnectEvent(self, 'close'));\n server.once('timeout', handleInitialConnectEvent(self, 'timeout'));\n server.once('parseError', handleInitialConnectEvent(self, 'parseError'));\n server.once('error', handleInitialConnectEvent(self, 'error'));\n server.once('connect', handleInitialConnectEvent(self, 'connect'));\n\n // SDAM Monitoring events\n server.on('serverOpening', e => self.emit('serverOpening', e));\n server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e));\n server.on('serverClosed', e => self.emit('serverClosed', e));\n\n // Command Monitoring events\n relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']);\n\n // Start connection\n server.connect(self.s.connectOptions);\n }, timeoutInterval);\n }\n\n // Start all the servers\n while (servers.length > 0) {\n connect(servers.shift(), timeoutInterval++);\n }\n}\n\n/**\n * Emit event if it exists\n * @method\n */\nfunction emitSDAMEvent(self, event, description) {\n if (self.listeners(event).length > 0) {\n self.emit(event, description);\n }\n}\n\n/**\n * Initiate server connect\n */\nReplSet.prototype.connect = function(options) {\n var self = this;\n // Add any connect level options to the internal state\n this.s.connectOptions = options || {};\n\n // Set connecting state\n stateTransition(this, CONNECTING);\n\n // Create server instances\n var servers = this.s.seedlist.map(function(x) {\n return new Server(\n Object.assign({}, self.s.options, x, options, {\n reconnect: false,\n monitoring: false,\n parent: self\n })\n );\n });\n\n // Error out as high availbility interval must be < than socketTimeout\n if (\n this.s.options.socketTimeout > 0 &&\n this.s.options.socketTimeout <= this.s.options.haInterval\n ) {\n return self.emit(\n 'error',\n new MongoError(\n f(\n 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS',\n this.s.options.haInterval,\n this.s.options.socketTimeout\n )\n )\n );\n }\n\n // Emit the topology opening event\n emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id });\n // Start all server connections\n connectServers(self, servers);\n};\n\n/**\n * Authenticate the topology.\n * @method\n * @param {MongoCredentials} credentials The credentials for authentication we are using\n * @param {authResultCallback} callback A callback function\n */\nReplSet.prototype.auth = function(credentials, callback) {\n if (typeof callback === 'function') callback(null, null);\n};\n\n/**\n * Destroy the server connection\n * @param {boolean} [options.force=false] Force destroy the pool\n * @method\n */\nReplSet.prototype.destroy = function(options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n options = options || {};\n\n let destroyCount = this.s.connectingServers.length + 1; // +1 for the callback from `replicaSetState.destroy`\n const serverDestroyed = () => {\n destroyCount--;\n if (destroyCount > 0) {\n return;\n }\n\n // Emit toplogy closing event\n emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id });\n\n // Transition state\n stateTransition(this, DESTROYED);\n\n if (typeof callback === 'function') {\n callback(null, null);\n }\n };\n\n // Clear out any monitoring process\n if (this.haTimeoutId) clearTimeout(this.haTimeoutId);\n\n // Clear out all monitoring\n for (var i = 0; i < this.intervalIds.length; i++) {\n this.intervalIds[i].stop();\n }\n\n // Reset list of intervalIds\n this.intervalIds = [];\n\n if (destroyCount === 0) {\n serverDestroyed();\n return;\n }\n\n // Destroy the replicaset\n this.s.replicaSetState.destroy(options, serverDestroyed);\n\n // Destroy all connecting servers\n this.s.connectingServers.forEach(function(x) {\n x.destroy(options, serverDestroyed);\n });\n};\n\n/**\n * Unref all connections belong to this server\n * @method\n */\nReplSet.prototype.unref = function() {\n // Transition state\n stateTransition(this, UNREFERENCED);\n\n this.s.replicaSetState.allServers().forEach(function(x) {\n x.unref();\n });\n\n clearTimeout(this.haTimeoutId);\n};\n\n/**\n * Returns the last known ismaster document for this server\n * @method\n * @return {object}\n */\nReplSet.prototype.lastIsMaster = function() {\n // If secondaryOnlyConnectionAllowed and no primary but secondary\n // return the secondaries ismaster result.\n if (\n this.s.options.secondaryOnlyConnectionAllowed &&\n !this.s.replicaSetState.hasPrimary() &&\n this.s.replicaSetState.hasSecondary()\n ) {\n return this.s.replicaSetState.secondaries[0].lastIsMaster();\n }\n\n return this.s.replicaSetState.primary\n ? this.s.replicaSetState.primary.lastIsMaster()\n : this.ismaster;\n};\n\n/**\n * All raw connections\n * @method\n * @return {Connection[]}\n */\nReplSet.prototype.connections = function() {\n var servers = this.s.replicaSetState.allServers();\n var connections = [];\n for (var i = 0; i < servers.length; i++) {\n connections = connections.concat(servers[i].connections());\n }\n\n return connections;\n};\n\n/**\n * Figure out if the server is connected\n * @method\n * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it\n * @return {boolean}\n */\nReplSet.prototype.isConnected = function(options) {\n options = options || {};\n\n // If we specified a read preference check if we are connected to something\n // than can satisfy this\n if (options.readPreference && options.readPreference.equals(ReadPreference.secondary)) {\n return this.s.replicaSetState.hasSecondary();\n }\n\n if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) {\n return this.s.replicaSetState.hasPrimary();\n }\n\n if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) {\n return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary();\n }\n\n if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) {\n return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary();\n }\n\n if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) {\n return true;\n }\n\n return this.s.replicaSetState.hasPrimary();\n};\n\n/**\n * Figure out if the replicaset instance was destroyed by calling destroy\n * @method\n * @return {boolean}\n */\nReplSet.prototype.isDestroyed = function() {\n return this.state === DESTROYED;\n};\n\nconst SERVER_SELECTION_TIMEOUT_MS = 10000; // hardcoded `serverSelectionTimeoutMS` for legacy topology\nconst SERVER_SELECTION_INTERVAL_MS = 1000; // time to wait between selection attempts\n/**\n * Selects a server\n *\n * @method\n * @param {function} selector Unused\n * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it\n * @param {ClientSession} [options.session] Unused\n * @param {function} callback\n */\nReplSet.prototype.selectServer = function(selector, options, callback) {\n if (typeof selector === 'function' && typeof callback === 'undefined')\n (callback = selector), (selector = undefined), (options = {});\n if (typeof options === 'function') (callback = options), (options = selector);\n options = options || {};\n\n let readPreference;\n if (selector instanceof ReadPreference) {\n readPreference = selector;\n } else {\n readPreference = options.readPreference || ReadPreference.primary;\n }\n\n let lastError;\n const start = now();\n const _selectServer = () => {\n if (calculateDurationInMs(start) >= SERVER_SELECTION_TIMEOUT_MS) {\n if (lastError != null) {\n callback(lastError, null);\n } else {\n callback(new MongoError('Server selection timed out'));\n }\n\n return;\n }\n\n const server = this.s.replicaSetState.pickServer(readPreference);\n if (server == null) {\n setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS);\n return;\n }\n\n if (!(server instanceof Server)) {\n lastError = server;\n setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS);\n return;\n }\n\n if (this.s.debug) this.emit('pickedServer', options.readPreference, server);\n callback(null, server);\n };\n\n _selectServer();\n};\n\n/**\n * Get all connected servers\n * @method\n * @return {Server[]}\n */\nReplSet.prototype.getServers = function() {\n return this.s.replicaSetState.allServers();\n};\n\n//\n// Execute write operation\nfunction executeWriteOperation(args, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n // TODO: once we drop Node 4, use destructuring either here or in arguments.\n const self = args.self;\n const op = args.op;\n const ns = args.ns;\n const ops = args.ops;\n\n if (self.state === DESTROYED) {\n return callback(new MongoError(f('topology was destroyed')));\n }\n\n const willRetryWrite =\n !args.retrying &&\n !!options.retryWrites &&\n options.session &&\n isRetryableWritesSupported(self) &&\n !options.session.inTransaction();\n\n if (!self.s.replicaSetState.hasPrimary()) {\n if (self.s.disconnectHandler) {\n // Not connected but we have a disconnecthandler\n return self.s.disconnectHandler.add(op, ns, ops, options, callback);\n } else if (!willRetryWrite) {\n // No server returned we had an error\n return callback(new MongoError('no primary server found'));\n }\n }\n\n const handler = (err, result) => {\n if (!err) return callback(null, result);\n if (!legacyIsRetryableWriteError(err, self)) {\n err = getMMAPError(err);\n return callback(err);\n }\n\n if (willRetryWrite) {\n const newArgs = Object.assign({}, args, { retrying: true });\n return executeWriteOperation(newArgs, options, callback);\n }\n\n // Per SDAM, remove primary from replicaset\n if (self.s.replicaSetState.primary) {\n self.s.replicaSetState.primary.destroy();\n self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true });\n }\n\n return callback(err);\n };\n\n if (callback.operationId) {\n handler.operationId = callback.operationId;\n }\n\n // increment and assign txnNumber\n if (willRetryWrite) {\n options.session.incrementTransactionNumber();\n options.willRetryWrite = willRetryWrite;\n }\n\n self.s.replicaSetState.primary[op](ns, ops, options, handler);\n}\n\n/**\n * Insert one or more documents\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of documents to insert\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {boolean} [options.retryWrites] Enable retryable writes for this operation\n * @param {opResultCallback} callback A callback function\n */\nReplSet.prototype.insert = function(ns, ops, options, callback) {\n // Execute write operation\n executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback);\n};\n\n/**\n * Perform one or more update operations\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of updates\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {boolean} [options.retryWrites] Enable retryable writes for this operation\n * @param {opResultCallback} callback A callback function\n */\nReplSet.prototype.update = function(ns, ops, options, callback) {\n // Execute write operation\n executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback);\n};\n\n/**\n * Perform one or more remove operations\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of removes\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {boolean} [options.retryWrites] Enable retryable writes for this operation\n * @param {opResultCallback} callback A callback function\n */\nReplSet.prototype.remove = function(ns, ops, options, callback) {\n // Execute write operation\n executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback);\n};\n\nconst RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete'];\n\nfunction isWriteCommand(command) {\n return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]);\n}\n\n/**\n * Execute a command\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object} cmd The command hash\n * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it\n * @param {Connection} [options.connection] Specify connection object to execute command against\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {opResultCallback} callback A callback function\n */\nReplSet.prototype.command = function(ns, cmd, options, callback) {\n if (typeof options === 'function') {\n (callback = options), (options = {}), (options = options || {});\n }\n\n if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed')));\n var self = this;\n\n // Establish readPreference\n var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary;\n\n // If the readPreference is primary and we have no primary, store it\n if (\n readPreference.preference === 'primary' &&\n !this.s.replicaSetState.hasPrimary() &&\n this.s.disconnectHandler != null\n ) {\n return this.s.disconnectHandler.add('command', ns, cmd, options, callback);\n } else if (\n readPreference.preference === 'secondary' &&\n !this.s.replicaSetState.hasSecondary() &&\n this.s.disconnectHandler != null\n ) {\n return this.s.disconnectHandler.add('command', ns, cmd, options, callback);\n } else if (\n readPreference.preference !== 'primary' &&\n !this.s.replicaSetState.hasSecondary() &&\n !this.s.replicaSetState.hasPrimary() &&\n this.s.disconnectHandler != null\n ) {\n return this.s.disconnectHandler.add('command', ns, cmd, options, callback);\n }\n\n // Pick a server\n var server = this.s.replicaSetState.pickServer(readPreference);\n // We received an error, return it\n if (!(server instanceof Server)) return callback(server);\n // Emit debug event\n if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server);\n\n // No server returned we had an error\n if (server == null) {\n return callback(\n new MongoError(\n f('no server found that matches the provided readPreference %s', readPreference)\n )\n );\n }\n\n const willRetryWrite =\n !options.retrying &&\n !!options.retryWrites &&\n options.session &&\n isRetryableWritesSupported(self) &&\n !options.session.inTransaction() &&\n isWriteCommand(cmd);\n\n const cb = (err, result) => {\n if (!err) return callback(null, result);\n if (!legacyIsRetryableWriteError(err, self)) {\n return callback(err);\n }\n\n if (willRetryWrite) {\n const newOptions = Object.assign({}, options, { retrying: true });\n return this.command(ns, cmd, newOptions, callback);\n }\n\n // Per SDAM, remove primary from replicaset\n if (this.s.replicaSetState.primary) {\n this.s.replicaSetState.primary.destroy();\n this.s.replicaSetState.remove(this.s.replicaSetState.primary, { force: true });\n }\n\n return callback(err);\n };\n\n // increment and assign txnNumber\n if (willRetryWrite) {\n options.session.incrementTransactionNumber();\n options.willRetryWrite = willRetryWrite;\n }\n\n // Execute the command\n server.command(ns, cmd, options, cb);\n};\n\n/**\n * Get a new cursor\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId\n * @param {object} [options] Options for the cursor\n * @param {object} [options.batchSize=0] Batchsize for the operation\n * @param {array} [options.documents=[]] Initial documents list for cursor\n * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {object} [options.topology] The internal topology of the created cursor\n * @returns {Cursor}\n */\nReplSet.prototype.cursor = function(ns, cmd, options) {\n options = options || {};\n const topology = options.topology || this;\n\n // Set up final cursor type\n var FinalCursor = options.cursorFactory || this.s.Cursor;\n\n // Return the cursor\n return new FinalCursor(topology, ns, cmd, options);\n};\n\n/**\n * A replset connect event, used to verify that the connection is up and running\n *\n * @event ReplSet#connect\n * @type {ReplSet}\n */\n\n/**\n * A replset reconnect event, used to verify that the topology reconnected\n *\n * @event ReplSet#reconnect\n * @type {ReplSet}\n */\n\n/**\n * A replset fullsetup event, used to signal that all topology members have been contacted.\n *\n * @event ReplSet#fullsetup\n * @type {ReplSet}\n */\n\n/**\n * A replset all event, used to signal that all topology members have been contacted.\n *\n * @event ReplSet#all\n * @type {ReplSet}\n */\n\n/**\n * A replset failed event, used to signal that initial replset connection failed.\n *\n * @event ReplSet#failed\n * @type {ReplSet}\n */\n\n/**\n * A server member left the replicaset\n *\n * @event ReplSet#left\n * @type {function}\n * @param {string} type The type of member that left (primary|secondary|arbiter)\n * @param {Server} server The server object that left\n */\n\n/**\n * A server member joined the replicaset\n *\n * @event ReplSet#joined\n * @type {function}\n * @param {string} type The type of member that joined (primary|secondary|arbiter)\n * @param {Server} server The server object that joined\n */\n\n/**\n * A server opening SDAM monitoring event\n *\n * @event ReplSet#serverOpening\n * @type {object}\n */\n\n/**\n * A server closed SDAM monitoring event\n *\n * @event ReplSet#serverClosed\n * @type {object}\n */\n\n/**\n * A server description SDAM change monitoring event\n *\n * @event ReplSet#serverDescriptionChanged\n * @type {object}\n */\n\n/**\n * A topology open SDAM event\n *\n * @event ReplSet#topologyOpening\n * @type {object}\n */\n\n/**\n * A topology closed SDAM event\n *\n * @event ReplSet#topologyClosed\n * @type {object}\n */\n\n/**\n * A topology structure SDAM change event\n *\n * @event ReplSet#topologyDescriptionChanged\n * @type {object}\n */\n\n/**\n * A topology serverHeartbeatStarted SDAM event\n *\n * @event ReplSet#serverHeartbeatStarted\n * @type {object}\n */\n\n/**\n * A topology serverHeartbeatFailed SDAM event\n *\n * @event ReplSet#serverHeartbeatFailed\n * @type {object}\n */\n\n/**\n * A topology serverHeartbeatSucceeded SDAM change event\n *\n * @event ReplSet#serverHeartbeatSucceeded\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command was started, if command monitoring is enabled\n *\n * @event ReplSet#commandStarted\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command succeeded, if command monitoring is enabled\n *\n * @event ReplSet#commandSucceeded\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command failed, if command monitoring is enabled\n *\n * @event ReplSet#commandFailed\n * @type {object}\n */\n\nmodule.exports = ReplSet;\n","'use strict';\n\nvar inherits = require('util').inherits,\n f = require('util').format,\n diff = require('./shared').diff,\n EventEmitter = require('events').EventEmitter,\n Logger = require('../connection/logger'),\n ReadPreference = require('./read_preference'),\n MongoError = require('../error').MongoError,\n Buffer = require('safe-buffer').Buffer;\n\nvar TopologyType = {\n Single: 'Single',\n ReplicaSetNoPrimary: 'ReplicaSetNoPrimary',\n ReplicaSetWithPrimary: 'ReplicaSetWithPrimary',\n Sharded: 'Sharded',\n Unknown: 'Unknown'\n};\n\nvar ServerType = {\n Standalone: 'Standalone',\n Mongos: 'Mongos',\n PossiblePrimary: 'PossiblePrimary',\n RSPrimary: 'RSPrimary',\n RSSecondary: 'RSSecondary',\n RSArbiter: 'RSArbiter',\n RSOther: 'RSOther',\n RSGhost: 'RSGhost',\n Unknown: 'Unknown'\n};\n\nvar ReplSetState = function(options) {\n options = options || {};\n // Add event listener\n EventEmitter.call(this);\n // Topology state\n this.topologyType = TopologyType.ReplicaSetNoPrimary;\n this.setName = options.setName;\n\n // Server set\n this.set = {};\n\n // Unpacked options\n this.id = options.id;\n this.setName = options.setName;\n\n // Replicaset logger\n this.logger = options.logger || Logger('ReplSet', options);\n\n // Server selection index\n this.index = 0;\n // Acceptable latency\n this.acceptableLatency = options.acceptableLatency || 15;\n\n // heartbeatFrequencyMS\n this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000;\n\n // Server side\n this.primary = null;\n this.secondaries = [];\n this.arbiters = [];\n this.passives = [];\n this.ghosts = [];\n // Current unknown hosts\n this.unknownServers = [];\n // In set status\n this.set = {};\n // Status\n this.maxElectionId = null;\n this.maxSetVersion = 0;\n // Description of the Replicaset\n this.replicasetDescription = {\n topologyType: 'Unknown',\n servers: []\n };\n\n this.logicalSessionTimeoutMinutes = undefined;\n};\n\ninherits(ReplSetState, EventEmitter);\n\nReplSetState.prototype.hasPrimaryAndSecondary = function() {\n return this.primary != null && this.secondaries.length > 0;\n};\n\nReplSetState.prototype.hasPrimaryOrSecondary = function() {\n return this.hasPrimary() || this.hasSecondary();\n};\n\nReplSetState.prototype.hasPrimary = function() {\n return this.primary != null;\n};\n\nReplSetState.prototype.hasSecondary = function() {\n return this.secondaries.length > 0;\n};\n\nReplSetState.prototype.get = function(host) {\n var servers = this.allServers();\n\n for (var i = 0; i < servers.length; i++) {\n if (servers[i].name.toLowerCase() === host.toLowerCase()) {\n return servers[i];\n }\n }\n\n return null;\n};\n\nReplSetState.prototype.allServers = function(options) {\n options = options || {};\n var servers = this.primary ? [this.primary] : [];\n servers = servers.concat(this.secondaries);\n if (!options.ignoreArbiters) servers = servers.concat(this.arbiters);\n servers = servers.concat(this.passives);\n return servers;\n};\n\nReplSetState.prototype.destroy = function(options, callback) {\n const serversToDestroy = this.secondaries\n .concat(this.arbiters)\n .concat(this.passives)\n .concat(this.ghosts);\n if (this.primary) serversToDestroy.push(this.primary);\n\n let serverCount = serversToDestroy.length;\n const serverDestroyed = () => {\n serverCount--;\n if (serverCount > 0) {\n return;\n }\n\n // Clear out the complete state\n this.secondaries = [];\n this.arbiters = [];\n this.passives = [];\n this.ghosts = [];\n this.unknownServers = [];\n this.set = {};\n this.primary = null;\n\n // Emit the topology changed\n emitTopologyDescriptionChanged(this);\n\n if (typeof callback === 'function') {\n callback(null, null);\n }\n };\n\n if (serverCount === 0) {\n serverDestroyed();\n return;\n }\n\n serversToDestroy.forEach(server => server.destroy(options, serverDestroyed));\n};\n\nReplSetState.prototype.remove = function(server, options) {\n options = options || {};\n\n // Get the server name and lowerCase it\n var serverName = server.name.toLowerCase();\n\n // Only remove if the current server is not connected\n var servers = this.primary ? [this.primary] : [];\n servers = servers.concat(this.secondaries);\n servers = servers.concat(this.arbiters);\n servers = servers.concat(this.passives);\n\n // Check if it's active and this is just a failed connection attempt\n for (var i = 0; i < servers.length; i++) {\n if (\n !options.force &&\n servers[i].equals(server) &&\n servers[i].isConnected &&\n servers[i].isConnected()\n ) {\n return;\n }\n }\n\n // If we have it in the set remove it\n if (this.set[serverName]) {\n this.set[serverName].type = ServerType.Unknown;\n this.set[serverName].electionId = null;\n this.set[serverName].setName = null;\n this.set[serverName].setVersion = null;\n }\n\n // Remove type\n var removeType = null;\n\n // Remove from any lists\n if (this.primary && this.primary.equals(server)) {\n this.primary = null;\n this.topologyType = TopologyType.ReplicaSetNoPrimary;\n removeType = 'primary';\n }\n\n // Remove from any other server lists\n removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType;\n removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType;\n removeType = removeFrom(server, this.passives) ? 'secondary' : removeType;\n removeFrom(server, this.ghosts);\n removeFrom(server, this.unknownServers);\n\n // Push to unknownServers\n this.unknownServers.push(serverName);\n\n // Do we have a removeType\n if (removeType) {\n this.emit('left', removeType, server);\n }\n};\n\nconst isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName;\n\nReplSetState.prototype.update = function(server) {\n var self = this;\n // Get the current ismaster\n var ismaster = server.lastIsMaster();\n\n // Get the server name and lowerCase it\n var serverName = server.name.toLowerCase();\n\n //\n // Add any hosts\n //\n if (ismaster) {\n // Join all the possible new hosts\n var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : [];\n hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []);\n hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []);\n hosts = hosts.map(function(s) {\n return s.toLowerCase();\n });\n\n // Add all hosts as unknownServers\n for (var i = 0; i < hosts.length; i++) {\n // Add to the list of unknown server\n if (\n this.unknownServers.indexOf(hosts[i]) === -1 &&\n (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown)\n ) {\n this.unknownServers.push(hosts[i].toLowerCase());\n }\n\n if (!this.set[hosts[i]]) {\n this.set[hosts[i]] = {\n type: ServerType.Unknown,\n electionId: null,\n setName: null,\n setVersion: null\n };\n }\n }\n }\n\n //\n // Unknown server\n //\n if (!ismaster && !inList(ismaster, server, this.unknownServers)) {\n self.set[serverName] = {\n type: ServerType.Unknown,\n setVersion: null,\n electionId: null,\n setName: null\n };\n // Update set information about the server instance\n self.set[serverName].type = ServerType.Unknown;\n self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster;\n self.set[serverName].setName = ismaster ? ismaster.setName : ismaster;\n self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster;\n\n if (self.unknownServers.indexOf(server.name) === -1) {\n self.unknownServers.push(serverName);\n }\n\n // Set the topology\n return false;\n }\n\n // Update logicalSessionTimeoutMinutes\n if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) {\n if (\n self.logicalSessionTimeoutMinutes === undefined ||\n ismaster.logicalSessionTimeoutMinutes === null\n ) {\n self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes;\n } else {\n self.logicalSessionTimeoutMinutes = Math.min(\n self.logicalSessionTimeoutMinutes,\n ismaster.logicalSessionTimeoutMinutes\n );\n }\n }\n\n //\n // Is this a mongos\n //\n if (ismaster && ismaster.msg === 'isdbgrid') {\n if (this.primary && this.primary.name === serverName) {\n this.primary = null;\n this.topologyType = TopologyType.ReplicaSetNoPrimary;\n }\n\n return false;\n }\n\n // A RSGhost instance\n if (ismaster.isreplicaset) {\n self.set[serverName] = {\n type: ServerType.RSGhost,\n setVersion: null,\n electionId: null,\n setName: ismaster.setName\n };\n\n if (this.primary && this.primary.name === serverName) {\n this.primary = null;\n }\n\n // Set the topology\n this.topologyType = this.primary\n ? TopologyType.ReplicaSetWithPrimary\n : TopologyType.ReplicaSetNoPrimary;\n if (ismaster.setName) this.setName = ismaster.setName;\n\n // Set the topology\n return false;\n }\n\n // A RSOther instance\n if (\n (ismaster.setName && ismaster.hidden) ||\n (ismaster.setName &&\n !ismaster.ismaster &&\n !ismaster.secondary &&\n !ismaster.arbiterOnly &&\n !ismaster.passive)\n ) {\n self.set[serverName] = {\n type: ServerType.RSOther,\n setVersion: null,\n electionId: null,\n setName: ismaster.setName\n };\n\n // Set the topology\n this.topologyType = this.primary\n ? TopologyType.ReplicaSetWithPrimary\n : TopologyType.ReplicaSetNoPrimary;\n if (ismaster.setName) this.setName = ismaster.setName;\n return false;\n }\n\n //\n // Standalone server, destroy and return\n //\n if (ismaster && ismaster.ismaster && !ismaster.setName) {\n this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown;\n this.remove(server, { force: true });\n return false;\n }\n\n //\n // Server in maintanance mode\n //\n if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) {\n this.remove(server, { force: true });\n return false;\n }\n\n //\n // If the .me field does not match the passed in server\n //\n if (ismaster.me && ismaster.me.toLowerCase() !== serverName) {\n if (this.logger.isWarn()) {\n this.logger.warn(\n f(\n 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s',\n server.name,\n ismaster.me\n )\n );\n }\n\n // Delete from the set\n delete this.set[serverName];\n // Delete unknown servers\n removeFrom(server, self.unknownServers);\n\n // Destroy the instance\n server.destroy({ force: true });\n\n // Set the type of topology we have\n if (this.primary && !this.primary.equals(server)) {\n this.topologyType = TopologyType.ReplicaSetWithPrimary;\n } else {\n this.topologyType = TopologyType.ReplicaSetNoPrimary;\n }\n\n //\n // We have a potential primary\n //\n if (!this.primary && ismaster.primary) {\n this.set[ismaster.primary.toLowerCase()] = {\n type: ServerType.PossiblePrimary,\n setName: null,\n electionId: null,\n setVersion: null\n };\n }\n\n return false;\n }\n\n //\n // Primary handling\n //\n if (!this.primary && ismaster.ismaster && ismaster.setName) {\n var ismasterElectionId = server.lastIsMaster().electionId;\n if (this.setName && this.setName !== ismaster.setName) {\n this.topologyType = TopologyType.ReplicaSetNoPrimary;\n return new MongoError(\n f(\n 'setName from ismaster does not match provided connection setName [%s] != [%s]',\n ismaster.setName,\n this.setName\n )\n );\n }\n\n if (!this.maxElectionId && ismasterElectionId) {\n this.maxElectionId = ismasterElectionId;\n } else if (this.maxElectionId && ismasterElectionId) {\n var result = compareObjectIds(this.maxElectionId, ismasterElectionId);\n // Get the electionIds\n var ismasterSetVersion = server.lastIsMaster().setVersion;\n\n if (result === 1) {\n this.topologyType = TopologyType.ReplicaSetNoPrimary;\n return false;\n } else if (result === 0 && ismasterSetVersion) {\n if (ismasterSetVersion < this.maxSetVersion) {\n this.topologyType = TopologyType.ReplicaSetNoPrimary;\n return false;\n }\n }\n\n this.maxSetVersion = ismasterSetVersion;\n this.maxElectionId = ismasterElectionId;\n }\n\n // Hande normalization of server names\n var normalizedHosts = ismaster.hosts.map(function(x) {\n return x.toLowerCase();\n });\n var locationIndex = normalizedHosts.indexOf(serverName);\n\n // Validate that the server exists in the host list\n if (locationIndex !== -1) {\n self.primary = server;\n self.set[serverName] = {\n type: ServerType.RSPrimary,\n setVersion: ismaster.setVersion,\n electionId: ismaster.electionId,\n setName: ismaster.setName\n };\n\n // Set the topology\n this.topologyType = TopologyType.ReplicaSetWithPrimary;\n if (ismaster.setName) this.setName = ismaster.setName;\n removeFrom(server, self.unknownServers);\n removeFrom(server, self.secondaries);\n removeFrom(server, self.passives);\n self.emit('joined', 'primary', server);\n } else {\n this.topologyType = TopologyType.ReplicaSetNoPrimary;\n }\n\n emitTopologyDescriptionChanged(self);\n return true;\n } else if (ismaster.ismaster && ismaster.setName) {\n // Get the electionIds\n var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId;\n var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion;\n var currentSetName = self.set[self.primary.name.toLowerCase()].setName;\n ismasterElectionId = server.lastIsMaster().electionId;\n ismasterSetVersion = server.lastIsMaster().setVersion;\n var ismasterSetName = server.lastIsMaster().setName;\n\n // Is it the same server instance\n if (this.primary.equals(server) && currentSetName === ismasterSetName) {\n return false;\n }\n\n // If we do not have the same rs name\n if (currentSetName && currentSetName !== ismasterSetName) {\n if (!this.primary.equals(server)) {\n this.topologyType = TopologyType.ReplicaSetWithPrimary;\n } else {\n this.topologyType = TopologyType.ReplicaSetNoPrimary;\n }\n\n return false;\n }\n\n // Check if we need to replace the server\n if (currentElectionId && ismasterElectionId) {\n result = compareObjectIds(currentElectionId, ismasterElectionId);\n\n if (result === 1) {\n return false;\n } else if (result === 0 && currentSetVersion > ismasterSetVersion) {\n return false;\n }\n } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) {\n if (ismasterSetVersion < this.maxSetVersion) {\n return false;\n }\n }\n\n if (!this.maxElectionId && ismasterElectionId) {\n this.maxElectionId = ismasterElectionId;\n } else if (this.maxElectionId && ismasterElectionId) {\n result = compareObjectIds(this.maxElectionId, ismasterElectionId);\n\n if (result === 1) {\n return false;\n } else if (result === 0 && currentSetVersion && ismasterSetVersion) {\n if (ismasterSetVersion < this.maxSetVersion) {\n return false;\n }\n } else {\n if (ismasterSetVersion < this.maxSetVersion) {\n return false;\n }\n }\n\n this.maxElectionId = ismasterElectionId;\n this.maxSetVersion = ismasterSetVersion;\n } else {\n this.maxSetVersion = ismasterSetVersion;\n }\n\n // Modify the entry to unknown\n self.set[self.primary.name.toLowerCase()] = {\n type: ServerType.Unknown,\n setVersion: null,\n electionId: null,\n setName: null\n };\n\n // Signal primary left\n self.emit('left', 'primary', this.primary);\n // Destroy the instance\n self.primary.destroy({ force: true });\n // Set the new instance\n self.primary = server;\n // Set the set information\n self.set[serverName] = {\n type: ServerType.RSPrimary,\n setVersion: ismaster.setVersion,\n electionId: ismaster.electionId,\n setName: ismaster.setName\n };\n\n // Set the topology\n this.topologyType = TopologyType.ReplicaSetWithPrimary;\n if (ismaster.setName) this.setName = ismaster.setName;\n removeFrom(server, self.unknownServers);\n removeFrom(server, self.secondaries);\n removeFrom(server, self.passives);\n self.emit('joined', 'primary', server);\n emitTopologyDescriptionChanged(self);\n return true;\n }\n\n // A possible instance\n if (!this.primary && ismaster.primary) {\n self.set[ismaster.primary.toLowerCase()] = {\n type: ServerType.PossiblePrimary,\n setVersion: null,\n electionId: null,\n setName: null\n };\n }\n\n //\n // Secondary handling\n //\n if (\n ismaster.secondary &&\n ismaster.setName &&\n !inList(ismaster, server, this.secondaries) &&\n this.setName &&\n this.setName === ismaster.setName\n ) {\n addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries);\n // Set the topology\n this.topologyType = this.primary\n ? TopologyType.ReplicaSetWithPrimary\n : TopologyType.ReplicaSetNoPrimary;\n if (ismaster.setName) this.setName = ismaster.setName;\n removeFrom(server, self.unknownServers);\n\n // Remove primary\n if (this.primary && this.primary.name.toLowerCase() === serverName) {\n server.destroy({ force: true });\n this.primary = null;\n self.emit('left', 'primary', server);\n }\n\n // Emit secondary joined replicaset\n self.emit('joined', 'secondary', server);\n emitTopologyDescriptionChanged(self);\n return true;\n }\n\n //\n // Arbiter handling\n //\n if (\n isArbiter(ismaster) &&\n !inList(ismaster, server, this.arbiters) &&\n this.setName &&\n this.setName === ismaster.setName\n ) {\n addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters);\n // Set the topology\n this.topologyType = this.primary\n ? TopologyType.ReplicaSetWithPrimary\n : TopologyType.ReplicaSetNoPrimary;\n if (ismaster.setName) this.setName = ismaster.setName;\n removeFrom(server, self.unknownServers);\n self.emit('joined', 'arbiter', server);\n emitTopologyDescriptionChanged(self);\n return true;\n }\n\n //\n // Passive handling\n //\n if (\n ismaster.passive &&\n ismaster.setName &&\n !inList(ismaster, server, this.passives) &&\n this.setName &&\n this.setName === ismaster.setName\n ) {\n addToList(self, ServerType.RSSecondary, ismaster, server, this.passives);\n // Set the topology\n this.topologyType = this.primary\n ? TopologyType.ReplicaSetWithPrimary\n : TopologyType.ReplicaSetNoPrimary;\n if (ismaster.setName) this.setName = ismaster.setName;\n removeFrom(server, self.unknownServers);\n\n // Remove primary\n if (this.primary && this.primary.name.toLowerCase() === serverName) {\n server.destroy({ force: true });\n this.primary = null;\n self.emit('left', 'primary', server);\n }\n\n self.emit('joined', 'secondary', server);\n emitTopologyDescriptionChanged(self);\n return true;\n }\n\n //\n // Remove the primary\n //\n if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) {\n self.emit('left', 'primary', this.primary);\n this.primary.destroy({ force: true });\n this.primary = null;\n this.topologyType = TopologyType.ReplicaSetNoPrimary;\n return false;\n }\n\n this.topologyType = this.primary\n ? TopologyType.ReplicaSetWithPrimary\n : TopologyType.ReplicaSetNoPrimary;\n return false;\n};\n\n/**\n * Recalculate single server max staleness\n * @method\n */\nReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) {\n // Locate the max secondary lastwrite\n var max = 0;\n // Go over all secondaries\n for (var i = 0; i < this.secondaries.length; i++) {\n max = Math.max(max, this.secondaries[i].lastWriteDate);\n }\n\n // Perform this servers staleness calculation\n if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) {\n server.staleness =\n server.lastUpdateTime -\n server.lastWriteDate -\n (this.primary.lastUpdateTime - this.primary.lastWriteDate) +\n haInterval;\n } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) {\n server.staleness = max - server.lastWriteDate + haInterval;\n }\n};\n\n/**\n * Recalculate all the staleness values for secodaries\n * @method\n */\nReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) {\n for (var i = 0; i < this.secondaries.length; i++) {\n this.updateServerMaxStaleness(this.secondaries[i], haInterval);\n }\n};\n\n/**\n * Pick a server by the passed in ReadPreference\n * @method\n * @param {ReadPreference} readPreference The ReadPreference instance to use\n */\nReplSetState.prototype.pickServer = function(readPreference) {\n // If no read Preference set to primary by default\n readPreference = readPreference || ReadPreference.primary;\n\n // maxStalenessSeconds is not allowed with a primary read\n if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) {\n return new MongoError('primary readPreference incompatible with maxStalenessSeconds');\n }\n\n // Check if we have any non compatible servers for maxStalenessSeconds\n var allservers = this.primary ? [this.primary] : [];\n allservers = allservers.concat(this.secondaries);\n\n // Does any of the servers not support the right wire protocol version\n // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out\n if (readPreference.maxStalenessSeconds != null) {\n for (var i = 0; i < allservers.length; i++) {\n if (allservers[i].ismaster.maxWireVersion < 5) {\n return new MongoError(\n 'maxStalenessSeconds not supported by at least one of the replicaset members'\n );\n }\n }\n }\n\n // Do we have the nearest readPreference\n if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) {\n return pickNearest(this, readPreference);\n } else if (\n readPreference.preference === 'nearest' &&\n readPreference.maxStalenessSeconds != null\n ) {\n return pickNearestMaxStalenessSeconds(this, readPreference);\n }\n\n // Get all the secondaries\n var secondaries = this.secondaries;\n\n // Check if we can satisfy and of the basic read Preferences\n if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) {\n return new MongoError('no secondary server available');\n }\n\n if (\n readPreference.equals(ReadPreference.secondaryPreferred) &&\n secondaries.length === 0 &&\n this.primary == null\n ) {\n return new MongoError('no secondary or primary server available');\n }\n\n if (readPreference.equals(ReadPreference.primary) && this.primary == null) {\n return new MongoError('no primary server available');\n }\n\n // Secondary preferred or just secondaries\n if (\n readPreference.equals(ReadPreference.secondaryPreferred) ||\n readPreference.equals(ReadPreference.secondary)\n ) {\n if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) {\n // Pick nearest of any other servers available\n var server = pickNearest(this, readPreference);\n // No server in the window return primary\n if (server) {\n return server;\n }\n } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) {\n // Pick nearest of any other servers available\n server = pickNearestMaxStalenessSeconds(this, readPreference);\n // No server in the window return primary\n if (server) {\n return server;\n }\n }\n\n if (readPreference.equals(ReadPreference.secondaryPreferred)) {\n return this.primary;\n }\n\n return null;\n }\n\n // Primary preferred\n if (readPreference.equals(ReadPreference.primaryPreferred)) {\n server = null;\n\n // We prefer the primary if it's available\n if (this.primary) {\n return this.primary;\n }\n\n // Pick a secondary\n if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) {\n server = pickNearest(this, readPreference);\n } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) {\n server = pickNearestMaxStalenessSeconds(this, readPreference);\n }\n\n // Did we find a server\n if (server) return server;\n }\n\n // Return the primary\n return this.primary;\n};\n\n//\n// Filter serves by tags\nvar filterByTags = function(readPreference, servers) {\n if (readPreference.tags == null) return servers;\n var filteredServers = [];\n var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags];\n\n // Iterate over the tags\n for (var j = 0; j < tagsArray.length; j++) {\n var tags = tagsArray[j];\n\n // Iterate over all the servers\n for (var i = 0; i < servers.length; i++) {\n var serverTag = servers[i].lastIsMaster().tags || {};\n\n // Did we find the a matching server\n var found = true;\n // Check if the server is valid\n for (var name in tags) {\n if (serverTag[name] !== tags[name]) {\n found = false;\n }\n }\n\n // Add to candidate list\n if (found) {\n filteredServers.push(servers[i]);\n }\n }\n }\n\n // Returned filtered servers\n return filteredServers;\n};\n\nfunction pickNearestMaxStalenessSeconds(self, readPreference) {\n // Only get primary and secondaries as seeds\n var servers = [];\n\n // Get the maxStalenessMS\n var maxStalenessMS = readPreference.maxStalenessSeconds * 1000;\n\n // Check if the maxStalenessMS > 90 seconds\n if (maxStalenessMS < 90 * 1000) {\n return new MongoError('maxStalenessSeconds must be set to at least 90 seconds');\n }\n\n // Add primary to list if not a secondary read preference\n if (\n self.primary &&\n readPreference.preference !== 'secondary' &&\n readPreference.preference !== 'secondaryPreferred'\n ) {\n servers.push(self.primary);\n }\n\n // Add all the secondaries\n for (var i = 0; i < self.secondaries.length; i++) {\n servers.push(self.secondaries[i]);\n }\n\n // If we have a secondaryPreferred readPreference and no server add the primary\n if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') {\n servers.push(self.primary);\n }\n\n // Filter by tags\n servers = filterByTags(readPreference, servers);\n\n // Filter by latency\n servers = servers.filter(function(s) {\n return s.staleness <= maxStalenessMS;\n });\n\n // Sort by time\n servers.sort(function(a, b) {\n return a.lastIsMasterMS - b.lastIsMasterMS;\n });\n\n // No servers, default to primary\n if (servers.length === 0) {\n return null;\n }\n\n // Ensure index does not overflow the number of available servers\n self.index = self.index % servers.length;\n\n // Get the server\n var server = servers[self.index];\n // Add to the index\n self.index = self.index + 1;\n // Return the first server of the sorted and filtered list\n return server;\n}\n\nfunction pickNearest(self, readPreference) {\n // Only get primary and secondaries as seeds\n var servers = [];\n\n // Add primary to list if not a secondary read preference\n if (\n self.primary &&\n readPreference.preference !== 'secondary' &&\n readPreference.preference !== 'secondaryPreferred'\n ) {\n servers.push(self.primary);\n }\n\n // Add all the secondaries\n for (var i = 0; i < self.secondaries.length; i++) {\n servers.push(self.secondaries[i]);\n }\n\n // If we have a secondaryPreferred readPreference and no server add the primary\n if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') {\n servers.push(self.primary);\n }\n\n // Filter by tags\n servers = filterByTags(readPreference, servers);\n\n // Sort by time\n servers.sort(function(a, b) {\n return a.lastIsMasterMS - b.lastIsMasterMS;\n });\n\n // Locate lowest time (picked servers are lowest time + acceptable Latency margin)\n var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0;\n\n // Filter by latency\n servers = servers.filter(function(s) {\n return s.lastIsMasterMS <= lowest + self.acceptableLatency;\n });\n\n // No servers, default to primary\n if (servers.length === 0) {\n return null;\n }\n\n // Ensure index does not overflow the number of available servers\n self.index = self.index % servers.length;\n // Get the server\n var server = servers[self.index];\n // Add to the index\n self.index = self.index + 1;\n // Return the first server of the sorted and filtered list\n return server;\n}\n\nfunction inList(ismaster, server, list) {\n for (var i = 0; i < list.length; i++) {\n if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase())\n return true;\n }\n\n return false;\n}\n\nfunction addToList(self, type, ismaster, server, list) {\n var serverName = server.name.toLowerCase();\n // Update set information about the server instance\n self.set[serverName].type = type;\n self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster;\n self.set[serverName].setName = ismaster ? ismaster.setName : ismaster;\n self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster;\n // Add to the list\n list.push(server);\n}\n\nfunction compareObjectIds(id1, id2) {\n var a = Buffer.from(id1.toHexString(), 'hex');\n var b = Buffer.from(id2.toHexString(), 'hex');\n\n if (a === b) {\n return 0;\n }\n\n if (typeof Buffer.compare === 'function') {\n return Buffer.compare(a, b);\n }\n\n var x = a.length;\n var y = b.length;\n var len = Math.min(x, y);\n\n for (var i = 0; i < len; i++) {\n if (a[i] !== b[i]) {\n break;\n }\n }\n\n if (i !== len) {\n x = a[i];\n y = b[i];\n }\n\n return x < y ? -1 : y < x ? 1 : 0;\n}\n\nfunction removeFrom(server, list) {\n for (var i = 0; i < list.length; i++) {\n if (list[i].equals && list[i].equals(server)) {\n list.splice(i, 1);\n return true;\n } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) {\n list.splice(i, 1);\n return true;\n }\n }\n\n return false;\n}\n\nfunction emitTopologyDescriptionChanged(self) {\n if (self.listeners('topologyDescriptionChanged').length > 0) {\n var topology = 'Unknown';\n var setName = self.setName;\n\n if (self.hasPrimaryAndSecondary()) {\n topology = 'ReplicaSetWithPrimary';\n } else if (!self.hasPrimary() && self.hasSecondary()) {\n topology = 'ReplicaSetNoPrimary';\n }\n\n // Generate description\n var description = {\n topologyType: topology,\n setName: setName,\n servers: []\n };\n\n // Add the primary to the list\n if (self.hasPrimary()) {\n var desc = self.primary.getDescription();\n desc.type = 'RSPrimary';\n description.servers.push(desc);\n }\n\n // Add all the secondaries\n description.servers = description.servers.concat(\n self.secondaries.map(function(x) {\n var description = x.getDescription();\n description.type = 'RSSecondary';\n return description;\n })\n );\n\n // Add all the arbiters\n description.servers = description.servers.concat(\n self.arbiters.map(function(x) {\n var description = x.getDescription();\n description.type = 'RSArbiter';\n return description;\n })\n );\n\n // Add all the passives\n description.servers = description.servers.concat(\n self.passives.map(function(x) {\n var description = x.getDescription();\n description.type = 'RSSecondary';\n return description;\n })\n );\n\n // Get the diff\n var diffResult = diff(self.replicasetDescription, description);\n\n // Create the result\n var result = {\n topologyId: self.id,\n previousDescription: self.replicasetDescription,\n newDescription: description,\n diff: diffResult\n };\n\n // Emit the topologyDescription change\n // if(diffResult.servers.length > 0) {\n self.emit('topologyDescriptionChanged', result);\n // }\n\n // Set the new description\n self.replicasetDescription = description;\n }\n}\n\nmodule.exports = ReplSetState;\n","'use strict';\n\nvar inherits = require('util').inherits,\n f = require('util').format,\n EventEmitter = require('events').EventEmitter,\n ReadPreference = require('./read_preference'),\n Logger = require('../connection/logger'),\n debugOptions = require('../connection/utils').debugOptions,\n retrieveBSON = require('../connection/utils').retrieveBSON,\n Pool = require('../connection/pool'),\n MongoError = require('../error').MongoError,\n MongoNetworkError = require('../error').MongoNetworkError,\n wireProtocol = require('../wireprotocol'),\n CoreCursor = require('../cursor').CoreCursor,\n sdam = require('./shared'),\n createCompressionInfo = require('./shared').createCompressionInfo,\n resolveClusterTime = require('./shared').resolveClusterTime,\n SessionMixins = require('./shared').SessionMixins,\n relayEvents = require('../utils').relayEvents;\n\nconst collationNotSupported = require('../utils').collationNotSupported;\nconst makeClientMetadata = require('../utils').makeClientMetadata;\n\n// Used for filtering out fields for loggin\nvar debugFields = [\n 'reconnect',\n 'reconnectTries',\n 'reconnectInterval',\n 'emitError',\n 'cursorFactory',\n 'host',\n 'port',\n 'size',\n 'keepAlive',\n 'keepAliveInitialDelay',\n 'noDelay',\n 'connectionTimeout',\n 'checkServerIdentity',\n 'socketTimeout',\n 'ssl',\n 'ca',\n 'crl',\n 'cert',\n 'key',\n 'rejectUnauthorized',\n 'promoteLongs',\n 'promoteValues',\n 'promoteBuffers',\n 'servername'\n];\n\n// Server instance id\nvar id = 0;\nvar serverAccounting = false;\nvar servers = {};\nvar BSON = retrieveBSON();\n\nfunction topologyId(server) {\n return server.s.parent == null ? server.id : server.s.parent.id;\n}\n\n/**\n * Creates a new Server instance\n * @class\n * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection\n * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times\n * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries\n * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval)\n * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled.\n * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors\n * @param {string} options.host The server host\n * @param {number} options.port The server port\n * @param {number} [options.size=5] Server connection pool size\n * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled\n * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled\n * @param {boolean} [options.noDelay=true] TCP Connection no delay\n * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting\n * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting\n * @param {boolean} [options.ssl=false] Use SSL for connection\n * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.\n * @param {Buffer} [options.ca] SSL Certificate store binary buffer\n * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer\n * @param {Buffer} [options.cert] SSL Certificate binary buffer\n * @param {Buffer} [options.key] SSL Key file binary buffer\n * @param {string} [options.passphrase] SSL Certificate pass phrase\n * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates\n * @param {string} [options.servername=null] String containing the server name requested via TLS SNI.\n * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits\n * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.\n * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.\n * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes.\n * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.\n * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology\n * @return {Server} A cursor instance\n * @fires Server#connect\n * @fires Server#close\n * @fires Server#error\n * @fires Server#timeout\n * @fires Server#parseError\n * @fires Server#reconnect\n * @fires Server#reconnectFailed\n * @fires Server#serverHeartbeatStarted\n * @fires Server#serverHeartbeatSucceeded\n * @fires Server#serverHeartbeatFailed\n * @fires Server#topologyOpening\n * @fires Server#topologyClosed\n * @fires Server#topologyDescriptionChanged\n * @property {string} type the topology type.\n * @property {string} parserType the parser type used (c++ or js).\n */\nvar Server = function(options) {\n options = options || {};\n\n // Add event listener\n EventEmitter.call(this);\n\n // Server instance id\n this.id = id++;\n\n // Internal state\n this.s = {\n // Options\n options: Object.assign({ metadata: makeClientMetadata(options) }, options),\n // Logger\n logger: Logger('Server', options),\n // Factory overrides\n Cursor: options.cursorFactory || CoreCursor,\n // BSON instance\n bson:\n options.bson ||\n new BSON([\n BSON.Binary,\n BSON.Code,\n BSON.DBRef,\n BSON.Decimal128,\n BSON.Double,\n BSON.Int32,\n BSON.Long,\n BSON.Map,\n BSON.MaxKey,\n BSON.MinKey,\n BSON.ObjectId,\n BSON.BSONRegExp,\n BSON.Symbol,\n BSON.Timestamp\n ]),\n // Pool\n pool: null,\n // Disconnect handler\n disconnectHandler: options.disconnectHandler,\n // Monitor thread (keeps the connection alive)\n monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true,\n // Is the server in a topology\n inTopology: !!options.parent,\n // Monitoring timeout\n monitoringInterval:\n typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000,\n compression: { compressors: createCompressionInfo(options) },\n // Optional parent topology\n parent: options.parent\n };\n\n // If this is a single deployment we need to track the clusterTime here\n if (!this.s.parent) {\n this.s.clusterTime = null;\n }\n\n // Curent ismaster\n this.ismaster = null;\n // Current ping time\n this.lastIsMasterMS = -1;\n // The monitoringProcessId\n this.monitoringProcessId = null;\n // Initial connection\n this.initialConnect = true;\n // Default type\n this._type = 'server';\n\n // Max Stalleness values\n // last time we updated the ismaster state\n this.lastUpdateTime = 0;\n // Last write time\n this.lastWriteDate = 0;\n // Stalleness\n this.staleness = 0;\n};\n\ninherits(Server, EventEmitter);\nObject.assign(Server.prototype, SessionMixins);\n\nObject.defineProperty(Server.prototype, 'type', {\n enumerable: true,\n get: function() {\n return this._type;\n }\n});\n\nObject.defineProperty(Server.prototype, 'parserType', {\n enumerable: true,\n get: function() {\n return BSON.native ? 'c++' : 'js';\n }\n});\n\nObject.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', {\n enumerable: true,\n get: function() {\n if (!this.ismaster) return null;\n return this.ismaster.logicalSessionTimeoutMinutes || null;\n }\n});\n\nObject.defineProperty(Server.prototype, 'clientMetadata', {\n enumerable: true,\n get: function() {\n return this.s.options.metadata;\n }\n});\n\n// In single server deployments we track the clusterTime directly on the topology, however\n// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the\n// tracking objects so we can ensure we are gossiping the maximum time received from the\n// server.\nObject.defineProperty(Server.prototype, 'clusterTime', {\n enumerable: true,\n set: function(clusterTime) {\n const settings = this.s.parent ? this.s.parent : this.s;\n resolveClusterTime(settings, clusterTime);\n },\n get: function() {\n const settings = this.s.parent ? this.s.parent : this.s;\n return settings.clusterTime || null;\n }\n});\n\nServer.enableServerAccounting = function() {\n serverAccounting = true;\n servers = {};\n};\n\nServer.disableServerAccounting = function() {\n serverAccounting = false;\n};\n\nServer.servers = function() {\n return servers;\n};\n\nObject.defineProperty(Server.prototype, 'name', {\n enumerable: true,\n get: function() {\n return this.s.options.host + ':' + this.s.options.port;\n }\n});\n\nfunction disconnectHandler(self, type, ns, cmd, options, callback) {\n // Topology is not connected, save the call in the provided store to be\n // Executed at some point when the handler deems it's reconnected\n if (\n !self.s.pool.isConnected() &&\n self.s.options.reconnect &&\n self.s.disconnectHandler != null &&\n !options.monitoring\n ) {\n self.s.disconnectHandler.add(type, ns, cmd, options, callback);\n return true;\n }\n\n // If we have no connection error\n if (!self.s.pool.isConnected()) {\n callback(new MongoError(f('no connection available to server %s', self.name)));\n return true;\n }\n}\n\nfunction monitoringProcess(self) {\n return function() {\n // Pool was destroyed do not continue process\n if (self.s.pool.isDestroyed()) return;\n // Emit monitoring Process event\n self.emit('monitoring', self);\n // Perform ismaster call\n // Get start time\n var start = new Date().getTime();\n\n // Execute the ismaster query\n self.command(\n 'admin.$cmd',\n { ismaster: true },\n {\n socketTimeout:\n typeof self.s.options.connectionTimeout !== 'number'\n ? 2000\n : self.s.options.connectionTimeout,\n monitoring: true\n },\n (err, result) => {\n // Set initial lastIsMasterMS\n self.lastIsMasterMS = new Date().getTime() - start;\n if (self.s.pool.isDestroyed()) return;\n // Update the ismaster view if we have a result\n if (result) {\n self.ismaster = result.result;\n }\n // Re-schedule the monitoring process\n self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval);\n }\n );\n };\n}\n\nvar eventHandler = function(self, event) {\n return function(err, conn) {\n // Log information of received information if in info mode\n if (self.s.logger.isInfo()) {\n var object = err instanceof MongoError ? JSON.stringify(err) : {};\n self.s.logger.info(\n f('server %s fired event %s out with message %s', self.name, event, object)\n );\n }\n\n // Handle connect event\n if (event === 'connect') {\n self.initialConnect = false;\n self.ismaster = conn.ismaster;\n self.lastIsMasterMS = conn.lastIsMasterMS;\n if (conn.agreedCompressor) {\n self.s.pool.options.agreedCompressor = conn.agreedCompressor;\n }\n\n if (conn.zlibCompressionLevel) {\n self.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel;\n }\n\n if (conn.ismaster.$clusterTime) {\n const $clusterTime = conn.ismaster.$clusterTime;\n self.clusterTime = $clusterTime;\n }\n\n // It's a proxy change the type so\n // the wireprotocol will send $readPreference\n if (self.ismaster.msg === 'isdbgrid') {\n self._type = 'mongos';\n }\n\n // Have we defined self monitoring\n if (self.s.monitoring) {\n self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval);\n }\n\n // Emit server description changed if something listening\n sdam.emitServerDescriptionChanged(self, {\n address: self.name,\n arbiters: [],\n hosts: [],\n passives: [],\n type: sdam.getTopologyType(self)\n });\n\n if (!self.s.inTopology) {\n // Emit topology description changed if something listening\n sdam.emitTopologyDescriptionChanged(self, {\n topologyType: 'Single',\n servers: [\n {\n address: self.name,\n arbiters: [],\n hosts: [],\n passives: [],\n type: sdam.getTopologyType(self)\n }\n ]\n });\n }\n\n // Log the ismaster if available\n if (self.s.logger.isInfo()) {\n self.s.logger.info(\n f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster))\n );\n }\n\n // Emit connect\n self.emit('connect', self);\n } else if (\n event === 'error' ||\n event === 'parseError' ||\n event === 'close' ||\n event === 'timeout' ||\n event === 'reconnect' ||\n event === 'attemptReconnect' ||\n 'reconnectFailed'\n ) {\n // Remove server instance from accounting\n if (\n serverAccounting &&\n ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1\n ) {\n // Emit toplogy opening event if not in topology\n if (!self.s.inTopology) {\n self.emit('topologyOpening', { topologyId: self.id });\n }\n\n delete servers[self.id];\n }\n\n if (event === 'close') {\n // Closing emits a server description changed event going to unknown.\n sdam.emitServerDescriptionChanged(self, {\n address: self.name,\n arbiters: [],\n hosts: [],\n passives: [],\n type: 'Unknown'\n });\n }\n\n // Reconnect failed return error\n if (event === 'reconnectFailed') {\n self.emit('reconnectFailed', err);\n // Emit error if any listeners\n if (self.listeners('error').length > 0) {\n self.emit('error', err);\n }\n // Terminate\n return;\n }\n\n // On first connect fail\n if (\n ['disconnected', 'connecting'].indexOf(self.s.pool.state) !== -1 &&\n self.initialConnect &&\n ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1\n ) {\n self.initialConnect = false;\n return self.emit(\n 'error',\n new MongoNetworkError(\n f('failed to connect to server [%s] on first connect [%s]', self.name, err)\n )\n );\n }\n\n // Reconnect event, emit the server\n if (event === 'reconnect') {\n // Reconnecting emits a server description changed event going from unknown to the\n // current server type.\n sdam.emitServerDescriptionChanged(self, {\n address: self.name,\n arbiters: [],\n hosts: [],\n passives: [],\n type: sdam.getTopologyType(self)\n });\n return self.emit(event, self);\n }\n\n // Emit the event\n self.emit(event, err);\n }\n };\n};\n\n/**\n * Initiate server connect\n */\nServer.prototype.connect = function(options) {\n var self = this;\n options = options || {};\n\n // Set the connections\n if (serverAccounting) servers[this.id] = this;\n\n // Do not allow connect to be called on anything that's not disconnected\n if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) {\n throw new MongoError(f('server instance in invalid state %s', self.s.pool.state));\n }\n\n // Create a pool\n self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson }));\n\n // Set up listeners\n self.s.pool.on('close', eventHandler(self, 'close'));\n self.s.pool.on('error', eventHandler(self, 'error'));\n self.s.pool.on('timeout', eventHandler(self, 'timeout'));\n self.s.pool.on('parseError', eventHandler(self, 'parseError'));\n self.s.pool.on('connect', eventHandler(self, 'connect'));\n self.s.pool.on('reconnect', eventHandler(self, 'reconnect'));\n self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed'));\n\n // Set up listeners for command monitoring\n relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']);\n\n // Emit toplogy opening event if not in topology\n if (!self.s.inTopology) {\n this.emit('topologyOpening', { topologyId: topologyId(self) });\n }\n\n // Emit opening server event\n self.emit('serverOpening', { topologyId: topologyId(self), address: self.name });\n\n self.s.pool.connect();\n};\n\n/**\n * Authenticate the topology.\n * @method\n * @param {MongoCredentials} credentials The credentials for authentication we are using\n * @param {authResultCallback} callback A callback function\n */\nServer.prototype.auth = function(credentials, callback) {\n if (typeof callback === 'function') callback(null, null);\n};\n\n/**\n * Get the server description\n * @method\n * @return {object}\n */\nServer.prototype.getDescription = function() {\n var ismaster = this.ismaster || {};\n var description = {\n type: sdam.getTopologyType(this),\n address: this.name\n };\n\n // Add fields if available\n if (ismaster.hosts) description.hosts = ismaster.hosts;\n if (ismaster.arbiters) description.arbiters = ismaster.arbiters;\n if (ismaster.passives) description.passives = ismaster.passives;\n if (ismaster.setName) description.setName = ismaster.setName;\n return description;\n};\n\n/**\n * Returns the last known ismaster document for this server\n * @method\n * @return {object}\n */\nServer.prototype.lastIsMaster = function() {\n return this.ismaster;\n};\n\n/**\n * Unref all connections belong to this server\n * @method\n */\nServer.prototype.unref = function() {\n this.s.pool.unref();\n};\n\n/**\n * Figure out if the server is connected\n * @method\n * @return {boolean}\n */\nServer.prototype.isConnected = function() {\n if (!this.s.pool) return false;\n return this.s.pool.isConnected();\n};\n\n/**\n * Figure out if the server instance was destroyed by calling destroy\n * @method\n * @return {boolean}\n */\nServer.prototype.isDestroyed = function() {\n if (!this.s.pool) return false;\n return this.s.pool.isDestroyed();\n};\n\nfunction basicWriteValidations(self) {\n if (!self.s.pool) return new MongoError('server instance is not connected');\n if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed');\n}\n\nfunction basicReadValidations(self, options) {\n basicWriteValidations(self, options);\n\n if (options.readPreference && !(options.readPreference instanceof ReadPreference)) {\n throw new Error('readPreference must be an instance of ReadPreference');\n }\n}\n\n/**\n * Execute a command\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object} cmd The command hash\n * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {opResultCallback} callback A callback function\n */\nServer.prototype.command = function(ns, cmd, options, callback) {\n var self = this;\n if (typeof options === 'function') {\n (callback = options), (options = {}), (options = options || {});\n }\n\n var result = basicReadValidations(self, options);\n if (result) return callback(result);\n\n // Clone the options\n options = Object.assign({}, options, { wireProtocolCommand: false });\n\n // Debug log\n if (self.s.logger.isDebug())\n self.s.logger.debug(\n f(\n 'executing command [%s] against %s',\n JSON.stringify({\n ns: ns,\n cmd: cmd,\n options: debugOptions(debugFields, options)\n }),\n self.name\n )\n );\n\n // If we are not connected or have a disconnectHandler specified\n if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return;\n\n // error if collation not supported\n if (collationNotSupported(this, cmd)) {\n return callback(new MongoError(`server ${this.name} does not support collation`));\n }\n\n wireProtocol.command(self, ns, cmd, options, callback);\n};\n\n/**\n * Execute a query against the server\n *\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object} cmd The command document for the query\n * @param {object} options Optional settings\n * @param {function} callback\n */\nServer.prototype.query = function(ns, cmd, cursorState, options, callback) {\n wireProtocol.query(this, ns, cmd, cursorState, options, callback);\n};\n\n/**\n * Execute a `getMore` against the server\n *\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object} cursorState State data associated with the cursor calling this method\n * @param {object} options Optional settings\n * @param {function} callback\n */\nServer.prototype.getMore = function(ns, cursorState, batchSize, options, callback) {\n wireProtocol.getMore(this, ns, cursorState, batchSize, options, callback);\n};\n\n/**\n * Execute a `killCursors` command against the server\n *\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object} cursorState State data associated with the cursor calling this method\n * @param {function} callback\n */\nServer.prototype.killCursors = function(ns, cursorState, callback) {\n wireProtocol.killCursors(this, ns, cursorState, callback);\n};\n\n/**\n * Insert one or more documents\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of documents to insert\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {opResultCallback} callback A callback function\n */\nServer.prototype.insert = function(ns, ops, options, callback) {\n var self = this;\n if (typeof options === 'function') {\n (callback = options), (options = {}), (options = options || {});\n }\n\n var result = basicWriteValidations(self, options);\n if (result) return callback(result);\n\n // If we are not connected or have a disconnectHandler specified\n if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return;\n\n // Setup the docs as an array\n ops = Array.isArray(ops) ? ops : [ops];\n\n // Execute write\n return wireProtocol.insert(self, ns, ops, options, callback);\n};\n\n/**\n * Perform one or more update operations\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of updates\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {opResultCallback} callback A callback function\n */\nServer.prototype.update = function(ns, ops, options, callback) {\n var self = this;\n if (typeof options === 'function') {\n (callback = options), (options = {}), (options = options || {});\n }\n\n var result = basicWriteValidations(self, options);\n if (result) return callback(result);\n\n // If we are not connected or have a disconnectHandler specified\n if (disconnectHandler(self, 'update', ns, ops, options, callback)) return;\n\n // error if collation not supported\n if (collationNotSupported(this, options)) {\n return callback(new MongoError(`server ${this.name} does not support collation`));\n }\n\n // Setup the docs as an array\n ops = Array.isArray(ops) ? ops : [ops];\n // Execute write\n return wireProtocol.update(self, ns, ops, options, callback);\n};\n\n/**\n * Perform one or more remove operations\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {array} ops An array of removes\n * @param {boolean} [options.ordered=true] Execute in order or out of order\n * @param {object} [options.writeConcern={}] Write concern for the operation\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {opResultCallback} callback A callback function\n */\nServer.prototype.remove = function(ns, ops, options, callback) {\n var self = this;\n if (typeof options === 'function') {\n (callback = options), (options = {}), (options = options || {});\n }\n\n var result = basicWriteValidations(self, options);\n if (result) return callback(result);\n\n // If we are not connected or have a disconnectHandler specified\n if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return;\n\n // error if collation not supported\n if (collationNotSupported(this, options)) {\n return callback(new MongoError(`server ${this.name} does not support collation`));\n }\n\n // Setup the docs as an array\n ops = Array.isArray(ops) ? ops : [ops];\n // Execute write\n return wireProtocol.remove(self, ns, ops, options, callback);\n};\n\n/**\n * Get a new cursor\n * @method\n * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)\n * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId\n * @param {object} [options] Options for the cursor\n * @param {object} [options.batchSize=0] Batchsize for the operation\n * @param {array} [options.documents=[]] Initial documents list for cursor\n * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it\n * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {ClientSession} [options.session=null] Session to use for the operation\n * @param {object} [options.topology] The internal topology of the created cursor\n * @returns {Cursor}\n */\nServer.prototype.cursor = function(ns, cmd, options) {\n options = options || {};\n const topology = options.topology || this;\n\n // Set up final cursor type\n var FinalCursor = options.cursorFactory || this.s.Cursor;\n\n // Return the cursor\n return new FinalCursor(topology, ns, cmd, options);\n};\n\n/**\n * Compare two server instances\n * @method\n * @param {Server} server Server to compare equality against\n * @return {boolean}\n */\nServer.prototype.equals = function(server) {\n if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase();\n if (server.name) return this.name.toLowerCase() === server.name.toLowerCase();\n return false;\n};\n\n/**\n * All raw connections\n * @method\n * @return {Connection[]}\n */\nServer.prototype.connections = function() {\n return this.s.pool.allConnections();\n};\n\n/**\n * Selects a server\n * @method\n * @param {function} selector Unused\n * @param {ReadPreference} [options.readPreference] Unused\n * @param {ClientSession} [options.session] Unused\n * @return {Server}\n */\nServer.prototype.selectServer = function(selector, options, callback) {\n if (typeof selector === 'function' && typeof callback === 'undefined')\n (callback = selector), (selector = undefined), (options = {});\n if (typeof options === 'function')\n (callback = options), (options = selector), (selector = undefined);\n\n callback(null, this);\n};\n\nvar listeners = ['close', 'error', 'timeout', 'parseError', 'connect'];\n\n/**\n * Destroy the server connection\n * @method\n * @param {boolean} [options.emitClose=false] Emit close event on destroy\n * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy\n * @param {boolean} [options.force=false] Force destroy the pool\n */\nServer.prototype.destroy = function(options, callback) {\n if (this._destroyed) {\n if (typeof callback === 'function') callback(null, null);\n return;\n }\n\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n options = options || {};\n var self = this;\n\n // Set the connections\n if (serverAccounting) delete servers[this.id];\n\n // Destroy the monitoring process if any\n if (this.monitoringProcessId) {\n clearTimeout(this.monitoringProcessId);\n }\n\n // No pool, return\n if (!self.s.pool) {\n this._destroyed = true;\n if (typeof callback === 'function') callback(null, null);\n return;\n }\n\n // Emit close event\n if (options.emitClose) {\n self.emit('close', self);\n }\n\n // Emit destroy event\n if (options.emitDestroy) {\n self.emit('destroy', self);\n }\n\n // Remove all listeners\n listeners.forEach(function(event) {\n self.s.pool.removeAllListeners(event);\n });\n\n // Emit opening server event\n if (self.listeners('serverClosed').length > 0)\n self.emit('serverClosed', { topologyId: topologyId(self), address: self.name });\n\n // Emit toplogy opening event if not in topology\n if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) {\n self.emit('topologyClosed', { topologyId: topologyId(self) });\n }\n\n if (self.s.logger.isDebug()) {\n self.s.logger.debug(f('destroy called on server %s', self.name));\n }\n\n // Destroy the pool\n this.s.pool.destroy(options.force, callback);\n this._destroyed = true;\n};\n\n/**\n * A server connect event, used to verify that the connection is up and running\n *\n * @event Server#connect\n * @type {Server}\n */\n\n/**\n * A server reconnect event, used to verify that the server topology has reconnected\n *\n * @event Server#reconnect\n * @type {Server}\n */\n\n/**\n * A server opening SDAM monitoring event\n *\n * @event Server#serverOpening\n * @type {object}\n */\n\n/**\n * A server closed SDAM monitoring event\n *\n * @event Server#serverClosed\n * @type {object}\n */\n\n/**\n * A server description SDAM change monitoring event\n *\n * @event Server#serverDescriptionChanged\n * @type {object}\n */\n\n/**\n * A topology open SDAM event\n *\n * @event Server#topologyOpening\n * @type {object}\n */\n\n/**\n * A topology closed SDAM event\n *\n * @event Server#topologyClosed\n * @type {object}\n */\n\n/**\n * A topology structure SDAM change event\n *\n * @event Server#topologyDescriptionChanged\n * @type {object}\n */\n\n/**\n * Server reconnect failed\n *\n * @event Server#reconnectFailed\n * @type {Error}\n */\n\n/**\n * Server connection pool closed\n *\n * @event Server#close\n * @type {object}\n */\n\n/**\n * Server connection pool caused an error\n *\n * @event Server#error\n * @type {Error}\n */\n\n/**\n * Server destroyed was called\n *\n * @event Server#destroy\n * @type {Server}\n */\n\nmodule.exports = Server;\n","'use strict';\nconst ReadPreference = require('./read_preference');\nconst TopologyType = require('../sdam/common').TopologyType;\nconst MongoError = require('../error').MongoError;\nconst isRetryableWriteError = require('../error').isRetryableWriteError;\nconst maxWireVersion = require('../utils').maxWireVersion;\nconst MongoNetworkError = require('../error').MongoNetworkError;\nconst MMAPv1_RETRY_WRITES_ERROR_CODE = 20;\n\n/**\n * Emit event if it exists\n * @method\n */\nfunction emitSDAMEvent(self, event, description) {\n if (self.listeners(event).length > 0) {\n self.emit(event, description);\n }\n}\n\nfunction createCompressionInfo(options) {\n if (!options.compression || !options.compression.compressors) {\n return [];\n }\n\n // Check that all supplied compressors are valid\n options.compression.compressors.forEach(function(compressor) {\n if (compressor !== 'snappy' && compressor !== 'zlib') {\n throw new Error('compressors must be at least one of snappy or zlib');\n }\n });\n\n return options.compression.compressors;\n}\n\nfunction clone(object) {\n return JSON.parse(JSON.stringify(object));\n}\n\nvar getPreviousDescription = function(self) {\n if (!self.s.serverDescription) {\n self.s.serverDescription = {\n address: self.name,\n arbiters: [],\n hosts: [],\n passives: [],\n type: 'Unknown'\n };\n }\n\n return self.s.serverDescription;\n};\n\nvar emitServerDescriptionChanged = function(self, description) {\n if (self.listeners('serverDescriptionChanged').length > 0) {\n // Emit the server description changed events\n self.emit('serverDescriptionChanged', {\n topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id,\n address: self.name,\n previousDescription: getPreviousDescription(self),\n newDescription: description\n });\n\n self.s.serverDescription = description;\n }\n};\n\nvar getPreviousTopologyDescription = function(self) {\n if (!self.s.topologyDescription) {\n self.s.topologyDescription = {\n topologyType: 'Unknown',\n servers: [\n {\n address: self.name,\n arbiters: [],\n hosts: [],\n passives: [],\n type: 'Unknown'\n }\n ]\n };\n }\n\n return self.s.topologyDescription;\n};\n\nvar emitTopologyDescriptionChanged = function(self, description) {\n if (self.listeners('topologyDescriptionChanged').length > 0) {\n // Emit the server description changed events\n self.emit('topologyDescriptionChanged', {\n topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id,\n address: self.name,\n previousDescription: getPreviousTopologyDescription(self),\n newDescription: description\n });\n\n self.s.serverDescription = description;\n }\n};\n\nvar changedIsMaster = function(self, currentIsmaster, ismaster) {\n var currentType = getTopologyType(self, currentIsmaster);\n var newType = getTopologyType(self, ismaster);\n if (newType !== currentType) return true;\n return false;\n};\n\nvar getTopologyType = function(self, ismaster) {\n if (!ismaster) {\n ismaster = self.ismaster;\n }\n\n if (!ismaster) return 'Unknown';\n if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos';\n if (ismaster.ismaster && !ismaster.hosts) return 'Standalone';\n if (ismaster.ismaster) return 'RSPrimary';\n if (ismaster.secondary) return 'RSSecondary';\n if (ismaster.arbiterOnly) return 'RSArbiter';\n return 'Unknown';\n};\n\nvar inquireServerState = function(self) {\n return function(callback) {\n if (self.s.state === 'destroyed') return;\n // Record response time\n var start = new Date().getTime();\n\n // emitSDAMEvent\n emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name });\n\n // Attempt to execute ismaster command\n self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) {\n if (!err) {\n // Legacy event sender\n self.emit('ismaster', r, self);\n\n // Calculate latencyMS\n var latencyMS = new Date().getTime() - start;\n\n // Server heart beat event\n emitSDAMEvent(self, 'serverHeartbeatSucceeded', {\n durationMS: latencyMS,\n reply: r.result,\n connectionId: self.name\n });\n\n // Did the server change\n if (changedIsMaster(self, self.s.ismaster, r.result)) {\n // Emit server description changed if something listening\n emitServerDescriptionChanged(self, {\n address: self.name,\n arbiters: [],\n hosts: [],\n passives: [],\n type: !self.s.inTopology ? 'Standalone' : getTopologyType(self)\n });\n }\n\n // Updat ismaster view\n self.s.ismaster = r.result;\n\n // Set server response time\n self.s.isMasterLatencyMS = latencyMS;\n } else {\n emitSDAMEvent(self, 'serverHeartbeatFailed', {\n durationMS: latencyMS,\n failure: err,\n connectionId: self.name\n });\n }\n\n // Peforming an ismaster monitoring callback operation\n if (typeof callback === 'function') {\n return callback(err, r);\n }\n\n // Perform another sweep\n self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval);\n });\n };\n};\n\n//\n// Clone the options\nvar cloneOptions = function(options) {\n var opts = {};\n for (var name in options) {\n opts[name] = options[name];\n }\n return opts;\n};\n\nfunction Interval(fn, time) {\n var timer = false;\n\n this.start = function() {\n if (!this.isRunning()) {\n timer = setInterval(fn, time);\n }\n\n return this;\n };\n\n this.stop = function() {\n clearInterval(timer);\n timer = false;\n return this;\n };\n\n this.isRunning = function() {\n return timer !== false;\n };\n}\n\nfunction Timeout(fn, time) {\n var timer = false;\n var func = () => {\n if (timer) {\n clearTimeout(timer);\n timer = false;\n\n fn();\n }\n };\n\n this.start = function() {\n if (!this.isRunning()) {\n timer = setTimeout(func, time);\n }\n return this;\n };\n\n this.stop = function() {\n clearTimeout(timer);\n timer = false;\n return this;\n };\n\n this.isRunning = function() {\n return timer !== false;\n };\n}\n\nfunction diff(previous, current) {\n // Difference document\n var diff = {\n servers: []\n };\n\n // Previous entry\n if (!previous) {\n previous = { servers: [] };\n }\n\n // Check if we have any previous servers missing in the current ones\n for (var i = 0; i < previous.servers.length; i++) {\n var found = false;\n\n for (var j = 0; j < current.servers.length; j++) {\n if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) {\n found = true;\n break;\n }\n }\n\n if (!found) {\n // Add to the diff\n diff.servers.push({\n address: previous.servers[i].address,\n from: previous.servers[i].type,\n to: 'Unknown'\n });\n }\n }\n\n // Check if there are any severs that don't exist\n for (j = 0; j < current.servers.length; j++) {\n found = false;\n\n // Go over all the previous servers\n for (i = 0; i < previous.servers.length; i++) {\n if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) {\n found = true;\n break;\n }\n }\n\n // Add the server to the diff\n if (!found) {\n diff.servers.push({\n address: current.servers[j].address,\n from: 'Unknown',\n to: current.servers[j].type\n });\n }\n }\n\n // Got through all the servers\n for (i = 0; i < previous.servers.length; i++) {\n var prevServer = previous.servers[i];\n\n // Go through all current servers\n for (j = 0; j < current.servers.length; j++) {\n var currServer = current.servers[j];\n\n // Matching server\n if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) {\n // We had a change in state\n if (prevServer.type !== currServer.type) {\n diff.servers.push({\n address: prevServer.address,\n from: prevServer.type,\n to: currServer.type\n });\n }\n }\n }\n }\n\n // Return difference\n return diff;\n}\n\n/**\n * Shared function to determine clusterTime for a given topology\n *\n * @param {*} topology\n * @param {*} clusterTime\n */\nfunction resolveClusterTime(topology, $clusterTime) {\n if (topology.clusterTime == null) {\n topology.clusterTime = $clusterTime;\n } else {\n if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) {\n topology.clusterTime = $clusterTime;\n }\n }\n}\n\n// NOTE: this is a temporary move until the topologies can be more formally refactored\n// to share code.\nconst SessionMixins = {\n endSessions: function(sessions, callback) {\n if (!Array.isArray(sessions)) {\n sessions = [sessions];\n }\n\n // TODO:\n // When connected to a sharded cluster the endSessions command\n // can be sent to any mongos. When connected to a replica set the\n // endSessions command MUST be sent to the primary if the primary\n // is available, otherwise it MUST be sent to any available secondary.\n // Is it enough to use: ReadPreference.primaryPreferred ?\n this.command(\n 'admin.$cmd',\n { endSessions: sessions },\n { readPreference: ReadPreference.primaryPreferred },\n () => {\n // intentionally ignored, per spec\n if (typeof callback === 'function') callback();\n }\n );\n }\n};\n\nfunction topologyType(topology) {\n if (topology.description) {\n return topology.description.type;\n }\n\n if (topology.type === 'mongos') {\n return TopologyType.Sharded;\n } else if (topology.type === 'replset') {\n return TopologyType.ReplicaSetWithPrimary;\n }\n\n return TopologyType.Single;\n}\n\nconst RETRYABLE_WIRE_VERSION = 6;\n\n/**\n * Determines whether the provided topology supports retryable writes\n *\n * @param {Mongos|Replset} topology\n */\nconst isRetryableWritesSupported = function(topology) {\n const maxWireVersion = topology.lastIsMaster().maxWireVersion;\n if (maxWireVersion < RETRYABLE_WIRE_VERSION) {\n return false;\n }\n\n if (!topology.logicalSessionTimeoutMinutes) {\n return false;\n }\n\n if (topologyType(topology) === TopologyType.Single) {\n return false;\n }\n\n return true;\n};\n\nconst MMAPv1_RETRY_WRITES_ERROR_MESSAGE =\n 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.';\n\nfunction getMMAPError(err) {\n if (err.code !== MMAPv1_RETRY_WRITES_ERROR_CODE || !err.errmsg.includes('Transaction numbers')) {\n return err;\n }\n\n // According to the retryable writes spec, we must replace the error message in this case.\n // We need to replace err.message so the thrown message is correct and we need to replace err.errmsg to meet the spec requirement.\n const newErr = new MongoError({\n message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE,\n errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE,\n originalError: err\n });\n return newErr;\n}\n\n// NOTE: only used for legacy topology types\nfunction legacyIsRetryableWriteError(err, topology) {\n if (!(err instanceof MongoError)) {\n return false;\n }\n\n // if pre-4.4 server, then add error label if its a retryable write error\n if (\n isRetryableWritesSupported(topology) &&\n (err instanceof MongoNetworkError ||\n (maxWireVersion(topology) < 9 && isRetryableWriteError(err)))\n ) {\n err.addErrorLabel('RetryableWriteError');\n }\n\n return err.hasErrorLabel('RetryableWriteError');\n}\n\nmodule.exports = {\n SessionMixins,\n resolveClusterTime,\n inquireServerState,\n getTopologyType,\n emitServerDescriptionChanged,\n emitTopologyDescriptionChanged,\n cloneOptions,\n createCompressionInfo,\n clone,\n diff,\n Interval,\n Timeout,\n isRetryableWritesSupported,\n getMMAPError,\n topologyType,\n legacyIsRetryableWriteError\n};\n","'use strict';\nconst MongoError = require('./error').MongoError;\nconst ReadPreference = require('./topologies/read_preference');\nconst ReadConcern = require('../read_concern');\nconst WriteConcern = require('../write_concern');\n\nlet TxnState;\nlet stateMachine;\n\n(() => {\n const NO_TRANSACTION = 'NO_TRANSACTION';\n const STARTING_TRANSACTION = 'STARTING_TRANSACTION';\n const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS';\n const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED';\n const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY';\n const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED';\n\n TxnState = {\n NO_TRANSACTION,\n STARTING_TRANSACTION,\n TRANSACTION_IN_PROGRESS,\n TRANSACTION_COMMITTED,\n TRANSACTION_COMMITTED_EMPTY,\n TRANSACTION_ABORTED\n };\n\n stateMachine = {\n [NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION],\n [STARTING_TRANSACTION]: [\n TRANSACTION_IN_PROGRESS,\n TRANSACTION_COMMITTED,\n TRANSACTION_COMMITTED_EMPTY,\n TRANSACTION_ABORTED\n ],\n [TRANSACTION_IN_PROGRESS]: [\n TRANSACTION_IN_PROGRESS,\n TRANSACTION_COMMITTED,\n TRANSACTION_ABORTED\n ],\n [TRANSACTION_COMMITTED]: [\n TRANSACTION_COMMITTED,\n TRANSACTION_COMMITTED_EMPTY,\n STARTING_TRANSACTION,\n NO_TRANSACTION\n ],\n [TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION],\n [TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION]\n };\n})();\n\n/**\n * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties\n * of the data read from replica sets and replica set shards.\n * @typedef {Object} ReadConcern\n * @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level\n * @see https://docs.mongodb.com/manual/reference/read-concern/\n */\n\n/**\n * A MongoDB WriteConcern, which describes the level of acknowledgement\n * requested from MongoDB for write operations.\n * @typedef {Object} WriteConcern\n * @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has\n * propagated to a specified number of mongod hosts\n * @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has\n * been written to the journal\n * @property {number} [wtimeout] a time limit, in milliseconds, for the write concern\n * @see https://docs.mongodb.com/manual/reference/write-concern/\n */\n\n/**\n * Configuration options for a transaction.\n * @typedef {Object} TransactionOptions\n * @property {ReadConcern} [readConcern] A default read concern for commands in this transaction\n * @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction\n * @property {ReadPreference} [readPreference] A default read preference for commands in this transaction\n */\n\n/**\n * A class maintaining state related to a server transaction. Internal Only\n * @ignore\n */\nclass Transaction {\n /**\n * Create a transaction\n *\n * @ignore\n * @param {TransactionOptions} [options] Optional settings\n */\n constructor(options) {\n options = options || {};\n\n this.state = TxnState.NO_TRANSACTION;\n this.options = {};\n\n const writeConcern = WriteConcern.fromOptions(options);\n if (writeConcern) {\n if (writeConcern.w <= 0) {\n throw new MongoError('Transactions do not support unacknowledged write concern');\n }\n\n this.options.writeConcern = writeConcern;\n }\n\n if (options.readConcern) {\n this.options.readConcern = ReadConcern.fromOptions(options);\n }\n\n if (options.readPreference) {\n this.options.readPreference = ReadPreference.fromOptions(options);\n }\n\n if (options.maxCommitTimeMS) {\n this.options.maxTimeMS = options.maxCommitTimeMS;\n }\n\n // TODO: This isn't technically necessary\n this._pinnedServer = undefined;\n this._recoveryToken = undefined;\n }\n\n get server() {\n return this._pinnedServer;\n }\n\n get recoveryToken() {\n return this._recoveryToken;\n }\n\n get isPinned() {\n return !!this.server;\n }\n\n /**\n * @ignore\n * @return Whether this session is presently in a transaction\n */\n get isActive() {\n return (\n [TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1\n );\n }\n\n /**\n * Transition the transaction in the state machine\n * @ignore\n * @param {TxnState} state The new state to transition to\n */\n transition(nextState) {\n const nextStates = stateMachine[this.state];\n if (nextStates && nextStates.indexOf(nextState) !== -1) {\n this.state = nextState;\n if (this.state === TxnState.NO_TRANSACTION || this.state === TxnState.STARTING_TRANSACTION) {\n this.unpinServer();\n }\n return;\n }\n\n throw new MongoError(\n `Attempted illegal state transition from [${this.state}] to [${nextState}]`\n );\n }\n\n pinServer(server) {\n if (this.isActive) {\n this._pinnedServer = server;\n }\n }\n\n unpinServer() {\n this._pinnedServer = undefined;\n }\n}\n\nfunction isTransactionCommand(command) {\n return !!(command.commitTransaction || command.abortTransaction);\n}\n\nmodule.exports = { TxnState, Transaction, isTransactionCommand };\n","'use strict';\nconst URL = require('url');\nconst qs = require('querystring');\nconst dns = require('dns');\nconst MongoParseError = require('./error').MongoParseError;\nconst ReadPreference = require('./topologies/read_preference');\n\n/**\n * The following regular expression validates a connection string and breaks the\n * provide string into the following capture groups: [protocol, username, password, hosts]\n */\nconst HOSTS_RX = /(mongodb(?:\\+srv|)):\\/\\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\\/|)(.*)/;\n\n/**\n * Determines whether a provided address matches the provided parent domain in order\n * to avoid certain attack vectors.\n *\n * @param {String} srvAddress The address to check against a domain\n * @param {String} parentDomain The domain to check the provided address against\n * @return {Boolean} Whether the provided address matches the parent domain\n */\nfunction matchesParentDomain(srvAddress, parentDomain) {\n const regex = /^.*?\\./;\n const srv = `.${srvAddress.replace(regex, '')}`;\n const parent = `.${parentDomain.replace(regex, '')}`;\n return srv.endsWith(parent);\n}\n\n/**\n * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal\n * connection string.\n *\n * @param {string} uri The connection string to parse\n * @param {object} options Optional user provided connection string options\n * @param {function} callback\n */\nfunction parseSrvConnectionString(uri, options, callback) {\n const result = URL.parse(uri, true);\n\n if (options.directConnection || options.directconnection) {\n return callback(new MongoParseError('directConnection not supported with SRV URI'));\n }\n\n if (result.hostname.split('.').length < 3) {\n return callback(new MongoParseError('URI does not have hostname, domain name and tld'));\n }\n\n result.domainLength = result.hostname.split('.').length;\n if (result.pathname && result.pathname.match(',')) {\n return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames'));\n }\n\n if (result.port) {\n return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`));\n }\n\n // Resolve the SRV record and use the result as the list of hosts to connect to.\n const lookupAddress = result.host;\n dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => {\n if (err) return callback(err);\n\n if (addresses.length === 0) {\n return callback(new MongoParseError('No addresses found at host'));\n }\n\n for (let i = 0; i < addresses.length; i++) {\n if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) {\n return callback(\n new MongoParseError('Server record does not share hostname with parent URI')\n );\n }\n }\n\n // Convert the original URL to a non-SRV URL.\n result.protocol = 'mongodb';\n result.host = addresses.map(address => `${address.name}:${address.port}`).join(',');\n\n // Default to SSL true if it's not specified.\n if (\n !('ssl' in options) &&\n (!result.search || !('ssl' in result.query) || result.query.ssl === null)\n ) {\n result.query.ssl = true;\n }\n\n // Resolve TXT record and add options from there if they exist.\n dns.resolveTxt(lookupAddress, (err, record) => {\n if (err) {\n if (err.code !== 'ENODATA') {\n return callback(err);\n }\n record = null;\n }\n\n if (record) {\n if (record.length > 1) {\n return callback(new MongoParseError('Multiple text records not allowed'));\n }\n\n record = qs.parse(record[0].join(''));\n if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) {\n return callback(\n new MongoParseError('Text record must only set `authSource` or `replicaSet`')\n );\n }\n\n result.query = Object.assign({}, record, result.query);\n }\n\n // Set completed options back into the URL object.\n result.search = qs.stringify(result.query);\n\n const finalString = URL.format(result);\n parseConnectionString(finalString, options, (err, ret) => {\n if (err) {\n callback(err);\n return;\n }\n\n callback(null, Object.assign({}, ret, { srvHost: lookupAddress }));\n });\n });\n });\n}\n\n/**\n * Parses a query string item according to the connection string spec\n *\n * @param {string} key The key for the parsed value\n * @param {Array|String} value The value to parse\n * @return {Array|Object|String} The parsed value\n */\nfunction parseQueryStringItemValue(key, value) {\n if (Array.isArray(value)) {\n // deduplicate and simplify arrays\n value = value.filter((v, idx) => value.indexOf(v) === idx);\n if (value.length === 1) value = value[0];\n } else if (value.indexOf(':') > 0) {\n value = value.split(',').reduce((result, pair) => {\n const parts = pair.split(':');\n result[parts[0]] = parseQueryStringItemValue(key, parts[1]);\n return result;\n }, {});\n } else if (value.indexOf(',') > 0) {\n value = value.split(',').map(v => {\n return parseQueryStringItemValue(key, v);\n });\n } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') {\n value = value.toLowerCase() === 'true';\n } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) {\n const numericValue = parseFloat(value);\n if (!Number.isNaN(numericValue)) {\n value = parseFloat(value);\n }\n }\n\n return value;\n}\n\n// Options that are known boolean types\nconst BOOLEAN_OPTIONS = new Set([\n 'slaveok',\n 'slave_ok',\n 'sslvalidate',\n 'fsync',\n 'safe',\n 'retrywrites',\n 'j'\n]);\n\n// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue`\nconst STRING_OPTIONS = new Set(['authsource', 'replicaset']);\n\n// Supported text representations of auth mechanisms\n// NOTE: this list exists in native already, if it is merged here we should deduplicate\nconst AUTH_MECHANISMS = new Set([\n 'GSSAPI',\n 'MONGODB-AWS',\n 'MONGODB-X509',\n 'MONGODB-CR',\n 'DEFAULT',\n 'SCRAM-SHA-1',\n 'SCRAM-SHA-256',\n 'PLAIN'\n]);\n\n// Lookup table used to translate normalized (lower-cased) forms of connection string\n// options to their expected camelCase version\nconst CASE_TRANSLATION = {\n replicaset: 'replicaSet',\n connecttimeoutms: 'connectTimeoutMS',\n sockettimeoutms: 'socketTimeoutMS',\n maxpoolsize: 'maxPoolSize',\n minpoolsize: 'minPoolSize',\n maxidletimems: 'maxIdleTimeMS',\n waitqueuemultiple: 'waitQueueMultiple',\n waitqueuetimeoutms: 'waitQueueTimeoutMS',\n wtimeoutms: 'wtimeoutMS',\n readconcern: 'readConcern',\n readconcernlevel: 'readConcernLevel',\n readpreference: 'readPreference',\n maxstalenessseconds: 'maxStalenessSeconds',\n readpreferencetags: 'readPreferenceTags',\n authsource: 'authSource',\n authmechanism: 'authMechanism',\n authmechanismproperties: 'authMechanismProperties',\n gssapiservicename: 'gssapiServiceName',\n localthresholdms: 'localThresholdMS',\n serverselectiontimeoutms: 'serverSelectionTimeoutMS',\n serverselectiontryonce: 'serverSelectionTryOnce',\n heartbeatfrequencyms: 'heartbeatFrequencyMS',\n retrywrites: 'retryWrites',\n uuidrepresentation: 'uuidRepresentation',\n zlibcompressionlevel: 'zlibCompressionLevel',\n tlsallowinvalidcertificates: 'tlsAllowInvalidCertificates',\n tlsallowinvalidhostnames: 'tlsAllowInvalidHostnames',\n tlsinsecure: 'tlsInsecure',\n tlscafile: 'tlsCAFile',\n tlscertificatekeyfile: 'tlsCertificateKeyFile',\n tlscertificatekeyfilepassword: 'tlsCertificateKeyFilePassword',\n wtimeout: 'wTimeoutMS',\n j: 'journal',\n directconnection: 'directConnection'\n};\n\n/**\n * Sets the value for `key`, allowing for any required translation\n *\n * @param {object} obj The object to set the key on\n * @param {string} key The key to set the value for\n * @param {*} value The value to set\n * @param {object} options The options used for option parsing\n */\nfunction applyConnectionStringOption(obj, key, value, options) {\n // simple key translation\n if (key === 'journal') {\n key = 'j';\n } else if (key === 'wtimeoutms') {\n key = 'wtimeout';\n }\n\n // more complicated translation\n if (BOOLEAN_OPTIONS.has(key)) {\n value = value === 'true' || value === true;\n } else if (key === 'appname') {\n value = decodeURIComponent(value);\n } else if (key === 'readconcernlevel') {\n obj['readConcernLevel'] = value;\n key = 'readconcern';\n value = { level: value };\n }\n\n // simple validation\n if (key === 'compressors') {\n value = Array.isArray(value) ? value : [value];\n\n if (!value.every(c => c === 'snappy' || c === 'zlib')) {\n throw new MongoParseError(\n 'Value for `compressors` must be at least one of: `snappy`, `zlib`'\n );\n }\n }\n\n if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) {\n throw new MongoParseError(\n `Value for authMechanism must be one of: ${Array.from(AUTH_MECHANISMS).join(\n ', '\n )}, found: ${value}`\n );\n }\n\n if (key === 'readpreference' && !ReadPreference.isValid(value)) {\n throw new MongoParseError(\n 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`'\n );\n }\n\n if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) {\n throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9');\n }\n\n // special cases\n if (key === 'compressors' || key === 'zlibcompressionlevel') {\n obj.compression = obj.compression || {};\n obj = obj.compression;\n }\n\n if (key === 'authmechanismproperties') {\n if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME;\n if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM;\n if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') {\n obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME;\n }\n }\n\n if (key === 'readpreferencetags') {\n value = Array.isArray(value) ? splitArrayOfMultipleReadPreferenceTags(value) : [value];\n }\n\n // set the actual value\n if (options.caseTranslate && CASE_TRANSLATION[key]) {\n obj[CASE_TRANSLATION[key]] = value;\n return;\n }\n\n obj[key] = value;\n}\n\nconst USERNAME_REQUIRED_MECHANISMS = new Set([\n 'GSSAPI',\n 'MONGODB-CR',\n 'PLAIN',\n 'SCRAM-SHA-1',\n 'SCRAM-SHA-256'\n]);\n\nfunction splitArrayOfMultipleReadPreferenceTags(value) {\n const parsedTags = [];\n\n for (let i = 0; i < value.length; i++) {\n parsedTags[i] = {};\n value[i].split(',').forEach(individualTag => {\n const splitTag = individualTag.split(':');\n parsedTags[i][splitTag[0]] = splitTag[1];\n });\n }\n\n return parsedTags;\n}\n\n/**\n * Modifies the parsed connection string object taking into account expectations we\n * have for authentication-related options.\n *\n * @param {object} parsed The parsed connection string result\n * @return The parsed connection string result possibly modified for auth expectations\n */\nfunction applyAuthExpectations(parsed) {\n if (parsed.options == null) {\n return;\n }\n\n const options = parsed.options;\n const authSource = options.authsource || options.authSource;\n if (authSource != null) {\n parsed.auth = Object.assign({}, parsed.auth, { db: authSource });\n }\n\n const authMechanism = options.authmechanism || options.authMechanism;\n if (authMechanism != null) {\n if (\n USERNAME_REQUIRED_MECHANISMS.has(authMechanism) &&\n (!parsed.auth || parsed.auth.username == null)\n ) {\n throw new MongoParseError(`Username required for mechanism \\`${authMechanism}\\``);\n }\n\n if (authMechanism === 'GSSAPI') {\n if (authSource != null && authSource !== '$external') {\n throw new MongoParseError(\n `Invalid source \\`${authSource}\\` for mechanism \\`${authMechanism}\\` specified.`\n );\n }\n\n parsed.auth = Object.assign({}, parsed.auth, { db: '$external' });\n }\n\n if (authMechanism === 'MONGODB-AWS') {\n if (authSource != null && authSource !== '$external') {\n throw new MongoParseError(\n `Invalid source \\`${authSource}\\` for mechanism \\`${authMechanism}\\` specified.`\n );\n }\n\n parsed.auth = Object.assign({}, parsed.auth, { db: '$external' });\n }\n\n if (authMechanism === 'MONGODB-X509') {\n if (parsed.auth && parsed.auth.password != null) {\n throw new MongoParseError(`Password not allowed for mechanism \\`${authMechanism}\\``);\n }\n\n if (authSource != null && authSource !== '$external') {\n throw new MongoParseError(\n `Invalid source \\`${authSource}\\` for mechanism \\`${authMechanism}\\` specified.`\n );\n }\n\n parsed.auth = Object.assign({}, parsed.auth, { db: '$external' });\n }\n\n if (authMechanism === 'PLAIN') {\n if (parsed.auth && parsed.auth.db == null) {\n parsed.auth = Object.assign({}, parsed.auth, { db: '$external' });\n }\n }\n }\n\n // default to `admin` if nothing else was resolved\n if (parsed.auth && parsed.auth.db == null) {\n parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' });\n }\n\n return parsed;\n}\n\n/**\n * Parses a query string according the connection string spec.\n *\n * @param {String} query The query string to parse\n * @param {object} [options] The options used for options parsing\n * @return {Object|Error} The parsed query string as an object, or an error if one was encountered\n */\nfunction parseQueryString(query, options) {\n const result = {};\n let parsedQueryString = qs.parse(query);\n\n checkTLSOptions(parsedQueryString);\n\n for (const key in parsedQueryString) {\n const value = parsedQueryString[key];\n if (value === '' || value == null) {\n throw new MongoParseError('Incomplete key value pair for option');\n }\n\n const normalizedKey = key.toLowerCase();\n const parsedValue = parseQueryStringItemValue(normalizedKey, value);\n applyConnectionStringOption(result, normalizedKey, parsedValue, options);\n }\n\n // special cases for known deprecated options\n if (result.wtimeout && result.wtimeoutms) {\n delete result.wtimeout;\n console.warn('Unsupported option `wtimeout` specified');\n }\n\n return Object.keys(result).length ? result : null;\n}\n\n/// Adds support for modern `tls` variants of out `ssl` options\nfunction translateTLSOptions(queryString) {\n if (queryString.tls) {\n queryString.ssl = queryString.tls;\n }\n\n if (queryString.tlsInsecure) {\n queryString.checkServerIdentity = false;\n queryString.sslValidate = false;\n } else {\n Object.assign(queryString, {\n checkServerIdentity: queryString.tlsAllowInvalidHostnames ? false : true,\n sslValidate: queryString.tlsAllowInvalidCertificates ? false : true\n });\n }\n\n if (queryString.tlsCAFile) {\n queryString.ssl = true;\n queryString.sslCA = queryString.tlsCAFile;\n }\n\n if (queryString.tlsCertificateKeyFile) {\n queryString.ssl = true;\n if (queryString.tlsCertificateFile) {\n queryString.sslCert = queryString.tlsCertificateFile;\n queryString.sslKey = queryString.tlsCertificateKeyFile;\n } else {\n queryString.sslKey = queryString.tlsCertificateKeyFile;\n queryString.sslCert = queryString.tlsCertificateKeyFile;\n }\n }\n\n if (queryString.tlsCertificateKeyFilePassword) {\n queryString.ssl = true;\n queryString.sslPass = queryString.tlsCertificateKeyFilePassword;\n }\n\n return queryString;\n}\n\n/**\n * Checks a query string for invalid tls options according to the URI options spec.\n *\n * @param {string} queryString The query string to check\n * @throws {MongoParseError}\n */\nfunction checkTLSOptions(queryString) {\n const queryStringKeys = Object.keys(queryString);\n if (\n queryStringKeys.indexOf('tlsInsecure') !== -1 &&\n (queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 ||\n queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1)\n ) {\n throw new MongoParseError(\n 'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.'\n );\n }\n\n const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys);\n const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys);\n\n if (tlsValue != null && sslValue != null) {\n if (tlsValue !== sslValue) {\n throw new MongoParseError('All values of `tls` and `ssl` must be the same.');\n }\n }\n}\n\n/**\n * Checks a query string to ensure all tls/ssl options are the same.\n *\n * @param {string} key The key (tls or ssl) to check\n * @param {string} queryString The query string to check\n * @throws {MongoParseError}\n * @return The value of the tls/ssl option\n */\nfunction assertTlsOptionsAreEqual(optionName, queryString, queryStringKeys) {\n const queryStringHasTLSOption = queryStringKeys.indexOf(optionName) !== -1;\n\n let optionValue;\n if (Array.isArray(queryString[optionName])) {\n optionValue = queryString[optionName][0];\n } else {\n optionValue = queryString[optionName];\n }\n\n if (queryStringHasTLSOption) {\n if (Array.isArray(queryString[optionName])) {\n const firstValue = queryString[optionName][0];\n queryString[optionName].forEach(tlsValue => {\n if (tlsValue !== firstValue) {\n throw new MongoParseError(`All values of ${optionName} must be the same.`);\n }\n });\n }\n }\n\n return optionValue;\n}\n\nconst PROTOCOL_MONGODB = 'mongodb';\nconst PROTOCOL_MONGODB_SRV = 'mongodb+srv';\nconst SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV];\n\n/**\n * Parses a MongoDB connection string\n *\n * @param {*} uri the MongoDB connection string to parse\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization\n * @param {parseCallback} callback\n */\nfunction parseConnectionString(uri, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = Object.assign({}, { caseTranslate: true }, options);\n\n // Check for bad uris before we parse\n try {\n URL.parse(uri);\n } catch (e) {\n return callback(new MongoParseError('URI malformed, cannot be parsed'));\n }\n\n const cap = uri.match(HOSTS_RX);\n if (!cap) {\n return callback(new MongoParseError('Invalid connection string'));\n }\n\n const protocol = cap[1];\n if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) {\n return callback(new MongoParseError('Invalid protocol provided'));\n }\n\n const dbAndQuery = cap[4].split('?');\n const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null;\n const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null;\n\n let parsedOptions;\n try {\n parsedOptions = parseQueryString(query, options);\n } catch (parseError) {\n return callback(parseError);\n }\n\n parsedOptions = Object.assign({}, parsedOptions, options);\n\n if (protocol === PROTOCOL_MONGODB_SRV) {\n return parseSrvConnectionString(uri, parsedOptions, callback);\n }\n\n const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null };\n if (parsedOptions.auth) {\n // maintain support for legacy options passed into `MongoClient`\n if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username;\n if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user;\n if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password;\n } else {\n if (parsedOptions.username) auth.username = parsedOptions.username;\n if (parsedOptions.user) auth.username = parsedOptions.user;\n if (parsedOptions.password) auth.password = parsedOptions.password;\n }\n\n if (cap[4].split('?')[0].indexOf('@') !== -1) {\n return callback(new MongoParseError('Unescaped slash in userinfo section'));\n }\n\n const authorityParts = cap[3].split('@');\n if (authorityParts.length > 2) {\n return callback(new MongoParseError('Unescaped at-sign in authority section'));\n }\n\n if (authorityParts[0] == null || authorityParts[0] === '') {\n return callback(new MongoParseError('No username provided in authority section'));\n }\n\n if (authorityParts.length > 1) {\n const authParts = authorityParts.shift().split(':');\n if (authParts.length > 2) {\n return callback(new MongoParseError('Unescaped colon in authority section'));\n }\n\n if (authParts[0] === '') {\n return callback(new MongoParseError('Invalid empty username provided'));\n }\n\n if (!auth.username) auth.username = qs.unescape(authParts[0]);\n if (!auth.password) auth.password = authParts[1] ? qs.unescape(authParts[1]) : null;\n }\n\n let hostParsingError = null;\n const hosts = authorityParts\n .shift()\n .split(',')\n .map(host => {\n let parsedHost = URL.parse(`mongodb://${host}`);\n if (parsedHost.path === '/:') {\n hostParsingError = new MongoParseError('Double colon in host identifier');\n return null;\n }\n\n // heuristically determine if we're working with a domain socket\n if (host.match(/\\.sock/)) {\n parsedHost.hostname = qs.unescape(host);\n parsedHost.port = null;\n }\n\n if (Number.isNaN(parsedHost.port)) {\n hostParsingError = new MongoParseError('Invalid port (non-numeric string)');\n return;\n }\n\n const result = {\n host: parsedHost.hostname,\n port: parsedHost.port ? parseInt(parsedHost.port) : 27017\n };\n\n if (result.port === 0) {\n hostParsingError = new MongoParseError('Invalid port (zero) with hostname');\n return;\n }\n\n if (result.port > 65535) {\n hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname');\n return;\n }\n\n if (result.port < 0) {\n hostParsingError = new MongoParseError('Invalid port (negative number)');\n return;\n }\n\n return result;\n })\n .filter(host => !!host);\n\n if (hostParsingError) {\n return callback(hostParsingError);\n }\n\n if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) {\n return callback(new MongoParseError('No hostname or hostnames provided in connection string'));\n }\n\n const directConnection = !!parsedOptions.directConnection;\n if (directConnection && hosts.length !== 1) {\n // If the option is set to true, the driver MUST validate that there is exactly one host given\n // in the host list in the URI, and fail client creation otherwise.\n return callback(new MongoParseError('directConnection option requires exactly one host'));\n }\n\n // NOTE: this behavior will go away in v4.0, we will always auto discover there\n if (\n parsedOptions.directConnection == null &&\n hosts.length === 1 &&\n parsedOptions.replicaSet == null\n ) {\n parsedOptions.directConnection = true;\n }\n\n const result = {\n hosts: hosts,\n auth: auth.db || auth.username ? auth : null,\n options: Object.keys(parsedOptions).length ? parsedOptions : null\n };\n\n if (result.auth && result.auth.db) {\n result.defaultDatabase = result.auth.db;\n } else {\n result.defaultDatabase = 'test';\n }\n\n // support modern `tls` variants to SSL options\n result.options = translateTLSOptions(result.options);\n\n try {\n applyAuthExpectations(result);\n } catch (authError) {\n return callback(authError);\n }\n\n callback(null, result);\n}\n\nmodule.exports = parseConnectionString;\n","'use strict';\nconst os = require('os');\nconst crypto = require('crypto');\nconst requireOptional = require('require_optional');\n\n/**\n * Generate a UUIDv4\n */\nconst uuidV4 = () => {\n const result = crypto.randomBytes(16);\n result[6] = (result[6] & 0x0f) | 0x40;\n result[8] = (result[8] & 0x3f) | 0x80;\n return result;\n};\n\n/**\n * Relays events for a given listener and emitter\n *\n * @param {EventEmitter} listener the EventEmitter to listen to the events from\n * @param {EventEmitter} emitter the EventEmitter to relay the events to\n */\nfunction relayEvents(listener, emitter, events) {\n events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event)));\n}\n\nfunction retrieveKerberos() {\n let kerberos;\n\n try {\n kerberos = requireOptional('kerberos');\n } catch (err) {\n if (err.code === 'MODULE_NOT_FOUND') {\n throw new Error('The `kerberos` module was not found. Please install it and try again.');\n }\n\n throw err;\n }\n\n return kerberos;\n}\n\n// Throw an error if an attempt to use EJSON is made when it is not installed\nconst noEJSONError = function() {\n throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.');\n};\n\n// Facilitate loading EJSON optionally\nfunction retrieveEJSON() {\n let EJSON = null;\n try {\n EJSON = requireOptional('mongodb-extjson');\n } catch (error) {} // eslint-disable-line\n if (!EJSON) {\n EJSON = {\n parse: noEJSONError,\n deserialize: noEJSONError,\n serialize: noEJSONError,\n stringify: noEJSONError,\n setBSONModule: noEJSONError,\n BSON: noEJSONError\n };\n }\n\n return EJSON;\n}\n\n/**\n * A helper function for determining `maxWireVersion` between legacy and new topology\n * instances\n *\n * @private\n * @param {(Topology|Server)} topologyOrServer\n */\nfunction maxWireVersion(topologyOrServer) {\n if (topologyOrServer) {\n if (topologyOrServer.ismaster) {\n return topologyOrServer.ismaster.maxWireVersion;\n }\n\n if (typeof topologyOrServer.lastIsMaster === 'function') {\n const lastIsMaster = topologyOrServer.lastIsMaster();\n if (lastIsMaster) {\n return lastIsMaster.maxWireVersion;\n }\n }\n\n if (topologyOrServer.description) {\n return topologyOrServer.description.maxWireVersion;\n }\n }\n\n return 0;\n}\n\n/*\n * Checks that collation is supported by server.\n *\n * @param {Server} [server] to check against\n * @param {object} [cmd] object where collation may be specified\n * @param {function} [callback] callback function\n * @return true if server does not support collation\n */\nfunction collationNotSupported(server, cmd) {\n return cmd && cmd.collation && maxWireVersion(server) < 5;\n}\n\n/**\n * Checks if a given value is a Promise\n *\n * @param {*} maybePromise\n * @return true if the provided value is a Promise\n */\nfunction isPromiseLike(maybePromise) {\n return maybePromise && typeof maybePromise.then === 'function';\n}\n\n/**\n * Applies the function `eachFn` to each item in `arr`, in parallel.\n *\n * @param {array} arr an array of items to asynchronusly iterate over\n * @param {function} eachFn A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete.\n * @param {function} callback The callback called after every item has been iterated\n */\nfunction eachAsync(arr, eachFn, callback) {\n arr = arr || [];\n\n let idx = 0;\n let awaiting = 0;\n for (idx = 0; idx < arr.length; ++idx) {\n awaiting++;\n eachFn(arr[idx], eachCallback);\n }\n\n if (awaiting === 0) {\n callback();\n return;\n }\n\n function eachCallback(err) {\n awaiting--;\n if (err) {\n callback(err);\n return;\n }\n\n if (idx === arr.length && awaiting <= 0) {\n callback();\n }\n }\n}\n\nfunction eachAsyncSeries(arr, eachFn, callback) {\n arr = arr || [];\n\n let idx = 0;\n let awaiting = arr.length;\n if (awaiting === 0) {\n callback();\n return;\n }\n\n function eachCallback(err) {\n idx++;\n awaiting--;\n if (err) {\n callback(err);\n return;\n }\n\n if (idx === arr.length && awaiting <= 0) {\n callback();\n return;\n }\n\n eachFn(arr[idx], eachCallback);\n }\n\n eachFn(arr[idx], eachCallback);\n}\n\nfunction isUnifiedTopology(topology) {\n return topology.description != null;\n}\n\nfunction arrayStrictEqual(arr, arr2) {\n if (!Array.isArray(arr) || !Array.isArray(arr2)) {\n return false;\n }\n\n return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]);\n}\n\nfunction tagsStrictEqual(tags, tags2) {\n const tagsKeys = Object.keys(tags);\n const tags2Keys = Object.keys(tags2);\n return tagsKeys.length === tags2Keys.length && tagsKeys.every(key => tags2[key] === tags[key]);\n}\n\nfunction errorStrictEqual(lhs, rhs) {\n if (lhs === rhs) {\n return true;\n }\n\n if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) {\n return false;\n }\n\n if (lhs.constructor.name !== rhs.constructor.name) {\n return false;\n }\n\n if (lhs.message !== rhs.message) {\n return false;\n }\n\n return true;\n}\n\nfunction makeStateMachine(stateTable) {\n return function stateTransition(target, newState) {\n const legalStates = stateTable[target.s.state];\n if (legalStates && legalStates.indexOf(newState) < 0) {\n throw new TypeError(\n `illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]`\n );\n }\n\n target.emit('stateChanged', target.s.state, newState);\n target.s.state = newState;\n };\n}\n\nfunction makeClientMetadata(options) {\n options = options || {};\n\n const metadata = {\n driver: {\n name: 'nodejs',\n version: require('../../package.json').version\n },\n os: {\n type: os.type(),\n name: process.platform,\n architecture: process.arch,\n version: os.release()\n },\n platform: `'Node.js ${process.version}, ${os.endianness} (${\n options.useUnifiedTopology ? 'unified' : 'legacy'\n })`\n };\n\n // support optionally provided wrapping driver info\n if (options.driverInfo) {\n if (options.driverInfo.name) {\n metadata.driver.name = `${metadata.driver.name}|${options.driverInfo.name}`;\n }\n\n if (options.driverInfo.version) {\n metadata.version = `${metadata.driver.version}|${options.driverInfo.version}`;\n }\n\n if (options.driverInfo.platform) {\n metadata.platform = `${metadata.platform}|${options.driverInfo.platform}`;\n }\n }\n\n if (options.appname) {\n // MongoDB requires the appname not exceed a byte length of 128\n const buffer = Buffer.from(options.appname);\n metadata.application = {\n name: buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname\n };\n }\n\n return metadata;\n}\n\nconst noop = () => {};\n\nmodule.exports = {\n uuidV4,\n relayEvents,\n collationNotSupported,\n retrieveEJSON,\n retrieveKerberos,\n maxWireVersion,\n isPromiseLike,\n eachAsync,\n eachAsyncSeries,\n isUnifiedTopology,\n arrayStrictEqual,\n tagsStrictEqual,\n errorStrictEqual,\n makeStateMachine,\n makeClientMetadata,\n noop\n};\n","'use strict';\n\nconst Query = require('../connection/commands').Query;\nconst Msg = require('../connection/msg').Msg;\nconst MongoError = require('../error').MongoError;\nconst getReadPreference = require('./shared').getReadPreference;\nconst isSharded = require('./shared').isSharded;\nconst databaseNamespace = require('./shared').databaseNamespace;\nconst isTransactionCommand = require('../transactions').isTransactionCommand;\nconst applySession = require('../sessions').applySession;\nconst MongoNetworkError = require('../error').MongoNetworkError;\nconst maxWireVersion = require('../utils').maxWireVersion;\n\nfunction isClientEncryptionEnabled(server) {\n const wireVersion = maxWireVersion(server);\n return wireVersion && server.autoEncrypter;\n}\n\nfunction command(server, ns, cmd, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n if (cmd == null) {\n return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`));\n }\n\n if (!isClientEncryptionEnabled(server)) {\n _command(server, ns, cmd, options, callback);\n return;\n }\n\n const wireVersion = maxWireVersion(server);\n if (typeof wireVersion !== 'number' || wireVersion < 8) {\n callback(new MongoError('Auto-encryption requires a minimum MongoDB version of 4.2'));\n return;\n }\n\n _cryptCommand(server, ns, cmd, options, callback);\n}\n\nfunction _command(server, ns, cmd, options, callback) {\n const bson = server.s.bson;\n const pool = server.s.pool;\n const readPreference = getReadPreference(cmd, options);\n const shouldUseOpMsg = supportsOpMsg(server);\n const session = options.session;\n\n let clusterTime = server.clusterTime;\n let finalCmd = Object.assign({}, cmd);\n if (hasSessionSupport(server) && session) {\n if (\n session.clusterTime &&\n session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime)\n ) {\n clusterTime = session.clusterTime;\n }\n\n const err = applySession(session, finalCmd, options);\n if (err) {\n return callback(err);\n }\n }\n\n // if we have a known cluster time, gossip it\n if (clusterTime) {\n finalCmd.$clusterTime = clusterTime;\n }\n\n if (isSharded(server) && !shouldUseOpMsg && readPreference && readPreference.mode !== 'primary') {\n finalCmd = {\n $query: finalCmd,\n $readPreference: readPreference.toJSON()\n };\n }\n\n const commandOptions = Object.assign(\n {\n command: true,\n numberToSkip: 0,\n numberToReturn: -1,\n checkKeys: false\n },\n options\n );\n\n // This value is not overridable\n commandOptions.slaveOk = readPreference.slaveOk();\n\n const cmdNs = `${databaseNamespace(ns)}.$cmd`;\n const message = shouldUseOpMsg\n ? new Msg(bson, cmdNs, finalCmd, commandOptions)\n : new Query(bson, cmdNs, finalCmd, commandOptions);\n\n const inTransaction = session && (session.inTransaction() || isTransactionCommand(finalCmd));\n const commandResponseHandler = inTransaction\n ? function(err) {\n // We need to add a TransientTransactionError errorLabel, as stated in the transaction spec.\n if (\n err &&\n err instanceof MongoNetworkError &&\n !err.hasErrorLabel('TransientTransactionError')\n ) {\n err.addErrorLabel('TransientTransactionError');\n }\n\n if (\n !cmd.commitTransaction &&\n err &&\n err instanceof MongoError &&\n err.hasErrorLabel('TransientTransactionError')\n ) {\n session.transaction.unpinServer();\n }\n\n return callback.apply(null, arguments);\n }\n : callback;\n\n try {\n pool.write(message, commandOptions, commandResponseHandler);\n } catch (err) {\n commandResponseHandler(err);\n }\n}\n\nfunction hasSessionSupport(topology) {\n if (topology == null) return false;\n if (topology.description) {\n return topology.description.maxWireVersion >= 6;\n }\n\n return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6;\n}\n\nfunction supportsOpMsg(topologyOrServer) {\n const description = topologyOrServer.ismaster\n ? topologyOrServer.ismaster\n : topologyOrServer.description;\n\n if (description == null) {\n return false;\n }\n\n return description.maxWireVersion >= 6 && description.__nodejs_mock_server__ == null;\n}\n\nfunction _cryptCommand(server, ns, cmd, options, callback) {\n const autoEncrypter = server.autoEncrypter;\n function commandResponseHandler(err, response) {\n if (err || response == null) {\n callback(err, response);\n return;\n }\n\n autoEncrypter.decrypt(response.result, options, (err, decrypted) => {\n if (err) {\n callback(err, null);\n return;\n }\n\n response.result = decrypted;\n response.message.documents = [decrypted];\n callback(null, response);\n });\n }\n\n autoEncrypter.encrypt(ns, cmd, options, (err, encrypted) => {\n if (err) {\n callback(err, null);\n return;\n }\n\n _command(server, ns, encrypted, options, commandResponseHandler);\n });\n}\n\nmodule.exports = command;\n","'use strict';\n\nconst Snappy = require('../connection/utils').retrieveSnappy();\nconst zlib = require('zlib');\n\nconst compressorIDs = {\n snappy: 1,\n zlib: 2\n};\n\nconst uncompressibleCommands = new Set([\n 'ismaster',\n 'saslStart',\n 'saslContinue',\n 'getnonce',\n 'authenticate',\n 'createUser',\n 'updateUser',\n 'copydbSaslStart',\n 'copydbgetnonce',\n 'copydb'\n]);\n\n// Facilitate compressing a message using an agreed compressor\nfunction compress(self, dataToBeCompressed, callback) {\n switch (self.options.agreedCompressor) {\n case 'snappy':\n Snappy.compress(dataToBeCompressed, callback);\n break;\n case 'zlib':\n // Determine zlibCompressionLevel\n var zlibOptions = {};\n if (self.options.zlibCompressionLevel) {\n zlibOptions.level = self.options.zlibCompressionLevel;\n }\n zlib.deflate(dataToBeCompressed, zlibOptions, callback);\n break;\n default:\n throw new Error(\n 'Attempt to compress message using unknown compressor \"' +\n self.options.agreedCompressor +\n '\".'\n );\n }\n}\n\n// Decompress a message using the given compressor\nfunction decompress(compressorID, compressedData, callback) {\n if (compressorID < 0 || compressorID > compressorIDs.length) {\n throw new Error(\n 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' +\n compressorID +\n ')'\n );\n }\n switch (compressorID) {\n case compressorIDs.snappy:\n Snappy.uncompress(compressedData, callback);\n break;\n case compressorIDs.zlib:\n zlib.inflate(compressedData, callback);\n break;\n default:\n callback(null, compressedData);\n }\n}\n\nmodule.exports = {\n compressorIDs,\n uncompressibleCommands,\n compress,\n decompress\n};\n","'use strict';\n\nconst MIN_SUPPORTED_SERVER_VERSION = '2.6';\nconst MAX_SUPPORTED_SERVER_VERSION = '4.4';\nconst MIN_SUPPORTED_WIRE_VERSION = 2;\nconst MAX_SUPPORTED_WIRE_VERSION = 9;\n\nmodule.exports = {\n MIN_SUPPORTED_SERVER_VERSION,\n MAX_SUPPORTED_SERVER_VERSION,\n MIN_SUPPORTED_WIRE_VERSION,\n MAX_SUPPORTED_WIRE_VERSION\n};\n","'use strict';\n\nconst GetMore = require('../connection/commands').GetMore;\nconst retrieveBSON = require('../connection/utils').retrieveBSON;\nconst MongoError = require('../error').MongoError;\nconst MongoNetworkError = require('../error').MongoNetworkError;\nconst BSON = retrieveBSON();\nconst Long = BSON.Long;\nconst collectionNamespace = require('./shared').collectionNamespace;\nconst maxWireVersion = require('../utils').maxWireVersion;\nconst applyCommonQueryOptions = require('./shared').applyCommonQueryOptions;\nconst command = require('./command');\n\nfunction getMore(server, ns, cursorState, batchSize, options, callback) {\n options = options || {};\n\n const wireVersion = maxWireVersion(server);\n function queryCallback(err, result) {\n if (err) return callback(err);\n const response = result.message;\n\n // If we have a timed out query or a cursor that was killed\n if (response.cursorNotFound) {\n return callback(new MongoNetworkError('cursor killed or timed out'), null);\n }\n\n if (wireVersion < 4) {\n const cursorId =\n typeof response.cursorId === 'number'\n ? Long.fromNumber(response.cursorId)\n : response.cursorId;\n\n cursorState.documents = response.documents;\n cursorState.cursorId = cursorId;\n\n callback(null, null, response.connection);\n return;\n }\n\n // We have an error detected\n if (response.documents[0].ok === 0) {\n return callback(new MongoError(response.documents[0]));\n }\n\n // Ensure we have a Long valid cursor id\n const cursorId =\n typeof response.documents[0].cursor.id === 'number'\n ? Long.fromNumber(response.documents[0].cursor.id)\n : response.documents[0].cursor.id;\n\n cursorState.documents = response.documents[0].cursor.nextBatch;\n cursorState.cursorId = cursorId;\n\n callback(null, response.documents[0], response.connection);\n }\n\n if (wireVersion < 4) {\n const bson = server.s.bson;\n const getMoreOp = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize });\n const queryOptions = applyCommonQueryOptions({}, cursorState);\n server.s.pool.write(getMoreOp, queryOptions, queryCallback);\n return;\n }\n\n const cursorId =\n cursorState.cursorId instanceof Long\n ? cursorState.cursorId\n : Long.fromNumber(cursorState.cursorId);\n\n const getMoreCmd = {\n getMore: cursorId,\n collection: collectionNamespace(ns),\n batchSize: Math.abs(batchSize)\n };\n\n if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') {\n getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS;\n }\n\n const commandOptions = Object.assign(\n {\n returnFieldSelector: null,\n documentsReturnedIn: 'nextBatch'\n },\n options\n );\n\n if (cursorState.session) {\n commandOptions.session = cursorState.session;\n }\n\n command(server, ns, getMoreCmd, commandOptions, queryCallback);\n}\n\nmodule.exports = getMore;\n","'use strict';\nconst writeCommand = require('./write_command');\n\nmodule.exports = {\n insert: function insert(server, ns, ops, options, callback) {\n writeCommand(server, 'insert', 'documents', ns, ops, options, callback);\n },\n update: function update(server, ns, ops, options, callback) {\n writeCommand(server, 'update', 'updates', ns, ops, options, callback);\n },\n remove: function remove(server, ns, ops, options, callback) {\n writeCommand(server, 'delete', 'deletes', ns, ops, options, callback);\n },\n killCursors: require('./kill_cursors'),\n getMore: require('./get_more'),\n query: require('./query'),\n command: require('./command')\n};\n","'use strict';\n\nconst KillCursor = require('../connection/commands').KillCursor;\nconst MongoError = require('../error').MongoError;\nconst MongoNetworkError = require('../error').MongoNetworkError;\nconst collectionNamespace = require('./shared').collectionNamespace;\nconst maxWireVersion = require('../utils').maxWireVersion;\nconst command = require('./command');\n\nfunction killCursors(server, ns, cursorState, callback) {\n callback = typeof callback === 'function' ? callback : () => {};\n const cursorId = cursorState.cursorId;\n\n if (maxWireVersion(server) < 4) {\n const bson = server.s.bson;\n const pool = server.s.pool;\n const killCursor = new KillCursor(bson, ns, [cursorId]);\n const options = {\n immediateRelease: true,\n noResponse: true\n };\n\n if (typeof cursorState.session === 'object') {\n options.session = cursorState.session;\n }\n\n if (pool && pool.isConnected()) {\n try {\n pool.write(killCursor, options, callback);\n } catch (err) {\n if (typeof callback === 'function') {\n callback(err, null);\n } else {\n console.warn(err);\n }\n }\n }\n\n return;\n }\n\n const killCursorCmd = {\n killCursors: collectionNamespace(ns),\n cursors: [cursorId]\n };\n\n const options = {};\n if (typeof cursorState.session === 'object') options.session = cursorState.session;\n\n command(server, ns, killCursorCmd, options, (err, result) => {\n if (err) {\n return callback(err);\n }\n\n const response = result.message;\n if (response.cursorNotFound) {\n return callback(new MongoNetworkError('cursor killed or timed out'), null);\n }\n\n if (!Array.isArray(response.documents) || response.documents.length === 0) {\n return callback(\n new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`)\n );\n }\n\n callback(null, response.documents[0]);\n });\n}\n\nmodule.exports = killCursors;\n","'use strict';\n\nconst Query = require('../connection/commands').Query;\nconst MongoError = require('../error').MongoError;\nconst getReadPreference = require('./shared').getReadPreference;\nconst collectionNamespace = require('./shared').collectionNamespace;\nconst isSharded = require('./shared').isSharded;\nconst maxWireVersion = require('../utils').maxWireVersion;\nconst applyCommonQueryOptions = require('./shared').applyCommonQueryOptions;\nconst command = require('./command');\n\nfunction query(server, ns, cmd, cursorState, options, callback) {\n options = options || {};\n if (cursorState.cursorId != null) {\n return callback();\n }\n\n if (cmd == null) {\n return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`));\n }\n\n if (maxWireVersion(server) < 4) {\n const query = prepareLegacyFindQuery(server, ns, cmd, cursorState, options);\n const queryOptions = applyCommonQueryOptions({}, cursorState);\n if (typeof query.documentsReturnedIn === 'string') {\n queryOptions.documentsReturnedIn = query.documentsReturnedIn;\n }\n\n server.s.pool.write(query, queryOptions, callback);\n return;\n }\n\n const readPreference = getReadPreference(cmd, options);\n const findCmd = prepareFindCommand(server, ns, cmd, cursorState, options);\n\n // NOTE: This actually modifies the passed in cmd, and our code _depends_ on this\n // side-effect. Change this ASAP\n cmd.virtual = false;\n\n const commandOptions = Object.assign(\n {\n documentsReturnedIn: 'firstBatch',\n numberToReturn: 1,\n slaveOk: readPreference.slaveOk()\n },\n options\n );\n\n if (cmd.readPreference) {\n commandOptions.readPreference = readPreference;\n }\n\n if (cursorState.session) {\n commandOptions.session = cursorState.session;\n }\n\n command(server, ns, findCmd, commandOptions, callback);\n}\n\nfunction prepareFindCommand(server, ns, cmd, cursorState) {\n cursorState.batchSize = cmd.batchSize || cursorState.batchSize;\n let findCmd = {\n find: collectionNamespace(ns)\n };\n\n if (cmd.query) {\n if (cmd.query['$query']) {\n findCmd.filter = cmd.query['$query'];\n } else {\n findCmd.filter = cmd.query;\n }\n }\n\n let sortValue = cmd.sort;\n if (Array.isArray(sortValue)) {\n const sortObject = {};\n\n if (sortValue.length > 0 && !Array.isArray(sortValue[0])) {\n let sortDirection = sortValue[1];\n if (sortDirection === 'asc') {\n sortDirection = 1;\n } else if (sortDirection === 'desc') {\n sortDirection = -1;\n }\n\n sortObject[sortValue[0]] = sortDirection;\n } else {\n for (let i = 0; i < sortValue.length; i++) {\n let sortDirection = sortValue[i][1];\n if (sortDirection === 'asc') {\n sortDirection = 1;\n } else if (sortDirection === 'desc') {\n sortDirection = -1;\n }\n\n sortObject[sortValue[i][0]] = sortDirection;\n }\n }\n\n sortValue = sortObject;\n }\n\n if (typeof cmd.allowDiskUse === 'boolean') {\n findCmd.allowDiskUse = cmd.allowDiskUse;\n }\n\n if (cmd.sort) findCmd.sort = sortValue;\n if (cmd.fields) findCmd.projection = cmd.fields;\n if (cmd.hint) findCmd.hint = cmd.hint;\n if (cmd.skip) findCmd.skip = cmd.skip;\n if (cmd.limit) findCmd.limit = cmd.limit;\n if (cmd.limit < 0) {\n findCmd.limit = Math.abs(cmd.limit);\n findCmd.singleBatch = true;\n }\n\n if (typeof cmd.batchSize === 'number') {\n if (cmd.batchSize < 0) {\n if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) {\n findCmd.limit = Math.abs(cmd.batchSize);\n }\n\n findCmd.singleBatch = true;\n }\n\n findCmd.batchSize = Math.abs(cmd.batchSize);\n }\n\n if (cmd.comment) findCmd.comment = cmd.comment;\n if (cmd.maxScan) findCmd.maxScan = cmd.maxScan;\n if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS;\n if (cmd.min) findCmd.min = cmd.min;\n if (cmd.max) findCmd.max = cmd.max;\n findCmd.returnKey = cmd.returnKey ? cmd.returnKey : false;\n findCmd.showRecordId = cmd.showDiskLoc ? cmd.showDiskLoc : false;\n if (cmd.snapshot) findCmd.snapshot = cmd.snapshot;\n if (cmd.tailable) findCmd.tailable = cmd.tailable;\n if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay;\n if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout;\n if (cmd.awaitData) findCmd.awaitData = cmd.awaitData;\n if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata;\n if (cmd.partial) findCmd.partial = cmd.partial;\n if (cmd.collation) findCmd.collation = cmd.collation;\n if (cmd.readConcern) findCmd.readConcern = cmd.readConcern;\n\n // If we have explain, we need to rewrite the find command\n // to wrap it in the explain command\n if (cmd.explain) {\n findCmd = {\n explain: findCmd\n };\n }\n\n return findCmd;\n}\n\nfunction prepareLegacyFindQuery(server, ns, cmd, cursorState, options) {\n options = options || {};\n const bson = server.s.bson;\n const readPreference = getReadPreference(cmd, options);\n cursorState.batchSize = cmd.batchSize || cursorState.batchSize;\n\n let numberToReturn = 0;\n if (\n cursorState.limit < 0 ||\n (cursorState.limit !== 0 && cursorState.limit < cursorState.batchSize) ||\n (cursorState.limit > 0 && cursorState.batchSize === 0)\n ) {\n numberToReturn = cursorState.limit;\n } else {\n numberToReturn = cursorState.batchSize;\n }\n\n const numberToSkip = cursorState.skip || 0;\n\n const findCmd = {};\n if (isSharded(server) && readPreference) {\n findCmd['$readPreference'] = readPreference.toJSON();\n }\n\n if (cmd.sort) findCmd['$orderby'] = cmd.sort;\n if (cmd.hint) findCmd['$hint'] = cmd.hint;\n if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot;\n if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey;\n if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan;\n if (cmd.min) findCmd['$min'] = cmd.min;\n if (cmd.max) findCmd['$max'] = cmd.max;\n if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc;\n if (cmd.comment) findCmd['$comment'] = cmd.comment;\n if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS;\n if (cmd.explain) {\n // nToReturn must be 0 (match all) or negative (match N and close cursor)\n // nToReturn > 0 will give explain results equivalent to limit(0)\n numberToReturn = -Math.abs(cmd.limit || 0);\n findCmd['$explain'] = true;\n }\n\n findCmd['$query'] = cmd.query;\n if (cmd.readConcern && cmd.readConcern.level !== 'local') {\n throw new MongoError(\n `server find command does not support a readConcern level of ${cmd.readConcern.level}`\n );\n }\n\n if (cmd.readConcern) {\n cmd = Object.assign({}, cmd);\n delete cmd['readConcern'];\n }\n\n const serializeFunctions =\n typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;\n const ignoreUndefined =\n typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false;\n\n const query = new Query(bson, ns, findCmd, {\n numberToSkip: numberToSkip,\n numberToReturn: numberToReturn,\n pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined,\n checkKeys: false,\n returnFieldSelector: cmd.fields,\n serializeFunctions: serializeFunctions,\n ignoreUndefined: ignoreUndefined\n });\n\n if (typeof cmd.tailable === 'boolean') query.tailable = cmd.tailable;\n if (typeof cmd.oplogReplay === 'boolean') query.oplogReplay = cmd.oplogReplay;\n if (typeof cmd.noCursorTimeout === 'boolean') query.noCursorTimeout = cmd.noCursorTimeout;\n if (typeof cmd.awaitData === 'boolean') query.awaitData = cmd.awaitData;\n if (typeof cmd.partial === 'boolean') query.partial = cmd.partial;\n\n query.slaveOk = readPreference.slaveOk();\n return query;\n}\n\nmodule.exports = query;\n","'use strict';\n\nconst ReadPreference = require('../topologies/read_preference');\nconst MongoError = require('../error').MongoError;\nconst ServerType = require('../sdam/common').ServerType;\nconst TopologyDescription = require('../sdam/topology_description').TopologyDescription;\n\nconst MESSAGE_HEADER_SIZE = 16;\nconst COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID\n\n// OPCODE Numbers\n// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes\nvar opcodes = {\n OP_REPLY: 1,\n OP_UPDATE: 2001,\n OP_INSERT: 2002,\n OP_QUERY: 2004,\n OP_GETMORE: 2005,\n OP_DELETE: 2006,\n OP_KILL_CURSORS: 2007,\n OP_COMPRESSED: 2012,\n OP_MSG: 2013\n};\n\nvar getReadPreference = function(cmd, options) {\n // Default to command version of the readPreference\n var readPreference = cmd.readPreference || new ReadPreference('primary');\n // If we have an option readPreference override the command one\n if (options.readPreference) {\n readPreference = options.readPreference;\n }\n\n if (typeof readPreference === 'string') {\n readPreference = new ReadPreference(readPreference);\n }\n\n if (!(readPreference instanceof ReadPreference)) {\n throw new MongoError('read preference must be a ReadPreference instance');\n }\n\n return readPreference;\n};\n\n// Parses the header of a wire protocol message\nvar parseHeader = function(message) {\n return {\n length: message.readInt32LE(0),\n requestId: message.readInt32LE(4),\n responseTo: message.readInt32LE(8),\n opCode: message.readInt32LE(12)\n };\n};\n\nfunction applyCommonQueryOptions(queryOptions, options) {\n Object.assign(queryOptions, {\n raw: typeof options.raw === 'boolean' ? options.raw : false,\n promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true,\n promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true,\n promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false,\n monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false,\n fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false\n });\n\n if (typeof options.socketTimeout === 'number') {\n queryOptions.socketTimeout = options.socketTimeout;\n }\n\n if (options.session) {\n queryOptions.session = options.session;\n }\n\n if (typeof options.documentsReturnedIn === 'string') {\n queryOptions.documentsReturnedIn = options.documentsReturnedIn;\n }\n\n return queryOptions;\n}\n\nfunction isSharded(topologyOrServer) {\n if (topologyOrServer.type === 'mongos') return true;\n if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) {\n return true;\n }\n\n // NOTE: This is incredibly inefficient, and should be removed once command construction\n // happens based on `Server` not `Topology`.\n if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) {\n const servers = Array.from(topologyOrServer.description.servers.values());\n return servers.some(server => server.type === ServerType.Mongos);\n }\n\n return false;\n}\n\nfunction databaseNamespace(ns) {\n return ns.split('.')[0];\n}\nfunction collectionNamespace(ns) {\n return ns\n .split('.')\n .slice(1)\n .join('.');\n}\n\nmodule.exports = {\n getReadPreference,\n MESSAGE_HEADER_SIZE,\n COMPRESSION_DETAILS_SIZE,\n opcodes,\n parseHeader,\n applyCommonQueryOptions,\n isSharded,\n databaseNamespace,\n collectionNamespace\n};\n","'use strict';\n\nconst MongoError = require('../error').MongoError;\nconst collectionNamespace = require('./shared').collectionNamespace;\nconst command = require('./command');\n\nfunction writeCommand(server, type, opsField, ns, ops, options, callback) {\n if (ops.length === 0) throw new MongoError(`${type} must contain at least one document`);\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n options = options || {};\n const ordered = typeof options.ordered === 'boolean' ? options.ordered : true;\n const writeConcern = options.writeConcern;\n\n const writeCommand = {};\n writeCommand[type] = collectionNamespace(ns);\n writeCommand[opsField] = ops;\n writeCommand.ordered = ordered;\n\n if (writeConcern && Object.keys(writeConcern).length > 0) {\n writeCommand.writeConcern = writeConcern;\n }\n\n if (options.collation) {\n for (let i = 0; i < writeCommand[opsField].length; i++) {\n if (!writeCommand[opsField][i].collation) {\n writeCommand[opsField][i].collation = options.collation;\n }\n }\n }\n\n if (options.bypassDocumentValidation === true) {\n writeCommand.bypassDocumentValidation = options.bypassDocumentValidation;\n }\n\n const commandOptions = Object.assign(\n {\n checkKeys: type === 'insert',\n numberToReturn: 1\n },\n options\n );\n\n command(server, ns, writeCommand, commandOptions, callback);\n}\n\nmodule.exports = writeCommand;\n","'use strict';\n\nconst Transform = require('stream').Transform;\nconst PassThrough = require('stream').PassThrough;\nconst deprecate = require('util').deprecate;\nconst handleCallback = require('./utils').handleCallback;\nconst ReadPreference = require('./core').ReadPreference;\nconst MongoError = require('./core').MongoError;\nconst CoreCursor = require('./core/cursor').CoreCursor;\nconst CursorState = require('./core/cursor').CursorState;\nconst Map = require('./core').BSON.Map;\nconst maybePromise = require('./utils').maybePromise;\nconst executeOperation = require('./operations/execute_operation');\nconst formattedOrderClause = require('./utils').formattedOrderClause;\n\nconst each = require('./operations/cursor_ops').each;\nconst CountOperation = require('./operations/count');\n\n/**\n * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB\n * allowing for iteration over the results returned from the underlying query. It supports\n * one by one document iteration, conversion to an array or can be iterated as a Node 4.X\n * or higher stream\n *\n * **CURSORS Cannot directly be instantiated**\n * @example\n * const MongoClient = require('mongodb').MongoClient;\n * const test = require('assert');\n * // Connection url\n * const url = 'mongodb://localhost:27017';\n * // Database Name\n * const dbName = 'test';\n * // Connect using MongoClient\n * MongoClient.connect(url, function(err, client) {\n * // Create a collection we want to drop later\n * const col = client.db(dbName).collection('createIndexExample1');\n * // Insert a bunch of documents\n * col.insert([{a:1, b:1}\n * , {a:2, b:2}, {a:3, b:3}\n * , {a:4, b:4}], {w:1}, function(err, result) {\n * test.equal(null, err);\n * // Show that duplicate records got dropped\n * col.find({}).toArray(function(err, items) {\n * test.equal(null, err);\n * test.equal(4, items.length);\n * client.close();\n * });\n * });\n * });\n */\n\n/**\n * Namespace provided by the code module\n * @external CoreCursor\n * @external Readable\n */\n\n// Flags allowed for cursor\nconst flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial'];\nconst fields = ['numberOfRetries', 'tailableRetryInterval'];\n\n/**\n * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly)\n * @class Cursor\n * @extends external:CoreCursor\n * @extends external:Readable\n * @property {string} sortValue Cursor query sort setting.\n * @property {boolean} timeout Is Cursor able to time out.\n * @property {ReadPreference} readPreference Get cursor ReadPreference.\n * @fires Cursor#data\n * @fires Cursor#end\n * @fires Cursor#close\n * @fires Cursor#readable\n * @return {Cursor} a Cursor instance.\n * @example\n * Cursor cursor options.\n *\n * collection.find({}).project({a:1}) // Create a projection of field a\n * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10\n * collection.find({}).batchSize(5) // Set batchSize on cursor to 5\n * collection.find({}).filter({a:1}) // Set query on the cursor\n * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries\n * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable\n * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout\n * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData\n * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial\n * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1}\n * collection.find({}).max(10) // Set the cursor max\n * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS\n * collection.find({}).min(100) // Set the cursor min\n * collection.find({}).returnKey(true) // Set the cursor returnKey\n * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference\n * collection.find({}).showRecordId(true) // Set the cursor showRecordId\n * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query\n * collection.find({}).hint('a_1') // Set the cursor hint\n *\n * All options are chainable, so one can do the following.\n *\n * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..)\n */\nclass Cursor extends CoreCursor {\n constructor(topology, ns, cmd, options) {\n super(topology, ns, cmd, options);\n if (this.operation) {\n options = this.operation.options;\n }\n\n // Tailable cursor options\n const numberOfRetries = options.numberOfRetries || 5;\n const tailableRetryInterval = options.tailableRetryInterval || 500;\n const currentNumberOfRetries = numberOfRetries;\n\n // Get the promiseLibrary\n const promiseLibrary = options.promiseLibrary || Promise;\n\n // Internal cursor state\n this.s = {\n // Tailable cursor options\n numberOfRetries: numberOfRetries,\n tailableRetryInterval: tailableRetryInterval,\n currentNumberOfRetries: currentNumberOfRetries,\n // State\n state: CursorState.INIT,\n // Promise library\n promiseLibrary,\n // explicitlyIgnoreSession\n explicitlyIgnoreSession: !!options.explicitlyIgnoreSession\n };\n\n // Optional ClientSession\n if (!options.explicitlyIgnoreSession && options.session) {\n this.cursorState.session = options.session;\n }\n\n // Translate correctly\n if (this.options.noCursorTimeout === true) {\n this.addCursorFlag('noCursorTimeout', true);\n }\n\n // Get the batchSize\n let batchSize = 1000;\n if (this.cmd.cursor && this.cmd.cursor.batchSize) {\n batchSize = this.cmd.cursor.batchSize;\n } else if (options.cursor && options.cursor.batchSize) {\n batchSize = options.cursor.batchSize;\n } else if (typeof options.batchSize === 'number') {\n batchSize = options.batchSize;\n }\n\n // Set the batchSize\n this.setCursorBatchSize(batchSize);\n }\n\n get readPreference() {\n if (this.operation) {\n return this.operation.readPreference;\n }\n\n return this.options.readPreference;\n }\n\n get sortValue() {\n return this.cmd.sort;\n }\n\n _initializeCursor(callback) {\n if (this.operation && this.operation.session != null) {\n this.cursorState.session = this.operation.session;\n } else {\n // implicitly create a session if one has not been provided\n if (\n !this.s.explicitlyIgnoreSession &&\n !this.cursorState.session &&\n this.topology.hasSessionSupport()\n ) {\n this.cursorState.session = this.topology.startSession({ owner: this });\n\n if (this.operation) {\n this.operation.session = this.cursorState.session;\n }\n }\n }\n\n super._initializeCursor(callback);\n }\n\n /**\n * Check if there is any document still available in the cursor\n * @method\n * @param {Cursor~resultCallback} [callback] The result callback.\n * @throws {MongoError}\n * @return {Promise} returns Promise if no callback passed\n */\n hasNext(callback) {\n if (this.s.state === CursorState.CLOSED || (this.isDead && this.isDead())) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n return maybePromise(this, callback, cb => {\n const cursor = this;\n if (cursor.isNotified()) {\n return cb(null, false);\n }\n\n cursor._next((err, doc) => {\n if (err) return cb(err);\n if (doc == null || cursor.s.state === Cursor.CLOSED || cursor.isDead()) {\n return cb(null, false);\n }\n\n cursor.s.state = CursorState.OPEN;\n\n // NODE-2482: merge this into the core cursor implementation\n cursor.cursorState.cursorIndex--;\n if (cursor.cursorState.limit > 0) {\n cursor.cursorState.currentLimit--;\n }\n\n cb(null, true);\n });\n });\n }\n\n /**\n * Get the next available document from the cursor, returns null if no more documents are available.\n * @method\n * @param {Cursor~resultCallback} [callback] The result callback.\n * @throws {MongoError}\n * @return {Promise} returns Promise if no callback passed\n */\n next(callback) {\n return maybePromise(this, callback, cb => {\n const cursor = this;\n if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) {\n cb(MongoError.create({ message: 'Cursor is closed', driver: true }));\n return;\n }\n\n if (cursor.s.state === CursorState.INIT && cursor.cmd.sort) {\n try {\n cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort);\n } catch (err) {\n return cb(err);\n }\n }\n\n cursor._next((err, doc) => {\n if (err) return cb(err);\n cursor.s.state = CursorState.OPEN;\n cb(null, doc);\n });\n });\n }\n\n /**\n * Set the cursor query\n * @method\n * @param {object} filter The filter object used for the cursor.\n * @return {Cursor}\n */\n filter(filter) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n this.cmd.query = filter;\n return this;\n }\n\n /**\n * Set the cursor maxScan\n * @method\n * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query\n * @deprecated as of MongoDB 4.0\n * @return {Cursor}\n */\n maxScan(maxScan) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n this.cmd.maxScan = maxScan;\n return this;\n }\n\n /**\n * Set the cursor hint\n * @method\n * @param {object} hint If specified, then the query system will only consider plans using the hinted index.\n * @return {Cursor}\n */\n hint(hint) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n this.cmd.hint = hint;\n return this;\n }\n\n /**\n * Set the cursor min\n * @method\n * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order.\n * @return {Cursor}\n */\n min(min) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n this.cmd.min = min;\n return this;\n }\n\n /**\n * Set the cursor max\n * @method\n * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order.\n * @return {Cursor}\n */\n max(max) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n this.cmd.max = max;\n return this;\n }\n\n /**\n * Set the cursor returnKey. If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields.\n * @method\n * @param {bool} returnKey the returnKey value.\n * @return {Cursor}\n */\n returnKey(value) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n this.cmd.returnKey = value;\n return this;\n }\n\n /**\n * Set the cursor showRecordId\n * @method\n * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find.\n * @return {Cursor}\n */\n showRecordId(value) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n this.cmd.showDiskLoc = value;\n return this;\n }\n\n /**\n * Set the cursor snapshot\n * @method\n * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document.\n * @deprecated as of MongoDB 4.0\n * @return {Cursor}\n */\n snapshot(value) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n this.cmd.snapshot = value;\n return this;\n }\n\n /**\n * Set a node.js specific cursor option\n * @method\n * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval'].\n * @param {object} value The field value.\n * @throws {MongoError}\n * @return {Cursor}\n */\n setCursorOption(field, value) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n if (fields.indexOf(field) === -1) {\n throw MongoError.create({\n message: `option ${field} is not a supported option ${fields}`,\n driver: true\n });\n }\n\n this.s[field] = value;\n if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value;\n return this;\n }\n\n /**\n * Add a cursor flag to the cursor\n * @method\n * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial'].\n * @param {boolean} value The flag boolean value.\n * @throws {MongoError}\n * @return {Cursor}\n */\n addCursorFlag(flag, value) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n if (flags.indexOf(flag) === -1) {\n throw MongoError.create({\n message: `flag ${flag} is not a supported flag ${flags}`,\n driver: true\n });\n }\n\n if (typeof value !== 'boolean') {\n throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true });\n }\n\n this.cmd[flag] = value;\n return this;\n }\n\n /**\n * Add a query modifier to the cursor query\n * @method\n * @param {string} name The query modifier (must start with $, such as $orderby etc)\n * @param {string|boolean|number} value The modifier value.\n * @throws {MongoError}\n * @return {Cursor}\n */\n addQueryModifier(name, value) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n if (name[0] !== '$') {\n throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true });\n }\n\n // Strip of the $\n const field = name.substr(1);\n // Set on the command\n this.cmd[field] = value;\n // Deal with the special case for sort\n if (field === 'orderby') this.cmd.sort = this.cmd[field];\n return this;\n }\n\n /**\n * Add a comment to the cursor query allowing for tracking the comment in the log.\n * @method\n * @param {string} value The comment attached to this query.\n * @throws {MongoError}\n * @return {Cursor}\n */\n comment(value) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n this.cmd.comment = value;\n return this;\n }\n\n /**\n * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)\n * @method\n * @param {number} value Number of milliseconds to wait before aborting the tailed query.\n * @throws {MongoError}\n * @return {Cursor}\n */\n maxAwaitTimeMS(value) {\n if (typeof value !== 'number') {\n throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true });\n }\n\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n this.cmd.maxAwaitTimeMS = value;\n return this;\n }\n\n /**\n * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)\n * @method\n * @param {number} value Number of milliseconds to wait before aborting the query.\n * @throws {MongoError}\n * @return {Cursor}\n */\n maxTimeMS(value) {\n if (typeof value !== 'number') {\n throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true });\n }\n\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n this.cmd.maxTimeMS = value;\n return this;\n }\n\n /**\n * Sets a field projection for the query.\n * @method\n * @param {object} value The field projection object.\n * @throws {MongoError}\n * @return {Cursor}\n */\n project(value) {\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n this.cmd.fields = value;\n return this;\n }\n\n /**\n * Sets the sort order of the cursor query.\n * @method\n * @param {(string|array|object)} keyOrList The key or keys set for the sort.\n * @param {number} [direction] The direction of the sorting (1 or -1).\n * @throws {MongoError}\n * @return {Cursor}\n */\n sort(keyOrList, direction) {\n if (this.options.tailable) {\n throw MongoError.create({ message: \"Tailable cursor doesn't support sorting\", driver: true });\n }\n\n if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n let order = keyOrList;\n\n // We have an array of arrays, we need to preserve the order of the sort\n // so we will us a Map\n if (Array.isArray(order) && Array.isArray(order[0])) {\n order = new Map(\n order.map(x => {\n const value = [x[0], null];\n if (x[1] === 'asc') {\n value[1] = 1;\n } else if (x[1] === 'desc') {\n value[1] = -1;\n } else if (x[1] === 1 || x[1] === -1 || x[1].$meta) {\n value[1] = x[1];\n } else {\n throw new MongoError(\n \"Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]\"\n );\n }\n\n return value;\n })\n );\n }\n\n if (direction != null) {\n order = [[keyOrList, direction]];\n }\n\n this.cmd.sort = order;\n return this;\n }\n\n /**\n * Set the batch size for the cursor.\n * @method\n * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}.\n * @throws {MongoError}\n * @return {Cursor}\n */\n batchSize(value) {\n if (this.options.tailable) {\n throw MongoError.create({\n message: \"Tailable cursor doesn't support batchSize\",\n driver: true\n });\n }\n\n if (this.s.state === CursorState.CLOSED || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n if (typeof value !== 'number') {\n throw MongoError.create({ message: 'batchSize requires an integer', driver: true });\n }\n\n this.cmd.batchSize = value;\n this.setCursorBatchSize(value);\n return this;\n }\n\n /**\n * Set the collation options for the cursor.\n * @method\n * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @throws {MongoError}\n * @return {Cursor}\n */\n collation(value) {\n this.cmd.collation = value;\n return this;\n }\n\n /**\n * Set the limit for the cursor.\n * @method\n * @param {number} value The limit for the cursor query.\n * @throws {MongoError}\n * @return {Cursor}\n */\n limit(value) {\n if (this.options.tailable) {\n throw MongoError.create({ message: \"Tailable cursor doesn't support limit\", driver: true });\n }\n\n if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n if (typeof value !== 'number') {\n throw MongoError.create({ message: 'limit requires an integer', driver: true });\n }\n\n this.cmd.limit = value;\n this.setCursorLimit(value);\n return this;\n }\n\n /**\n * Set the skip for the cursor.\n * @method\n * @param {number} value The skip for the cursor query.\n * @throws {MongoError}\n * @return {Cursor}\n */\n skip(value) {\n if (this.options.tailable) {\n throw MongoError.create({ message: \"Tailable cursor doesn't support skip\", driver: true });\n }\n\n if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) {\n throw MongoError.create({ message: 'Cursor is closed', driver: true });\n }\n\n if (typeof value !== 'number') {\n throw MongoError.create({ message: 'skip requires an integer', driver: true });\n }\n\n this.cmd.skip = value;\n this.setCursorSkip(value);\n return this;\n }\n\n /**\n * The callback format for results\n * @callback Cursor~resultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {(object|null|boolean)} result The result object if the command was executed successfully.\n */\n\n /**\n * Clone the cursor\n * @function external:CoreCursor#clone\n * @return {Cursor}\n */\n\n /**\n * Resets the cursor\n * @function external:CoreCursor#rewind\n * @return {null}\n */\n\n /**\n * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,\n * not all of the elements will be iterated if this cursor had been previously accessed.\n * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike\n * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements\n * at any given time if batch size is specified. Otherwise, the caller is responsible\n * for making sure that the entire result can fit the memory.\n * @method\n * @deprecated\n * @param {Cursor~resultCallback} callback The result callback.\n * @throws {MongoError}\n * @return {null}\n */\n each(callback) {\n // Rewind cursor state\n this.rewind();\n // Set current cursor to INIT\n this.s.state = CursorState.INIT;\n // Run the query\n each(this, callback);\n }\n\n /**\n * The callback format for the forEach iterator method\n * @callback Cursor~iteratorCallback\n * @param {Object} doc An emitted document for the iterator\n */\n\n /**\n * The callback error format for the forEach iterator method\n * @callback Cursor~endCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n */\n\n /**\n * Iterates over all the documents for this cursor using the iterator, callback pattern.\n * @method\n * @param {Cursor~iteratorCallback} iterator The iteration callback.\n * @param {Cursor~endCallback} callback The end callback.\n * @throws {MongoError}\n * @return {Promise} if no callback supplied\n */\n forEach(iterator, callback) {\n // Rewind cursor state\n this.rewind();\n\n // Set current cursor to INIT\n this.s.state = CursorState.INIT;\n\n if (typeof callback === 'function') {\n each(this, (err, doc) => {\n if (err) {\n callback(err);\n return false;\n }\n if (doc != null) {\n iterator(doc);\n return true;\n }\n if (doc == null && callback) {\n const internalCallback = callback;\n callback = null;\n internalCallback(null);\n return false;\n }\n });\n } else {\n return new this.s.promiseLibrary((fulfill, reject) => {\n each(this, (err, doc) => {\n if (err) {\n reject(err);\n return false;\n } else if (doc == null) {\n fulfill(null);\n return false;\n } else {\n iterator(doc);\n return true;\n }\n });\n });\n }\n }\n\n /**\n * Set the ReadPreference for the cursor.\n * @method\n * @param {(string|ReadPreference)} readPreference The new read preference for the cursor.\n * @throws {MongoError}\n * @return {Cursor}\n */\n setReadPreference(readPreference) {\n if (this.s.state !== CursorState.INIT) {\n throw MongoError.create({\n message: 'cannot change cursor readPreference after cursor has been accessed',\n driver: true\n });\n }\n\n if (readPreference instanceof ReadPreference) {\n this.options.readPreference = readPreference;\n } else if (typeof readPreference === 'string') {\n this.options.readPreference = new ReadPreference(readPreference);\n } else {\n throw new TypeError('Invalid read preference: ' + readPreference);\n }\n\n return this;\n }\n\n /**\n * The callback format for results\n * @callback Cursor~toArrayResultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {object[]} documents All the documents the satisfy the cursor.\n */\n\n /**\n * Returns an array of documents. The caller is responsible for making sure that there\n * is enough memory to store the results. Note that the array only contains partial\n * results when this cursor had been previously accessed. In that case,\n * cursor.rewind() can be used to reset the cursor.\n * @method\n * @param {Cursor~toArrayResultCallback} [callback] The result callback.\n * @throws {MongoError}\n * @return {Promise} returns Promise if no callback passed\n */\n toArray(callback) {\n if (this.options.tailable) {\n throw MongoError.create({\n message: 'Tailable cursor cannot be converted to array',\n driver: true\n });\n }\n\n return maybePromise(this, callback, cb => {\n const cursor = this;\n const items = [];\n\n // Reset cursor\n cursor.rewind();\n cursor.s.state = CursorState.INIT;\n\n // Fetch all the documents\n const fetchDocs = () => {\n cursor._next((err, doc) => {\n if (err) {\n return handleCallback(cb, err);\n }\n\n if (doc == null) {\n return cursor.close({ skipKillCursors: true }, () => handleCallback(cb, null, items));\n }\n\n // Add doc to items\n items.push(doc);\n\n // Get all buffered objects\n if (cursor.bufferedCount() > 0) {\n let docs = cursor.readBufferedDocuments(cursor.bufferedCount());\n Array.prototype.push.apply(items, docs);\n }\n\n // Attempt a fetch\n fetchDocs();\n });\n };\n\n fetchDocs();\n });\n }\n\n /**\n * The callback format for results\n * @callback Cursor~countResultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {number} count The count of documents.\n */\n\n /**\n * Get the count of documents for this cursor\n * @method\n * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options.\n * @param {object} [options] Optional settings.\n * @param {number} [options.skip] The number of documents to skip.\n * @param {number} [options.limit] The maximum amounts to count before aborting.\n * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.\n * @param {string} [options.hint] An index name hint for the query.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {Cursor~countResultCallback} [callback] The result callback.\n * @return {Promise} returns Promise if no callback passed\n */\n count(applySkipLimit, opts, callback) {\n if (this.cmd.query == null)\n throw MongoError.create({\n message: 'count can only be used with find command',\n driver: true\n });\n if (typeof opts === 'function') (callback = opts), (opts = {});\n opts = opts || {};\n\n if (typeof applySkipLimit === 'function') {\n callback = applySkipLimit;\n applySkipLimit = true;\n }\n\n if (this.cursorState.session) {\n opts = Object.assign({}, opts, { session: this.cursorState.session });\n }\n\n const countOperation = new CountOperation(this, applySkipLimit, opts);\n\n return executeOperation(this.topology, countOperation, callback);\n }\n\n /**\n * Close the cursor, sending a KillCursor command and emitting close.\n * @method\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor.\n * @param {Cursor~resultCallback} [callback] The result callback.\n * @return {Promise} returns Promise if no callback passed\n */\n close(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = Object.assign({}, { skipKillCursors: false }, options);\n\n return maybePromise(this, callback, cb => {\n this.s.state = CursorState.CLOSED;\n if (!options.skipKillCursors) {\n // Kill the cursor\n this.kill();\n }\n\n this._endSession(() => {\n this.emit('close');\n cb(null, this);\n });\n });\n }\n\n /**\n * Map all documents using the provided function\n * @method\n * @param {function} [transform] The mapping transformation method.\n * @return {Cursor}\n */\n map(transform) {\n if (this.cursorState.transforms && this.cursorState.transforms.doc) {\n const oldTransform = this.cursorState.transforms.doc;\n this.cursorState.transforms.doc = doc => {\n return transform(oldTransform(doc));\n };\n } else {\n this.cursorState.transforms = { doc: transform };\n }\n\n return this;\n }\n\n /**\n * Is the cursor closed\n * @method\n * @return {boolean}\n */\n isClosed() {\n return this.isDead();\n }\n\n destroy(err) {\n if (err) this.emit('error', err);\n this.pause();\n this.close();\n }\n\n /**\n * Return a modified Readable stream including a possible transform method.\n * @method\n * @param {object} [options] Optional settings.\n * @param {function} [options.transform] A transformation method applied to each document emitted by the stream.\n * @return {Cursor}\n * TODO: replace this method with transformStream in next major release\n */\n stream(options) {\n this.cursorState.streamOptions = options || {};\n return this;\n }\n\n /**\n * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied,\n * returns a stream of unmodified docs.\n * @method\n * @param {object} [options] Optional settings.\n * @param {function} [options.transform] A transformation method applied to each document emitted by the stream.\n * @return {stream}\n */\n transformStream(options) {\n const streamOptions = options || {};\n if (typeof streamOptions.transform === 'function') {\n const stream = new Transform({\n objectMode: true,\n transform: function(chunk, encoding, callback) {\n this.push(streamOptions.transform(chunk));\n callback();\n }\n });\n\n return this.pipe(stream);\n }\n\n return this.pipe(new PassThrough({ objectMode: true }));\n }\n\n /**\n * Execute the explain for the cursor\n * @method\n * @param {Cursor~resultCallback} [callback] The result callback.\n * @return {Promise} returns Promise if no callback passed\n */\n explain(callback) {\n // NOTE: the next line includes a special case for operations which do not\n // subclass `CommandOperationV2`. To be removed asap.\n if (this.operation && this.operation.cmd == null) {\n this.operation.options.explain = true;\n this.operation.fullResponse = false;\n return executeOperation(this.topology, this.operation, callback);\n }\n\n this.cmd.explain = true;\n\n // Do we have a readConcern\n if (this.cmd.readConcern) {\n delete this.cmd['readConcern'];\n }\n return maybePromise(this, callback, cb => {\n CoreCursor.prototype._next.apply(this, [cb]);\n });\n }\n\n /**\n * Return the cursor logger\n * @method\n * @return {Logger} return the cursor logger\n * @ignore\n */\n getLogger() {\n return this.logger;\n }\n}\n\n/**\n * Cursor stream data event, fired for each document in the cursor.\n *\n * @event Cursor#data\n * @type {object}\n */\n\n/**\n * Cursor stream end event\n *\n * @event Cursor#end\n * @type {null}\n */\n\n/**\n * Cursor stream close event\n *\n * @event Cursor#close\n * @type {null}\n */\n\n/**\n * Cursor stream readable event\n *\n * @event Cursor#readable\n * @type {null}\n */\n\n// aliases\nCursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS;\n\n// deprecated methods\ndeprecate(Cursor.prototype.each, 'Cursor.each is deprecated. Use Cursor.forEach instead.');\ndeprecate(\n Cursor.prototype.maxScan,\n 'Cursor.maxScan is deprecated, and will be removed in a later version'\n);\n\ndeprecate(\n Cursor.prototype.snapshot,\n 'Cursor Snapshot is deprecated, and will be removed in a later version'\n);\n\n/**\n * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.\n * @function external:Readable#read\n * @param {number} size Optional argument to specify how much data to read.\n * @return {(String | Buffer | null)}\n */\n\n/**\n * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.\n * @function external:Readable#setEncoding\n * @param {string} encoding The encoding to use.\n * @return {null}\n */\n\n/**\n * This method will cause the readable stream to resume emitting data events.\n * @function external:Readable#resume\n * @return {null}\n */\n\n/**\n * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.\n * @function external:Readable#pause\n * @return {null}\n */\n\n/**\n * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.\n * @function external:Readable#pipe\n * @param {Writable} destination The destination for writing data\n * @param {object} [options] Pipe options\n * @return {null}\n */\n\n/**\n * This method will remove the hooks set up for a previous pipe() call.\n * @function external:Readable#unpipe\n * @param {Writable} [destination] The destination for writing data\n * @return {null}\n */\n\n/**\n * This is useful in certain cases where a stream is being consumed by a parser, which needs to \"un-consume\" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.\n * @function external:Readable#unshift\n * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue.\n * @return {null}\n */\n\n/**\n * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See \"Compatibility\" below for more information.)\n * @function external:Readable#wrap\n * @param {Stream} stream An \"old style\" readable stream.\n * @return {null}\n */\n\nmodule.exports = Cursor;\n","'use strict';\n\nconst EventEmitter = require('events').EventEmitter;\nconst inherits = require('util').inherits;\nconst getSingleProperty = require('./utils').getSingleProperty;\nconst CommandCursor = require('./command_cursor');\nconst handleCallback = require('./utils').handleCallback;\nconst filterOptions = require('./utils').filterOptions;\nconst toError = require('./utils').toError;\nconst ReadPreference = require('./core').ReadPreference;\nconst MongoError = require('./core').MongoError;\nconst ObjectID = require('./core').ObjectID;\nconst Logger = require('./core').Logger;\nconst Collection = require('./collection');\nconst mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern;\nconst executeLegacyOperation = require('./utils').executeLegacyOperation;\nconst ChangeStream = require('./change_stream');\nconst deprecate = require('util').deprecate;\nconst deprecateOptions = require('./utils').deprecateOptions;\nconst MongoDBNamespace = require('./utils').MongoDBNamespace;\nconst CONSTANTS = require('./constants');\nconst WriteConcern = require('./write_concern');\nconst ReadConcern = require('./read_concern');\nconst AggregationCursor = require('./aggregation_cursor');\n\n// Operations\nconst createListener = require('./operations/db_ops').createListener;\nconst ensureIndex = require('./operations/db_ops').ensureIndex;\nconst evaluate = require('./operations/db_ops').evaluate;\nconst profilingInfo = require('./operations/db_ops').profilingInfo;\nconst validateDatabaseName = require('./operations/db_ops').validateDatabaseName;\n\nconst AggregateOperation = require('./operations/aggregate');\nconst AddUserOperation = require('./operations/add_user');\nconst CollectionsOperation = require('./operations/collections');\nconst CommandOperation = require('./operations/command');\nconst RunCommandOperation = require('./operations/run_command');\nconst CreateCollectionOperation = require('./operations/create_collection');\nconst CreateIndexesOperation = require('./operations/create_indexes');\nconst DropCollectionOperation = require('./operations/drop').DropCollectionOperation;\nconst DropDatabaseOperation = require('./operations/drop').DropDatabaseOperation;\nconst ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command');\nconst IndexInformationOperation = require('./operations/index_information');\nconst ListCollectionsOperation = require('./operations/list_collections');\nconst ProfilingLevelOperation = require('./operations/profiling_level');\nconst RemoveUserOperation = require('./operations/remove_user');\nconst RenameOperation = require('./operations/rename');\nconst SetProfilingLevelOperation = require('./operations/set_profiling_level');\n\nconst executeOperation = require('./operations/execute_operation');\n\n/**\n * @fileOverview The **Db** class is a class that represents a MongoDB Database.\n *\n * @example\n * const MongoClient = require('mongodb').MongoClient;\n * // Connection url\n * const url = 'mongodb://localhost:27017';\n * // Database Name\n * const dbName = 'test';\n * // Connect using MongoClient\n * MongoClient.connect(url, function(err, client) {\n * // Select the database by name\n * const testDb = client.db(dbName);\n * client.close();\n * });\n */\n\n// Allowed parameters\nconst legalOptionNames = [\n 'w',\n 'wtimeout',\n 'fsync',\n 'j',\n 'readPreference',\n 'readPreferenceTags',\n 'native_parser',\n 'forceServerObjectId',\n 'pkFactory',\n 'serializeFunctions',\n 'raw',\n 'bufferMaxEntries',\n 'authSource',\n 'ignoreUndefined',\n 'promoteLongs',\n 'promiseLibrary',\n 'readConcern',\n 'retryMiliSeconds',\n 'numberOfRetries',\n 'parentDb',\n 'noListener',\n 'loggerLevel',\n 'logger',\n 'promoteBuffers',\n 'promoteLongs',\n 'promoteValues',\n 'compression',\n 'retryWrites'\n];\n\n/**\n * Creates a new Db instance\n * @class\n * @param {string} databaseName The name of the database this instance represents.\n * @param {(Server|ReplSet|Mongos)} topology The server topology for the database.\n * @param {object} [options] Optional settings.\n * @param {string} [options.authSource] If the database authentication is dependent on another databaseName.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.\n * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.\n * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.\n * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.\n * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.\n * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys.\n * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible\n * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)\n * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)\n * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology.\n * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database\n * @property {string} databaseName The name of the database this instance represents.\n * @property {object} options The options associated with the db instance.\n * @property {boolean} native_parser The current value of the parameter native_parser.\n * @property {boolean} slaveOk The current slaveOk value for the db instance.\n * @property {object} writeConcern The current write concern values.\n * @property {object} topology Access the topology object (single server, replicaset or mongos).\n * @fires Db#close\n * @fires Db#reconnect\n * @fires Db#error\n * @fires Db#timeout\n * @fires Db#parseError\n * @fires Db#fullsetup\n * @return {Db} a Db instance.\n */\nfunction Db(databaseName, topology, options) {\n options = options || {};\n if (!(this instanceof Db)) return new Db(databaseName, topology, options);\n EventEmitter.call(this);\n\n // Get the promiseLibrary\n const promiseLibrary = options.promiseLibrary || Promise;\n\n // Filter the options\n options = filterOptions(options, legalOptionNames);\n\n // Ensure we put the promiseLib in the options\n options.promiseLibrary = promiseLibrary;\n\n // Internal state of the db object\n this.s = {\n // DbCache\n dbCache: {},\n // Children db's\n children: [],\n // Topology\n topology: topology,\n // Options\n options: options,\n // Logger instance\n logger: Logger('Db', options),\n // Get the bson parser\n bson: topology ? topology.bson : null,\n // Unpack read preference\n readPreference: ReadPreference.fromOptions(options),\n // Set buffermaxEntries\n bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1,\n // Parent db (if chained)\n parentDb: options.parentDb || null,\n // Set up the primary key factory or fallback to ObjectID\n pkFactory: options.pkFactory || ObjectID,\n // Get native parser\n nativeParser: options.nativeParser || options.native_parser,\n // Promise library\n promiseLibrary: promiseLibrary,\n // No listener\n noListener: typeof options.noListener === 'boolean' ? options.noListener : false,\n // ReadConcern\n readConcern: ReadConcern.fromOptions(options),\n writeConcern: WriteConcern.fromOptions(options),\n // Namespace\n namespace: new MongoDBNamespace(databaseName)\n };\n\n // Ensure we have a valid db name\n validateDatabaseName(databaseName);\n\n // Add a read Only property\n getSingleProperty(this, 'serverConfig', this.s.topology);\n getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries);\n getSingleProperty(this, 'databaseName', this.s.namespace.db);\n\n // This is a child db, do not register any listeners\n if (options.parentDb) return;\n if (this.s.noListener) return;\n\n // Add listeners\n topology.on('error', createListener(this, 'error', this));\n topology.on('timeout', createListener(this, 'timeout', this));\n topology.on('close', createListener(this, 'close', this));\n topology.on('parseError', createListener(this, 'parseError', this));\n topology.once('open', createListener(this, 'open', this));\n topology.once('fullsetup', createListener(this, 'fullsetup', this));\n topology.once('all', createListener(this, 'all', this));\n topology.on('reconnect', createListener(this, 'reconnect', this));\n}\n\ninherits(Db, EventEmitter);\n\n// Topology\nObject.defineProperty(Db.prototype, 'topology', {\n enumerable: true,\n get: function() {\n return this.s.topology;\n }\n});\n\n// Options\nObject.defineProperty(Db.prototype, 'options', {\n enumerable: true,\n get: function() {\n return this.s.options;\n }\n});\n\n// slaveOk specified\nObject.defineProperty(Db.prototype, 'slaveOk', {\n enumerable: true,\n get: function() {\n if (\n this.s.options.readPreference != null &&\n (this.s.options.readPreference !== 'primary' ||\n this.s.options.readPreference.mode !== 'primary')\n ) {\n return true;\n }\n return false;\n }\n});\n\nObject.defineProperty(Db.prototype, 'readConcern', {\n enumerable: true,\n get: function() {\n return this.s.readConcern;\n }\n});\n\nObject.defineProperty(Db.prototype, 'readPreference', {\n enumerable: true,\n get: function() {\n if (this.s.readPreference == null) {\n // TODO: check client\n return ReadPreference.primary;\n }\n\n return this.s.readPreference;\n }\n});\n\n// get the write Concern\nObject.defineProperty(Db.prototype, 'writeConcern', {\n enumerable: true,\n get: function() {\n return this.s.writeConcern;\n }\n});\n\nObject.defineProperty(Db.prototype, 'namespace', {\n enumerable: true,\n get: function() {\n return this.s.namespace.toString();\n }\n});\n\n/**\n * Execute a command\n * @method\n * @param {object} command The command hash\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.command = function(command, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = Object.assign({}, options);\n\n const commandOperation = new RunCommandOperation(this, command, options);\n\n return executeOperation(this.s.topology, commandOperation, callback);\n};\n\n/**\n * Execute an aggregation framework pipeline against the database, needs MongoDB >= 3.6\n * @method\n * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution.\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.\n * @param {number} [options.cursor.batchSize=1000] Deprecated. Use `options.batchSize`\n * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >).\n * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).\n * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.\n * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query.\n * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.\n * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.\n * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.\n * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.\n * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {string} [options.comment] Add a comment to an aggregation command\n * @param {string|object} [options.hint] Add an index selection hint to an aggregation command\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Database~aggregationCallback} callback The command result callback\n * @return {(null|AggregationCursor)}\n */\nDb.prototype.aggregate = function(pipeline, options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n // If we have no options or callback we are doing\n // a cursor based aggregation\n if (options == null && callback == null) {\n options = {};\n }\n\n const cursor = new AggregationCursor(\n this.s.topology,\n new AggregateOperation(this, pipeline, options),\n options\n );\n\n // TODO: remove this when NODE-2074 is resolved\n if (typeof callback === 'function') {\n callback(null, cursor);\n return;\n }\n\n return cursor;\n};\n\n/**\n * Return the Admin db instance\n * @method\n * @return {Admin} return the new Admin db instance\n */\nDb.prototype.admin = function() {\n const Admin = require('./admin');\n\n return new Admin(this, this.s.topology, this.s.promiseLibrary);\n};\n\n/**\n * The callback format for the collection method, must be used if strict is specified\n * @callback Db~collectionResultCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {Collection} collection The collection instance.\n */\n\n/**\n * The callback format for an aggregation call\n * @callback Database~aggregationCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully.\n */\n\nconst collectionKeys = [\n 'pkFactory',\n 'readPreference',\n 'serializeFunctions',\n 'strict',\n 'readConcern',\n 'ignoreUndefined',\n 'promoteValues',\n 'promoteBuffers',\n 'promoteLongs'\n];\n\n/**\n * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you\n * can use it without a callback in the following way: `const collection = db.collection('mycollection');`\n *\n * @method\n * @param {string} name the collection name we wish to access.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.\n * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.strict=false] Returns an error if the collection does not exist\n * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)\n * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)\n * @param {Db~collectionResultCallback} [callback] The collection result callback\n * @return {Collection} return the new Collection instance if not in strict mode\n */\nDb.prototype.collection = function(name, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n options = Object.assign({}, options);\n\n // Set the promise library\n options.promiseLibrary = this.s.promiseLibrary;\n\n // If we have not set a collection level readConcern set the db level one\n options.readConcern = options.readConcern\n ? new ReadConcern(options.readConcern.level)\n : this.readConcern;\n\n // Do we have ignoreUndefined set\n if (this.s.options.ignoreUndefined) {\n options.ignoreUndefined = this.s.options.ignoreUndefined;\n }\n\n // Merge in all needed options and ensure correct writeConcern merging from db level\n options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true);\n\n // Execute\n if (options == null || !options.strict) {\n try {\n const collection = new Collection(\n this,\n this.s.topology,\n this.databaseName,\n name,\n this.s.pkFactory,\n options\n );\n if (callback) callback(null, collection);\n return collection;\n } catch (err) {\n if (err instanceof MongoError && callback) return callback(err);\n throw err;\n }\n }\n\n // Strict mode\n if (typeof callback !== 'function') {\n throw toError(`A callback is required in strict mode. While getting collection ${name}`);\n }\n\n // Did the user destroy the topology\n if (this.serverConfig && this.serverConfig.isDestroyed()) {\n return callback(new MongoError('topology was destroyed'));\n }\n\n const listCollectionOptions = Object.assign({}, options, { nameOnly: true });\n\n // Strict mode\n this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => {\n if (err != null) return handleCallback(callback, err, null);\n if (collections.length === 0)\n return handleCallback(\n callback,\n toError(`Collection ${name} does not exist. Currently in strict mode.`),\n null\n );\n\n try {\n return handleCallback(\n callback,\n null,\n new Collection(this, this.s.topology, this.databaseName, name, this.s.pkFactory, options)\n );\n } catch (err) {\n return handleCallback(callback, err, null);\n }\n });\n};\n\n/**\n * Create a new collection on a server with the specified options. Use this to create capped collections.\n * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/\n *\n * @method\n * @param {string} name the collection name we wish to access.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.\n * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.\n * @param {boolean} [options.strict=false] DEPRECATED: Returns an error if the collection does not exist\n * @param {boolean} [options.capped=false] Create a capped collection.\n * @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0\n * @param {number} [options.size] The size of the capped collection in bytes.\n * @param {number} [options.max] The maximum number of documents in the capped collection.\n * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag.\n * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher.\n * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher.\n * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher.\n * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher.\n * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher.\n * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher.\n * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher.\n * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~collectionResultCallback} [callback] The results callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.createCollection = deprecateOptions(\n {\n name: 'Db.createCollection',\n deprecatedOptions: ['autoIndexId', 'strict'],\n optionsIndex: 1\n },\n function(name, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary;\n options.readConcern = options.readConcern\n ? new ReadConcern(options.readConcern.level)\n : this.readConcern;\n const createCollectionOperation = new CreateCollectionOperation(this, name, options);\n\n return executeOperation(this.s.topology, createCollectionOperation, callback);\n }\n);\n\n/**\n * Get all the db statistics.\n *\n * @method\n * @param {object} [options] Optional settings.\n * @param {number} [options.scale] Divide the returned sizes by scale value.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The collection result callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.stats = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n // Build command object\n const commandObject = { dbStats: true };\n // Check if we have the scale value\n if (options['scale'] != null) commandObject['scale'] = options['scale'];\n\n // If we have a readPreference set\n if (options.readPreference == null && this.s.readPreference) {\n options.readPreference = this.s.readPreference;\n }\n\n const statsOperation = new CommandOperation(this, options, null, commandObject);\n\n // Execute the command\n return executeOperation(this.s.topology, statsOperation, callback);\n};\n\n/**\n * Get the list of all collection information for the specified db.\n *\n * @method\n * @param {object} [filter={}] Query to filter collections by\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info\n * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @return {CommandCursor}\n */\nDb.prototype.listCollections = function(filter, options) {\n filter = filter || {};\n options = options || {};\n\n return new CommandCursor(\n this.s.topology,\n new ListCollectionsOperation(this, filter, options),\n options\n );\n};\n\n/**\n * Evaluate JavaScript on the server\n *\n * @method\n * @param {Code} code JavaScript to execute on server.\n * @param {(object|array)} parameters The parameters for the call.\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaluation of the javascript.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The results callback\n * @deprecated Eval is deprecated on MongoDB 3.2 and forward\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.eval = deprecate(function(code, parameters, options, callback) {\n const args = Array.prototype.slice.call(arguments, 1);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n parameters = args.length ? args.shift() : parameters;\n options = args.length ? args.shift() || {} : {};\n\n return executeLegacyOperation(this.s.topology, evaluate, [\n this,\n code,\n parameters,\n options,\n callback\n ]);\n}, 'Db.eval is deprecated as of MongoDB version 3.2');\n\n/**\n * Rename a collection.\n *\n * @method\n * @param {string} fromCollection Name of current collection to rename.\n * @param {string} toCollection New name of of the collection.\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~collectionResultCallback} [callback] The results callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.renameCollection = function(fromCollection, toCollection, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY });\n\n // Add return new collection\n options.new_collection = true;\n\n const renameOperation = new RenameOperation(\n this.collection(fromCollection),\n toCollection,\n options\n );\n\n return executeOperation(this.s.topology, renameOperation, callback);\n};\n\n/**\n * Drop a collection from the database, removing it permanently. New accesses will create a new collection.\n *\n * @method\n * @param {string} name Name of collection to drop\n * @param {Object} [options] Optional settings\n * @param {WriteConcern} [options.writeConcern] A full WriteConcern object\n * @param {(number|string)} [options.w] The write concern\n * @param {number} [options.wtimeout] The write concern timeout\n * @param {boolean} [options.j] The journal write concern\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The results callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.dropCollection = function(name, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const dropCollectionOperation = new DropCollectionOperation(this, name, options);\n\n return executeOperation(this.s.topology, dropCollectionOperation, callback);\n};\n\n/**\n * Drop a database, removing it permanently from the server.\n *\n * @method\n * @param {Object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The results callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.dropDatabase = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const dropDatabaseOperation = new DropDatabaseOperation(this, options);\n\n return executeOperation(this.s.topology, dropDatabaseOperation, callback);\n};\n\n/**\n * Fetch all collections for the current db.\n *\n * @method\n * @param {Object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~collectionsResultCallback} [callback] The results callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.collections = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const collectionsOperation = new CollectionsOperation(this, options);\n\n return executeOperation(this.s.topology, collectionsOperation, callback);\n};\n\n/**\n * Runs a command on the database as admin.\n * @method\n * @param {object} command The command hash\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.executeDbAdminCommand = function(selector, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n options.readPreference = ReadPreference.resolve(this, options);\n\n const executeDbAdminCommandOperation = new ExecuteDbAdminCommandOperation(\n this,\n selector,\n options\n );\n\n return executeOperation(this.s.topology, executeDbAdminCommandOperation, callback);\n};\n\n/**\n * Creates an index on the db and collection.\n * @method\n * @param {string} name Name of the collection to create the index on.\n * @param {(string|object)} fieldOrSpec Defines the index.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.unique=false] Creates an unique index.\n * @param {boolean} [options.sparse=false] Creates a sparse index.\n * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.\n * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value\n * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates.\n * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates.\n * @param {number} [options.v] Specify the format version of the indexes.\n * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)\n * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)\n * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher)\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {(number|string)} [options.commitQuorum] (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the \"w\" field in a write concern plus \"votingMembers\", which indicates all voting data-bearing nodes.\n * @param {Db~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.createIndex = function(name, fieldOrSpec, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options ? Object.assign({}, options) : {};\n\n const createIndexesOperation = new CreateIndexesOperation(this, name, fieldOrSpec, options);\n\n return executeOperation(this.s.topology, createIndexesOperation, callback);\n};\n\n/**\n * Ensures that an index exists, if it does not it creates it\n * @method\n * @deprecated since version 2.0\n * @param {string} name The index name\n * @param {(string|object)} fieldOrSpec Defines the index.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.unique=false] Creates an unique index.\n * @param {boolean} [options.sparse=false] Creates a sparse index.\n * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.\n * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value\n * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates.\n * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates.\n * @param {number} [options.v] Specify the format version of the indexes.\n * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)\n * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeLegacyOperation(this.s.topology, ensureIndex, [\n this,\n name,\n fieldOrSpec,\n options,\n callback\n ]);\n}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0');\n\nDb.prototype.addChild = function(db) {\n if (this.s.parentDb) return this.s.parentDb.addChild(db);\n this.s.children.push(db);\n};\n\n/**\n * Add a user to the database.\n * @method\n * @param {string} username The username.\n * @param {string} password The password.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher)\n * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher)\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.addUser = function(username, password, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n // Special case where there is no password ($external users)\n if (typeof username === 'string' && password != null && typeof password === 'object') {\n options = password;\n password = null;\n }\n\n const addUserOperation = new AddUserOperation(this, username, password, options);\n\n return executeOperation(this.s.topology, addUserOperation, callback);\n};\n\n/**\n * Remove a user from a database\n * @method\n * @param {string} username The username.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.removeUser = function(username, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const removeUserOperation = new RemoveUserOperation(this, username, options);\n\n return executeOperation(this.s.topology, removeUserOperation, callback);\n};\n\n/**\n * Set the current profiling level of MongoDB\n *\n * @param {string} level The new profiling level (off, slow_only, all).\n * @param {Object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The command result callback.\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.setProfilingLevel = function(level, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const setProfilingLevelOperation = new SetProfilingLevelOperation(this, level, options);\n\n return executeOperation(this.s.topology, setProfilingLevelOperation, callback);\n};\n\n/**\n * Retrieve the current profiling information for MongoDB\n *\n * @param {Object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The command result callback.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Query the system.profile collection directly.\n */\nDb.prototype.profilingInfo = deprecate(function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeLegacyOperation(this.s.topology, profilingInfo, [this, options, callback]);\n}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.');\n\n/**\n * Retrieve the current profiling Level for MongoDB\n *\n * @param {Object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.profilingLevel = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const profilingLevelOperation = new ProfilingLevelOperation(this, options);\n\n return executeOperation(this.s.topology, profilingLevelOperation, callback);\n};\n\n/**\n * Retrieves this collections index info.\n * @method\n * @param {string} name The name of the collection.\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.full=false] Returns the full raw index information.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {Db~resultCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nDb.prototype.indexInformation = function(name, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n const indexInformationOperation = new IndexInformationOperation(this, name, options);\n\n return executeOperation(this.s.topology, indexInformationOperation, callback);\n};\n\n/**\n * Unref all sockets\n * @method\n */\nDb.prototype.unref = function() {\n this.s.topology.unref();\n};\n\n/**\n * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections.\n * @method\n * @since 3.1.0\n * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.\n * @param {object} [options] Optional settings\n * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.\n * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.\n * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query\n * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.\n * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @return {ChangeStream} a ChangeStream instance.\n */\nDb.prototype.watch = function(pipeline, options) {\n pipeline = pipeline || [];\n options = options || {};\n\n // Allow optionally not specifying a pipeline\n if (!Array.isArray(pipeline)) {\n options = pipeline;\n pipeline = [];\n }\n\n return new ChangeStream(this, pipeline, options);\n};\n\n/**\n * Return the db logger\n * @method\n * @return {Logger} return the db logger\n * @ignore\n */\nDb.prototype.getLogger = function() {\n return this.s.logger;\n};\n\n/**\n * Db close event\n *\n * Emitted after a socket closed against a single server or mongos proxy.\n *\n * @event Db#close\n * @type {MongoError}\n */\n\n/**\n * Db reconnect event\n *\n * * Server: Emitted when the driver has reconnected and re-authenticated.\n * * ReplicaSet: N/A\n * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos.\n *\n * @event Db#reconnect\n * @type {object}\n */\n\n/**\n * Db error event\n *\n * Emitted after an error occurred against a single server or mongos proxy.\n *\n * @event Db#error\n * @type {MongoError}\n */\n\n/**\n * Db timeout event\n *\n * Emitted after a socket timeout occurred against a single server or mongos proxy.\n *\n * @event Db#timeout\n * @type {MongoError}\n */\n\n/**\n * Db parseError event\n *\n * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server.\n *\n * @event Db#parseError\n * @type {MongoError}\n */\n\n/**\n * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time.\n *\n * * Server: Emitted when the driver has connected to the single server and has authenticated.\n * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members.\n * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies.\n *\n * @event Db#fullsetup\n * @type {Db}\n */\n\n// Constants\nDb.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION;\nDb.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION;\nDb.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION;\nDb.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION;\nDb.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION;\nDb.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION;\n\nmodule.exports = Db;\n","'use strict';\n\nlet collection;\nlet cursor;\nlet db;\n\nfunction loadCollection() {\n if (!collection) {\n collection = require('./collection');\n }\n return collection;\n}\n\nfunction loadCursor() {\n if (!cursor) {\n cursor = require('./cursor');\n }\n return cursor;\n}\n\nfunction loadDb() {\n if (!db) {\n db = require('./db');\n }\n return db;\n}\n\nmodule.exports = {\n loadCollection,\n loadCursor,\n loadDb\n};\n","'use strict';\n\nconst MongoNetworkError = require('./core').MongoNetworkError;\n\n// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error\nconst GET_MORE_RESUMABLE_CODES = new Set([\n 6, // HostUnreachable\n 7, // HostNotFound\n 89, // NetworkTimeout\n 91, // ShutdownInProgress\n 189, // PrimarySteppedDown\n 262, // ExceededTimeLimit\n 9001, // SocketException\n 10107, // NotMaster\n 11600, // InterruptedAtShutdown\n 11602, // InterruptedDueToReplStateChange\n 13435, // NotMasterNoSlaveOk\n 13436, // NotMasterOrSecondary\n 63, // StaleShardVersion\n 150, // StaleEpoch\n 13388, // StaleConfig\n 234, // RetryChangeStream\n 133, // FailedToSatisfyReadPreference\n 43 // CursorNotFound\n]);\n\nfunction isResumableError(error, wireVersion) {\n if (error instanceof MongoNetworkError) {\n return true;\n }\n\n if (wireVersion >= 9) {\n // DRIVERS-1308: For 4.4 drivers running against 4.4 servers, drivers will add a special case to treat the CursorNotFound error code as resumable\n if (error.code === 43) {\n return true;\n }\n return error.hasErrorLabel('ResumableChangeStreamError');\n }\n\n return GET_MORE_RESUMABLE_CODES.has(error.code);\n}\n\nmodule.exports = { GET_MORE_RESUMABLE_CODES, isResumableError };\n","'use strict';\n\nvar stream = require('stream'),\n util = require('util');\n\nmodule.exports = GridFSBucketReadStream;\n\n/**\n * A readable stream that enables you to read buffers from GridFS.\n *\n * Do not instantiate this class directly. Use `openDownloadStream()` instead.\n *\n * @class\n * @extends external:Readable\n * @param {Collection} chunks Handle for chunks collection\n * @param {Collection} files Handle for files collection\n * @param {Object} readPreference The read preference to use\n * @param {Object} filter The query to use to find the file document\n * @param {Object} [options] Optional settings.\n * @param {Number} [options.sort] Optional sort for the file find query\n * @param {Number} [options.skip] Optional skip for the file find query\n * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from\n * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before\n * @fires GridFSBucketReadStream#error\n * @fires GridFSBucketReadStream#file\n */\nfunction GridFSBucketReadStream(chunks, files, readPreference, filter, options) {\n this.s = {\n bytesRead: 0,\n chunks: chunks,\n cursor: null,\n expected: 0,\n files: files,\n filter: filter,\n init: false,\n expectedEnd: 0,\n file: null,\n options: options,\n readPreference: readPreference\n };\n\n stream.Readable.call(this);\n}\n\nutil.inherits(GridFSBucketReadStream, stream.Readable);\n\n/**\n * An error occurred\n *\n * @event GridFSBucketReadStream#error\n * @type {Error}\n */\n\n/**\n * Fires when the stream loaded the file document corresponding to the\n * provided id.\n *\n * @event GridFSBucketReadStream#file\n * @type {object}\n */\n\n/**\n * Emitted when a chunk of data is available to be consumed.\n *\n * @event GridFSBucketReadStream#data\n * @type {object}\n */\n\n/**\n * Fired when the stream is exhausted (no more data events).\n *\n * @event GridFSBucketReadStream#end\n * @type {object}\n */\n\n/**\n * Fired when the stream is exhausted and the underlying cursor is killed\n *\n * @event GridFSBucketReadStream#close\n * @type {object}\n */\n\n/**\n * Reads from the cursor and pushes to the stream.\n * Private Impl, do not call directly\n * @ignore\n * @method\n */\n\nGridFSBucketReadStream.prototype._read = function() {\n var _this = this;\n if (this.destroyed) {\n return;\n }\n\n waitForFile(_this, function() {\n doRead(_this);\n });\n};\n\n/**\n * Sets the 0-based offset in bytes to start streaming from. Throws\n * an error if this stream has entered flowing mode\n * (e.g. if you've already called `on('data')`)\n * @method\n * @param {Number} start Offset in bytes to start reading at\n * @return {GridFSBucketReadStream} Reference to Self\n */\n\nGridFSBucketReadStream.prototype.start = function(start) {\n throwIfInitialized(this);\n this.s.options.start = start;\n return this;\n};\n\n/**\n * Sets the 0-based offset in bytes to start streaming from. Throws\n * an error if this stream has entered flowing mode\n * (e.g. if you've already called `on('data')`)\n * @method\n * @param {Number} end Offset in bytes to stop reading at\n * @return {GridFSBucketReadStream} Reference to self\n */\n\nGridFSBucketReadStream.prototype.end = function(end) {\n throwIfInitialized(this);\n this.s.options.end = end;\n return this;\n};\n\n/**\n * Marks this stream as aborted (will never push another `data` event)\n * and kills the underlying cursor. Will emit the 'end' event, and then\n * the 'close' event once the cursor is successfully killed.\n *\n * @method\n * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred.\n * @fires GridFSBucketWriteStream#close\n * @fires GridFSBucketWriteStream#end\n */\n\nGridFSBucketReadStream.prototype.abort = function(callback) {\n var _this = this;\n this.push(null);\n this.destroyed = true;\n if (this.s.cursor) {\n this.s.cursor.close(function(error) {\n _this.emit('close');\n callback && callback(error);\n });\n } else {\n if (!this.s.init) {\n // If not initialized, fire close event because we will never\n // get a cursor\n _this.emit('close');\n }\n callback && callback();\n }\n};\n\n/**\n * @ignore\n */\n\nfunction throwIfInitialized(self) {\n if (self.s.init) {\n throw new Error('You cannot change options after the stream has entered' + 'flowing mode!');\n }\n}\n\n/**\n * @ignore\n */\n\nfunction doRead(_this) {\n if (_this.destroyed) {\n return;\n }\n\n _this.s.cursor.next(function(error, doc) {\n if (_this.destroyed) {\n return;\n }\n if (error) {\n return __handleError(_this, error);\n }\n if (!doc) {\n _this.push(null);\n\n process.nextTick(() => {\n _this.s.cursor.close(function(error) {\n if (error) {\n __handleError(_this, error);\n return;\n }\n\n _this.emit('close');\n });\n });\n\n return;\n }\n\n var bytesRemaining = _this.s.file.length - _this.s.bytesRead;\n var expectedN = _this.s.expected++;\n var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining);\n\n if (doc.n > expectedN) {\n var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN;\n return __handleError(_this, new Error(errmsg));\n }\n\n if (doc.n < expectedN) {\n errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN;\n return __handleError(_this, new Error(errmsg));\n }\n\n var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer;\n\n if (buf.length !== expectedLength) {\n if (bytesRemaining <= 0) {\n errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n;\n return __handleError(_this, new Error(errmsg));\n }\n\n errmsg =\n 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength;\n return __handleError(_this, new Error(errmsg));\n }\n\n _this.s.bytesRead += buf.length;\n\n if (buf.length === 0) {\n return _this.push(null);\n }\n\n var sliceStart = null;\n var sliceEnd = null;\n\n if (_this.s.bytesToSkip != null) {\n sliceStart = _this.s.bytesToSkip;\n _this.s.bytesToSkip = 0;\n }\n\n const atEndOfStream = expectedN === _this.s.expectedEnd - 1;\n const bytesLeftToRead = _this.s.options.end - _this.s.bytesToSkip;\n if (atEndOfStream && _this.s.bytesToTrim != null) {\n sliceEnd = _this.s.file.chunkSize - _this.s.bytesToTrim;\n } else if (_this.s.options.end && bytesLeftToRead < doc.data.length()) {\n sliceEnd = bytesLeftToRead;\n }\n\n if (sliceStart != null || sliceEnd != null) {\n buf = buf.slice(sliceStart || 0, sliceEnd || buf.length);\n }\n\n _this.push(buf);\n });\n}\n\n/**\n * @ignore\n */\n\nfunction init(self) {\n var findOneOptions = {};\n if (self.s.readPreference) {\n findOneOptions.readPreference = self.s.readPreference;\n }\n if (self.s.options && self.s.options.sort) {\n findOneOptions.sort = self.s.options.sort;\n }\n if (self.s.options && self.s.options.skip) {\n findOneOptions.skip = self.s.options.skip;\n }\n\n self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) {\n if (error) {\n return __handleError(self, error);\n }\n\n if (!doc) {\n var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename;\n var errmsg = 'FileNotFound: file ' + identifier + ' was not found';\n var err = new Error(errmsg);\n err.code = 'ENOENT';\n return __handleError(self, err);\n }\n\n // If document is empty, kill the stream immediately and don't\n // execute any reads\n if (doc.length <= 0) {\n self.push(null);\n return;\n }\n\n if (self.destroyed) {\n // If user destroys the stream before we have a cursor, wait\n // until the query is done to say we're 'closed' because we can't\n // cancel a query.\n self.emit('close');\n return;\n }\n\n try {\n self.s.bytesToSkip = handleStartOption(self, doc, self.s.options);\n } catch (error) {\n return __handleError(self, error);\n }\n\n var filter = { files_id: doc._id };\n\n // Currently (MongoDB 3.4.4) skip function does not support the index,\n // it needs to retrieve all the documents first and then skip them. (CS-25811)\n // As work around we use $gte on the \"n\" field.\n if (self.s.options && self.s.options.start != null) {\n var skip = Math.floor(self.s.options.start / doc.chunkSize);\n if (skip > 0) {\n filter['n'] = { $gte: skip };\n }\n }\n self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 });\n\n if (self.s.readPreference) {\n self.s.cursor.setReadPreference(self.s.readPreference);\n }\n\n self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize);\n self.s.file = doc;\n\n try {\n self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options);\n } catch (error) {\n return __handleError(self, error);\n }\n\n self.emit('file', doc);\n });\n}\n\n/**\n * @ignore\n */\n\nfunction waitForFile(_this, callback) {\n if (_this.s.file) {\n return callback();\n }\n\n if (!_this.s.init) {\n init(_this);\n _this.s.init = true;\n }\n\n _this.once('file', function() {\n callback();\n });\n}\n\n/**\n * @ignore\n */\n\nfunction handleStartOption(stream, doc, options) {\n if (options && options.start != null) {\n if (options.start > doc.length) {\n throw new Error(\n 'Stream start (' +\n options.start +\n ') must not be ' +\n 'more than the length of the file (' +\n doc.length +\n ')'\n );\n }\n if (options.start < 0) {\n throw new Error('Stream start (' + options.start + ') must not be ' + 'negative');\n }\n if (options.end != null && options.end < options.start) {\n throw new Error(\n 'Stream start (' +\n options.start +\n ') must not be ' +\n 'greater than stream end (' +\n options.end +\n ')'\n );\n }\n\n stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize;\n stream.s.expected = Math.floor(options.start / doc.chunkSize);\n\n return options.start - stream.s.bytesRead;\n }\n}\n\n/**\n * @ignore\n */\n\nfunction handleEndOption(stream, doc, cursor, options) {\n if (options && options.end != null) {\n if (options.end > doc.length) {\n throw new Error(\n 'Stream end (' +\n options.end +\n ') must not be ' +\n 'more than the length of the file (' +\n doc.length +\n ')'\n );\n }\n if (options.start < 0) {\n throw new Error('Stream end (' + options.end + ') must not be ' + 'negative');\n }\n\n var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0;\n\n cursor.limit(Math.ceil(options.end / doc.chunkSize) - start);\n\n stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize);\n\n return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end;\n }\n}\n\n/**\n * @ignore\n */\n\nfunction __handleError(_this, error) {\n _this.emit('error', error);\n}\n","'use strict';\n\nvar Emitter = require('events').EventEmitter;\nvar GridFSBucketReadStream = require('./download');\nvar GridFSBucketWriteStream = require('./upload');\nvar shallowClone = require('../utils').shallowClone;\nvar toError = require('../utils').toError;\nvar util = require('util');\nvar executeLegacyOperation = require('../utils').executeLegacyOperation;\n\nvar DEFAULT_GRIDFS_BUCKET_OPTIONS = {\n bucketName: 'fs',\n chunkSizeBytes: 255 * 1024\n};\n\nmodule.exports = GridFSBucket;\n\n/**\n * Constructor for a streaming GridFS interface\n * @class\n * @extends external:EventEmitter\n * @param {Db} db A db handle\n * @param {object} [options] Optional settings.\n * @param {string} [options.bucketName=\"fs\"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot.\n * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB\n * @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }`\n * @param {object} [options.readPreference] Optional read preference to be passed to read operations\n * @fires GridFSBucketWriteStream#index\n */\n\nfunction GridFSBucket(db, options) {\n Emitter.apply(this);\n this.setMaxListeners(0);\n\n if (options && typeof options === 'object') {\n options = shallowClone(options);\n var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS);\n for (var i = 0; i < keys.length; ++i) {\n if (!options[keys[i]]) {\n options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]];\n }\n }\n } else {\n options = DEFAULT_GRIDFS_BUCKET_OPTIONS;\n }\n\n this.s = {\n db: db,\n options: options,\n _chunksCollection: db.collection(options.bucketName + '.chunks'),\n _filesCollection: db.collection(options.bucketName + '.files'),\n checkedIndexes: false,\n calledOpenUploadStream: false,\n promiseLibrary: db.s.promiseLibrary || Promise\n };\n}\n\nutil.inherits(GridFSBucket, Emitter);\n\n/**\n * When the first call to openUploadStream is made, the upload stream will\n * check to see if it needs to create the proper indexes on the chunks and\n * files collections. This event is fired either when 1) it determines that\n * no index creation is necessary, 2) when it successfully creates the\n * necessary indexes.\n *\n * @event GridFSBucket#index\n * @type {Error}\n */\n\n/**\n * Returns a writable stream (GridFSBucketWriteStream) for writing\n * buffers to GridFS. The stream's 'id' property contains the resulting\n * file's id.\n * @method\n * @param {string} filename The value of the 'filename' key in the files doc\n * @param {object} [options] Optional settings.\n * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file\n * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field\n * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field\n * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field\n * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data\n * @return {GridFSBucketWriteStream}\n */\n\nGridFSBucket.prototype.openUploadStream = function(filename, options) {\n if (options) {\n options = shallowClone(options);\n } else {\n options = {};\n }\n if (!options.chunkSizeBytes) {\n options.chunkSizeBytes = this.s.options.chunkSizeBytes;\n }\n return new GridFSBucketWriteStream(this, filename, options);\n};\n\n/**\n * Returns a writable stream (GridFSBucketWriteStream) for writing\n * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting\n * file's id.\n * @method\n * @param {string|number|object} id A custom id used to identify the file\n * @param {string} filename The value of the 'filename' key in the files doc\n * @param {object} [options] Optional settings.\n * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file\n * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field\n * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field\n * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field\n * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data\n * @return {GridFSBucketWriteStream}\n */\n\nGridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) {\n if (options) {\n options = shallowClone(options);\n } else {\n options = {};\n }\n\n if (!options.chunkSizeBytes) {\n options.chunkSizeBytes = this.s.options.chunkSizeBytes;\n }\n\n options.id = id;\n\n return new GridFSBucketWriteStream(this, filename, options);\n};\n\n/**\n * Returns a readable stream (GridFSBucketReadStream) for streaming file\n * data from GridFS.\n * @method\n * @param {ObjectId} id The id of the file doc\n * @param {Object} [options] Optional settings.\n * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from\n * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before\n * @return {GridFSBucketReadStream}\n */\n\nGridFSBucket.prototype.openDownloadStream = function(id, options) {\n var filter = { _id: id };\n options = {\n start: options && options.start,\n end: options && options.end\n };\n\n return new GridFSBucketReadStream(\n this.s._chunksCollection,\n this.s._filesCollection,\n this.s.options.readPreference,\n filter,\n options\n );\n};\n\n/**\n * Deletes a file with the given id\n * @method\n * @param {ObjectId} id The id of the file doc\n * @param {GridFSBucket~errorCallback} [callback]\n */\n\nGridFSBucket.prototype.delete = function(id, callback) {\n return executeLegacyOperation(this.s.db.s.topology, _delete, [this, id, callback], {\n skipSessions: true\n });\n};\n\n/**\n * @ignore\n */\n\nfunction _delete(_this, id, callback) {\n _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) {\n if (error) {\n return callback(error);\n }\n\n _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) {\n if (error) {\n return callback(error);\n }\n\n // Delete orphaned chunks before returning FileNotFound\n if (!res.result.n) {\n var errmsg = 'FileNotFound: no file with id ' + id + ' found';\n return callback(new Error(errmsg));\n }\n\n callback();\n });\n });\n}\n\n/**\n * Convenience wrapper around find on the files collection\n * @method\n * @param {Object} filter\n * @param {Object} [options] Optional settings for cursor\n * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find|find command documentation}.\n * @param {number} [options.limit] Optional limit for cursor\n * @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor\n * @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag\n * @param {number} [options.skip] Optional skip for cursor\n * @param {object} [options.sort] Optional sort for cursor\n * @return {Cursor}\n */\n\nGridFSBucket.prototype.find = function(filter, options) {\n filter = filter || {};\n options = options || {};\n\n var cursor = this.s._filesCollection.find(filter);\n\n if (options.batchSize != null) {\n cursor.batchSize(options.batchSize);\n }\n if (options.limit != null) {\n cursor.limit(options.limit);\n }\n if (options.maxTimeMS != null) {\n cursor.maxTimeMS(options.maxTimeMS);\n }\n if (options.noCursorTimeout != null) {\n cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout);\n }\n if (options.skip != null) {\n cursor.skip(options.skip);\n }\n if (options.sort != null) {\n cursor.sort(options.sort);\n }\n\n return cursor;\n};\n\n/**\n * Returns a readable stream (GridFSBucketReadStream) for streaming the\n * file with the given name from GridFS. If there are multiple files with\n * the same name, this will stream the most recent file with the given name\n * (as determined by the `uploadDate` field). You can set the `revision`\n * option to change this behavior.\n * @method\n * @param {String} filename The name of the file to stream\n * @param {Object} [options] Optional settings\n * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest.\n * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from\n * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before\n * @return {GridFSBucketReadStream}\n */\n\nGridFSBucket.prototype.openDownloadStreamByName = function(filename, options) {\n var sort = { uploadDate: -1 };\n var skip = null;\n if (options && options.revision != null) {\n if (options.revision >= 0) {\n sort = { uploadDate: 1 };\n skip = options.revision;\n } else {\n skip = -options.revision - 1;\n }\n }\n\n var filter = { filename: filename };\n options = {\n sort: sort,\n skip: skip,\n start: options && options.start,\n end: options && options.end\n };\n return new GridFSBucketReadStream(\n this.s._chunksCollection,\n this.s._filesCollection,\n this.s.options.readPreference,\n filter,\n options\n );\n};\n\n/**\n * Renames the file with the given _id to the given string\n * @method\n * @param {ObjectId} id the id of the file to rename\n * @param {String} filename new name for the file\n * @param {GridFSBucket~errorCallback} [callback]\n */\n\nGridFSBucket.prototype.rename = function(id, filename, callback) {\n return executeLegacyOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], {\n skipSessions: true\n });\n};\n\n/**\n * @ignore\n */\n\nfunction _rename(_this, id, filename, callback) {\n var filter = { _id: id };\n var update = { $set: { filename: filename } };\n _this.s._filesCollection.updateOne(filter, update, function(error, res) {\n if (error) {\n return callback(error);\n }\n if (!res.result.n) {\n return callback(toError('File with id ' + id + ' not found'));\n }\n callback();\n });\n}\n\n/**\n * Removes this bucket's files collection, followed by its chunks collection.\n * @method\n * @param {GridFSBucket~errorCallback} [callback]\n */\n\nGridFSBucket.prototype.drop = function(callback) {\n return executeLegacyOperation(this.s.db.s.topology, _drop, [this, callback], {\n skipSessions: true\n });\n};\n\n/**\n * Return the db logger\n * @method\n * @return {Logger} return the db logger\n * @ignore\n */\nGridFSBucket.prototype.getLogger = function() {\n return this.s.db.s.logger;\n};\n\n/**\n * @ignore\n */\n\nfunction _drop(_this, callback) {\n _this.s._filesCollection.drop(function(error) {\n if (error) {\n return callback(error);\n }\n _this.s._chunksCollection.drop(function(error) {\n if (error) {\n return callback(error);\n }\n\n return callback();\n });\n });\n}\n\n/**\n * Callback format for all GridFSBucket methods that can accept a callback.\n * @callback GridFSBucket~errorCallback\n * @param {MongoError|undefined} error If present, an error instance representing any errors that occurred\n * @param {*} result If present, a returned result for the method\n */\n","'use strict';\n\nvar core = require('../core');\nvar crypto = require('crypto');\nvar stream = require('stream');\nvar util = require('util');\nvar Buffer = require('safe-buffer').Buffer;\n\nvar ERROR_NAMESPACE_NOT_FOUND = 26;\n\nmodule.exports = GridFSBucketWriteStream;\n\n/**\n * A writable stream that enables you to write buffers to GridFS.\n *\n * Do not instantiate this class directly. Use `openUploadStream()` instead.\n *\n * @class\n * @extends external:Writable\n * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket\n * @param {string} filename The value of the 'filename' key in the files doc\n * @param {object} [options] Optional settings.\n * @param {string|number|object} [options.id] Custom file id for the GridFS file.\n * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes\n * @param {number} [options.w] The write concern\n * @param {number} [options.wtimeout] The write concern timeout\n * @param {number} [options.j] The journal write concern\n * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data\n * @fires GridFSBucketWriteStream#error\n * @fires GridFSBucketWriteStream#finish\n */\n\nfunction GridFSBucketWriteStream(bucket, filename, options) {\n options = options || {};\n this.bucket = bucket;\n this.chunks = bucket.s._chunksCollection;\n this.filename = filename;\n this.files = bucket.s._filesCollection;\n this.options = options;\n // Signals the write is all done\n this.done = false;\n\n this.id = options.id ? options.id : core.BSON.ObjectId();\n this.chunkSizeBytes = this.options.chunkSizeBytes;\n this.bufToStore = Buffer.alloc(this.chunkSizeBytes);\n this.length = 0;\n this.md5 = !options.disableMD5 && crypto.createHash('md5');\n this.n = 0;\n this.pos = 0;\n this.state = {\n streamEnd: false,\n outstandingRequests: 0,\n errored: false,\n aborted: false,\n promiseLibrary: this.bucket.s.promiseLibrary\n };\n\n if (!this.bucket.s.calledOpenUploadStream) {\n this.bucket.s.calledOpenUploadStream = true;\n\n var _this = this;\n checkIndexes(this, function() {\n _this.bucket.s.checkedIndexes = true;\n _this.bucket.emit('index');\n });\n }\n}\n\nutil.inherits(GridFSBucketWriteStream, stream.Writable);\n\n/**\n * An error occurred\n *\n * @event GridFSBucketWriteStream#error\n * @type {Error}\n */\n\n/**\n * `end()` was called and the write stream successfully wrote the file\n * metadata and all the chunks to MongoDB.\n *\n * @event GridFSBucketWriteStream#finish\n * @type {object}\n */\n\n/**\n * Write a buffer to the stream.\n *\n * @method\n * @param {Buffer} chunk Buffer to write\n * @param {String} encoding Optional encoding for the buffer\n * @param {GridFSBucket~errorCallback} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush.\n * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise.\n */\n\nGridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) {\n var _this = this;\n return waitForIndexes(this, function() {\n return doWrite(_this, chunk, encoding, callback);\n });\n};\n\n/**\n * Places this write stream into an aborted state (all future writes fail)\n * and deletes all chunks that have already been written.\n *\n * @method\n * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred\n * @return {Promise} if no callback specified\n */\n\nGridFSBucketWriteStream.prototype.abort = function(callback) {\n if (this.state.streamEnd) {\n var error = new Error('Cannot abort a stream that has already completed');\n if (typeof callback === 'function') {\n return callback(error);\n }\n return this.state.promiseLibrary.reject(error);\n }\n if (this.state.aborted) {\n error = new Error('Cannot call abort() on a stream twice');\n if (typeof callback === 'function') {\n return callback(error);\n }\n return this.state.promiseLibrary.reject(error);\n }\n this.state.aborted = true;\n this.chunks.deleteMany({ files_id: this.id }, function(error) {\n if (typeof callback === 'function') callback(error);\n });\n};\n\n/**\n * Tells the stream that no more data will be coming in. The stream will\n * persist the remaining data to MongoDB, write the files document, and\n * then emit a 'finish' event.\n *\n * @method\n * @param {Buffer} chunk Buffer to write\n * @param {String} encoding Optional encoding for the buffer\n * @param {GridFSBucket~errorCallback} callback Function to call when all files and chunks have been persisted to MongoDB\n */\n\nGridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) {\n var _this = this;\n if (typeof chunk === 'function') {\n (callback = chunk), (chunk = null), (encoding = null);\n } else if (typeof encoding === 'function') {\n (callback = encoding), (encoding = null);\n }\n\n if (checkAborted(this, callback)) {\n return;\n }\n this.state.streamEnd = true;\n\n if (callback) {\n this.once('finish', function(result) {\n callback(null, result);\n });\n }\n\n if (!chunk) {\n waitForIndexes(this, function() {\n writeRemnant(_this);\n });\n return;\n }\n\n this.write(chunk, encoding, function() {\n writeRemnant(_this);\n });\n};\n\n/**\n * @ignore\n */\n\nfunction __handleError(_this, error, callback) {\n if (_this.state.errored) {\n return;\n }\n _this.state.errored = true;\n if (callback) {\n return callback(error);\n }\n _this.emit('error', error);\n}\n\n/**\n * @ignore\n */\n\nfunction createChunkDoc(filesId, n, data) {\n return {\n _id: core.BSON.ObjectId(),\n files_id: filesId,\n n: n,\n data: data\n };\n}\n\n/**\n * @ignore\n */\n\nfunction checkChunksIndex(_this, callback) {\n _this.chunks.listIndexes().toArray(function(error, indexes) {\n if (error) {\n // Collection doesn't exist so create index\n if (error.code === ERROR_NAMESPACE_NOT_FOUND) {\n var index = { files_id: 1, n: 1 };\n _this.chunks.createIndex(index, { background: false, unique: true }, function(error) {\n if (error) {\n return callback(error);\n }\n\n callback();\n });\n return;\n }\n return callback(error);\n }\n\n var hasChunksIndex = false;\n indexes.forEach(function(index) {\n if (index.key) {\n var keys = Object.keys(index.key);\n if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) {\n hasChunksIndex = true;\n }\n }\n });\n\n if (hasChunksIndex) {\n callback();\n } else {\n index = { files_id: 1, n: 1 };\n var indexOptions = getWriteOptions(_this);\n\n indexOptions.background = false;\n indexOptions.unique = true;\n\n _this.chunks.createIndex(index, indexOptions, function(error) {\n if (error) {\n return callback(error);\n }\n\n callback();\n });\n }\n });\n}\n\n/**\n * @ignore\n */\n\nfunction checkDone(_this, callback) {\n if (_this.done) return true;\n if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) {\n // Set done so we dont' trigger duplicate createFilesDoc\n _this.done = true;\n // Create a new files doc\n var filesDoc = createFilesDoc(\n _this.id,\n _this.length,\n _this.chunkSizeBytes,\n _this.md5 && _this.md5.digest('hex'),\n _this.filename,\n _this.options.contentType,\n _this.options.aliases,\n _this.options.metadata\n );\n\n if (checkAborted(_this, callback)) {\n return false;\n }\n\n _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) {\n if (error) {\n return __handleError(_this, error, callback);\n }\n _this.emit('finish', filesDoc);\n });\n\n return true;\n }\n\n return false;\n}\n\n/**\n * @ignore\n */\n\nfunction checkIndexes(_this, callback) {\n _this.files.findOne({}, { _id: 1 }, function(error, doc) {\n if (error) {\n return callback(error);\n }\n if (doc) {\n return callback();\n }\n\n _this.files.listIndexes().toArray(function(error, indexes) {\n if (error) {\n // Collection doesn't exist so create index\n if (error.code === ERROR_NAMESPACE_NOT_FOUND) {\n var index = { filename: 1, uploadDate: 1 };\n _this.files.createIndex(index, { background: false }, function(error) {\n if (error) {\n return callback(error);\n }\n\n checkChunksIndex(_this, callback);\n });\n return;\n }\n return callback(error);\n }\n\n var hasFileIndex = false;\n indexes.forEach(function(index) {\n var keys = Object.keys(index.key);\n if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) {\n hasFileIndex = true;\n }\n });\n\n if (hasFileIndex) {\n checkChunksIndex(_this, callback);\n } else {\n index = { filename: 1, uploadDate: 1 };\n\n var indexOptions = getWriteOptions(_this);\n\n indexOptions.background = false;\n\n _this.files.createIndex(index, indexOptions, function(error) {\n if (error) {\n return callback(error);\n }\n\n checkChunksIndex(_this, callback);\n });\n }\n });\n });\n}\n\n/**\n * @ignore\n */\n\nfunction createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) {\n var ret = {\n _id: _id,\n length: length,\n chunkSize: chunkSize,\n uploadDate: new Date(),\n filename: filename\n };\n\n if (md5) {\n ret.md5 = md5;\n }\n\n if (contentType) {\n ret.contentType = contentType;\n }\n\n if (aliases) {\n ret.aliases = aliases;\n }\n\n if (metadata) {\n ret.metadata = metadata;\n }\n\n return ret;\n}\n\n/**\n * @ignore\n */\n\nfunction doWrite(_this, chunk, encoding, callback) {\n if (checkAborted(_this, callback)) {\n return false;\n }\n\n var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding);\n\n _this.length += inputBuf.length;\n\n // Input is small enough to fit in our buffer\n if (_this.pos + inputBuf.length < _this.chunkSizeBytes) {\n inputBuf.copy(_this.bufToStore, _this.pos);\n _this.pos += inputBuf.length;\n\n callback && callback();\n\n // Note that we reverse the typical semantics of write's return value\n // to be compatible with node's `.pipe()` function.\n // True means client can keep writing.\n return true;\n }\n\n // Otherwise, buffer is too big for current chunk, so we need to flush\n // to MongoDB.\n var inputBufRemaining = inputBuf.length;\n var spaceRemaining = _this.chunkSizeBytes - _this.pos;\n var numToCopy = Math.min(spaceRemaining, inputBuf.length);\n var outstandingRequests = 0;\n while (inputBufRemaining > 0) {\n var inputBufPos = inputBuf.length - inputBufRemaining;\n inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy);\n _this.pos += numToCopy;\n spaceRemaining -= numToCopy;\n if (spaceRemaining === 0) {\n if (_this.md5) {\n _this.md5.update(_this.bufToStore);\n }\n var doc = createChunkDoc(_this.id, _this.n, Buffer.from(_this.bufToStore));\n ++_this.state.outstandingRequests;\n ++outstandingRequests;\n\n if (checkAborted(_this, callback)) {\n return false;\n }\n\n _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) {\n if (error) {\n return __handleError(_this, error);\n }\n --_this.state.outstandingRequests;\n --outstandingRequests;\n\n if (!outstandingRequests) {\n _this.emit('drain', doc);\n callback && callback();\n checkDone(_this);\n }\n });\n\n spaceRemaining = _this.chunkSizeBytes;\n _this.pos = 0;\n ++_this.n;\n }\n inputBufRemaining -= numToCopy;\n numToCopy = Math.min(spaceRemaining, inputBufRemaining);\n }\n\n // Note that we reverse the typical semantics of write's return value\n // to be compatible with node's `.pipe()` function.\n // False means the client should wait for the 'drain' event.\n return false;\n}\n\n/**\n * @ignore\n */\n\nfunction getWriteOptions(_this) {\n var obj = {};\n if (_this.options.writeConcern) {\n obj.w = _this.options.writeConcern.w;\n obj.wtimeout = _this.options.writeConcern.wtimeout;\n obj.j = _this.options.writeConcern.j;\n }\n return obj;\n}\n\n/**\n * @ignore\n */\n\nfunction waitForIndexes(_this, callback) {\n if (_this.bucket.s.checkedIndexes) {\n return callback(false);\n }\n\n _this.bucket.once('index', function() {\n callback(true);\n });\n\n return true;\n}\n\n/**\n * @ignore\n */\n\nfunction writeRemnant(_this, callback) {\n // Buffer is empty, so don't bother to insert\n if (_this.pos === 0) {\n return checkDone(_this, callback);\n }\n\n ++_this.state.outstandingRequests;\n\n // Create a new buffer to make sure the buffer isn't bigger than it needs\n // to be.\n var remnant = Buffer.alloc(_this.pos);\n _this.bufToStore.copy(remnant, 0, 0, _this.pos);\n if (_this.md5) {\n _this.md5.update(remnant);\n }\n var doc = createChunkDoc(_this.id, _this.n, remnant);\n\n // If the stream was aborted, do not write remnant\n if (checkAborted(_this, callback)) {\n return false;\n }\n\n _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) {\n if (error) {\n return __handleError(_this, error);\n }\n --_this.state.outstandingRequests;\n checkDone(_this);\n });\n}\n\n/**\n * @ignore\n */\n\nfunction checkAborted(_this, callback) {\n if (_this.state.aborted) {\n if (typeof callback === 'function') {\n callback(new Error('this stream has been aborted'));\n }\n return true;\n }\n return false;\n}\n","'use strict';\n\nvar Binary = require('../core').BSON.Binary,\n ObjectID = require('../core').BSON.ObjectID;\n\nvar Buffer = require('safe-buffer').Buffer;\n\n/**\n * Class for representing a single chunk in GridFS.\n *\n * @class\n *\n * @param file {GridStore} The {@link GridStore} object holding this chunk.\n * @param mongoObject {object} The mongo object representation of this chunk.\n *\n * @throws Error when the type of data field for {@link mongoObject} is not\n * supported. Currently supported types for data field are instances of\n * {@link String}, {@link Array}, {@link Binary} and {@link Binary}\n * from the bson module\n *\n * @see Chunk#buildMongoObject\n */\nvar Chunk = function(file, mongoObject, writeConcern) {\n if (!(this instanceof Chunk)) return new Chunk(file, mongoObject);\n\n this.file = file;\n var mongoObjectFinal = mongoObject == null ? {} : mongoObject;\n this.writeConcern = writeConcern || { w: 1 };\n this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id;\n this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n;\n this.data = new Binary();\n\n if (typeof mongoObjectFinal.data === 'string') {\n var buffer = Buffer.alloc(mongoObjectFinal.data.length);\n buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary');\n this.data = new Binary(buffer);\n } else if (Array.isArray(mongoObjectFinal.data)) {\n buffer = Buffer.alloc(mongoObjectFinal.data.length);\n var data = mongoObjectFinal.data.join('');\n buffer.write(data, 0, data.length, 'binary');\n this.data = new Binary(buffer);\n } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') {\n this.data = mongoObjectFinal.data;\n } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) {\n throw Error('Illegal chunk format');\n }\n\n // Update position\n this.internalPosition = 0;\n};\n\n/**\n * Writes a data to this object and advance the read/write head.\n *\n * @param data {string} the data to write\n * @param callback {function(*, GridStore)} This will be called after executing\n * this method. The first parameter will contain null and the second one\n * will contain a reference to this object.\n */\nChunk.prototype.write = function(data, callback) {\n this.data.write(data, this.internalPosition, data.length, 'binary');\n this.internalPosition = this.data.length();\n if (callback != null) return callback(null, this);\n return this;\n};\n\n/**\n * Reads data and advances the read/write head.\n *\n * @param length {number} The length of data to read.\n *\n * @return {string} The data read if the given length will not exceed the end of\n * the chunk. Returns an empty String otherwise.\n */\nChunk.prototype.read = function(length) {\n // Default to full read if no index defined\n length = length == null || length === 0 ? this.length() : length;\n\n if (this.length() - this.internalPosition + 1 >= length) {\n var data = this.data.read(this.internalPosition, length);\n this.internalPosition = this.internalPosition + length;\n return data;\n } else {\n return '';\n }\n};\n\nChunk.prototype.readSlice = function(length) {\n if (this.length() - this.internalPosition >= length) {\n var data = null;\n if (this.data.buffer != null) {\n //Pure BSON\n data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length);\n } else {\n //Native BSON\n data = Buffer.alloc(length);\n length = this.data.readInto(data, this.internalPosition);\n }\n this.internalPosition = this.internalPosition + length;\n return data;\n } else {\n return null;\n }\n};\n\n/**\n * Checks if the read/write head is at the end.\n *\n * @return {boolean} Whether the read/write head has reached the end of this\n * chunk.\n */\nChunk.prototype.eof = function() {\n return this.internalPosition === this.length() ? true : false;\n};\n\n/**\n * Reads one character from the data of this chunk and advances the read/write\n * head.\n *\n * @return {string} a single character data read if the the read/write head is\n * not at the end of the chunk. Returns an empty String otherwise.\n */\nChunk.prototype.getc = function() {\n return this.read(1);\n};\n\n/**\n * Clears the contents of the data in this chunk and resets the read/write head\n * to the initial position.\n */\nChunk.prototype.rewind = function() {\n this.internalPosition = 0;\n this.data = new Binary();\n};\n\n/**\n * Saves this chunk to the database. Also overwrites existing entries having the\n * same id as this chunk.\n *\n * @param callback {function(*, GridStore)} This will be called after executing\n * this method. The first parameter will contain null and the second one\n * will contain a reference to this object.\n */\nChunk.prototype.save = function(options, callback) {\n var self = this;\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n self.file.chunkCollection(function(err, collection) {\n if (err) return callback(err);\n\n // Merge the options\n var writeOptions = { upsert: true };\n for (var name in options) writeOptions[name] = options[name];\n for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name];\n\n if (self.data.length() > 0) {\n self.buildMongoObject(function(mongoObject) {\n var options = { forceServerObjectId: true };\n for (var name in self.writeConcern) {\n options[name] = self.writeConcern[name];\n }\n\n collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) {\n callback(err, self);\n });\n });\n } else {\n callback(null, self);\n }\n // });\n });\n};\n\n/**\n * Creates a mongoDB object representation of this chunk.\n *\n * @param callback {function(Object)} This will be called after executing this\n * method. The object will be passed to the first parameter and will have\n * the structure:\n *\n *
\n *        {\n *          '_id' : , // {number} id for this chunk\n *          'files_id' : , // {number} foreign key to the file collection\n *          'n' : , // {number} chunk number\n *          'data' : , // {bson#Binary} the chunk data itself\n *        }\n *        
\n *\n * @see MongoDB GridFS Chunk Object Structure\n */\nChunk.prototype.buildMongoObject = function(callback) {\n var mongoObject = {\n files_id: this.file.fileId,\n n: this.chunkNumber,\n data: this.data\n };\n // If we are saving using a specific ObjectId\n if (this.objectId != null) mongoObject._id = this.objectId;\n\n callback(mongoObject);\n};\n\n/**\n * @return {number} the length of the data\n */\nChunk.prototype.length = function() {\n return this.data.length();\n};\n\n/**\n * The position of the read/write head\n * @name position\n * @lends Chunk#\n * @field\n */\nObject.defineProperty(Chunk.prototype, 'position', {\n enumerable: true,\n get: function() {\n return this.internalPosition;\n },\n set: function(value) {\n this.internalPosition = value;\n }\n});\n\n/**\n * The default chunk size\n * @constant\n */\nChunk.DEFAULT_CHUNK_SIZE = 1024 * 255;\n\nmodule.exports = Chunk;\n","'use strict';\n\n/**\n * @fileOverview GridFS is a tool for MongoDB to store files to the database.\n * Because of the restrictions of the object size the database can hold, a\n * facility to split a file into several chunks is needed. The {@link GridStore}\n * class offers a simplified api to interact with files while managing the\n * chunks of split files behind the scenes. More information about GridFS can be\n * found here.\n *\n * @example\n * const MongoClient = require('mongodb').MongoClient;\n * const GridStore = require('mongodb').GridStore;\n * const ObjectID = require('mongodb').ObjectID;\n * const test = require('assert');\n * // Connection url\n * const url = 'mongodb://localhost:27017';\n * // Database Name\n * const dbName = 'test';\n * // Connect using MongoClient\n * MongoClient.connect(url, function(err, client) {\n * const db = client.db(dbName);\n * const gridStore = new GridStore(db, null, \"w\");\n * gridStore.open(function(err, gridStore) {\n * gridStore.write(\"hello world!\", function(err, gridStore) {\n * gridStore.close(function(err, result) {\n * // Let's read the file using object Id\n * GridStore.read(db, result._id, function(err, data) {\n * test.equal('hello world!', data);\n * client.close();\n * test.done();\n * });\n * });\n * });\n * });\n * });\n */\nconst Chunk = require('./chunk');\nconst ObjectID = require('../core').BSON.ObjectID;\nconst ReadPreference = require('../core').ReadPreference;\nconst Buffer = require('safe-buffer').Buffer;\nconst fs = require('fs');\nconst f = require('util').format;\nconst util = require('util');\nconst MongoError = require('../core').MongoError;\nconst inherits = util.inherits;\nconst Duplex = require('stream').Duplex;\nconst shallowClone = require('../utils').shallowClone;\nconst executeLegacyOperation = require('../utils').executeLegacyOperation;\nconst deprecate = require('util').deprecate;\n\nvar REFERENCE_BY_FILENAME = 0,\n REFERENCE_BY_ID = 1;\n\nconst deprecationFn = deprecate(() => {},\n'GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead');\n\n/**\n * Namespace provided by the core module\n * @external Duplex\n */\n\n/**\n * Create a new GridStore instance\n *\n * Modes\n * - **\"r\"** - read only. This is the default mode.\n * - **\"w\"** - write in truncate mode. Existing data will be overwritten.\n *\n * @class\n * @param {Db} db A database instance to interact with.\n * @param {object} [id] optional unique id for this file\n * @param {string} [filename] optional filename for this file, no unique constrain on the field\n * @param {string} mode set the mode for this file.\n * @param {object} [options] Optional settings.\n * @param {(number|string)} [options.w] The write concern.\n * @param {number} [options.wtimeout] The write concern timeout.\n * @param {boolean} [options.j=false] Specify a journal write concern.\n * @param {boolean} [options.fsync=false] Specify a file sync write concern.\n * @param {string} [options.root] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.\n * @param {string} [options.content_type] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**.\n * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**.\n * @param {object} [options.metadata] Arbitrary data the user wants to store.\n * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @property {number} chunkSize Get the gridstore chunk size.\n * @property {number} md5 The md5 checksum for this file.\n * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory\n * @return {GridStore} a GridStore instance.\n * @deprecated Use GridFSBucket API instead\n */\nvar GridStore = function GridStore(db, id, filename, mode, options) {\n deprecationFn();\n if (!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options);\n this.db = db;\n\n // Handle options\n if (typeof options === 'undefined') options = {};\n // Handle mode\n if (typeof mode === 'undefined') {\n mode = filename;\n filename = undefined;\n } else if (typeof mode === 'object') {\n options = mode;\n mode = filename;\n filename = undefined;\n }\n\n if (id && id._bsontype === 'ObjectID') {\n this.referenceBy = REFERENCE_BY_ID;\n this.fileId = id;\n this.filename = filename;\n } else if (typeof filename === 'undefined') {\n this.referenceBy = REFERENCE_BY_FILENAME;\n this.filename = id;\n if (mode.indexOf('w') != null) {\n this.fileId = new ObjectID();\n }\n } else {\n this.referenceBy = REFERENCE_BY_ID;\n this.fileId = id;\n this.filename = filename;\n }\n\n // Set up the rest\n this.mode = mode == null ? 'r' : mode;\n this.options = options || {};\n\n // Opened\n this.isOpen = false;\n\n // Set the root if overridden\n this.root =\n this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root'];\n this.position = 0;\n this.readPreference =\n this.options.readPreference || db.options.readPreference || ReadPreference.primary;\n this.writeConcern = _getWriteConcern(db, this.options);\n // Set default chunk size\n this.internalChunkSize =\n this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize'];\n\n // Get the promiseLibrary\n var promiseLibrary = this.options.promiseLibrary || Promise;\n\n // Set the promiseLibrary\n this.promiseLibrary = promiseLibrary;\n\n Object.defineProperty(this, 'chunkSize', {\n enumerable: true,\n get: function() {\n return this.internalChunkSize;\n },\n set: function(value) {\n if (!(this.mode[0] === 'w' && this.position === 0 && this.uploadDate == null)) {\n this.internalChunkSize = this.internalChunkSize;\n } else {\n this.internalChunkSize = value;\n }\n }\n });\n\n Object.defineProperty(this, 'md5', {\n enumerable: true,\n get: function() {\n return this.internalMd5;\n }\n });\n\n Object.defineProperty(this, 'chunkNumber', {\n enumerable: true,\n get: function() {\n return this.currentChunk && this.currentChunk.chunkNumber\n ? this.currentChunk.chunkNumber\n : null;\n }\n });\n};\n\n/**\n * The callback format for the Gridstore.open method\n * @callback GridStore~openCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {GridStore} gridStore The GridStore instance if the open method was successful.\n */\n\n/**\n * Opens the file from the database and initialize this object. Also creates a\n * new one if file does not exist.\n *\n * @method\n * @param {object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~openCallback} [callback] this will be called after executing this method\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.open = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n if (this.mode !== 'w' && this.mode !== 'w+' && this.mode !== 'r') {\n throw MongoError.create({ message: 'Illegal mode ' + this.mode, driver: true });\n }\n\n return executeLegacyOperation(this.db.s.topology, open, [this, options, callback], {\n skipSessions: true\n });\n};\n\nvar open = function(self, options, callback) {\n // Get the write concern\n var writeConcern = _getWriteConcern(self.db, self.options);\n\n // If we are writing we need to ensure we have the right indexes for md5's\n if (self.mode === 'w' || self.mode === 'w+') {\n // Get files collection\n var collection = self.collection();\n // Put index on filename\n collection.ensureIndex([['filename', 1]], writeConcern, function() {\n // Get chunk collection\n var chunkCollection = self.chunkCollection();\n // Make an unique index for compatibility with mongo-cxx-driver:legacy\n var chunkIndexOptions = shallowClone(writeConcern);\n chunkIndexOptions.unique = true;\n // Ensure index on chunk collection\n chunkCollection.ensureIndex(\n [\n ['files_id', 1],\n ['n', 1]\n ],\n chunkIndexOptions,\n function() {\n // Open the connection\n _open(self, writeConcern, function(err, r) {\n if (err) return callback(err);\n self.isOpen = true;\n callback(err, r);\n });\n }\n );\n });\n } else {\n // Open the gridstore\n _open(self, writeConcern, function(err, r) {\n if (err) return callback(err);\n self.isOpen = true;\n callback(err, r);\n });\n }\n};\n\n/**\n * Verify if the file is at EOF.\n *\n * @method\n * @return {boolean} true if the read/write head is at the end of this file.\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.eof = function() {\n return this.position === this.length ? true : false;\n};\n\n/**\n * The callback result format.\n * @callback GridStore~resultCallback\n * @param {object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {object} result The result from the callback.\n */\n\n/**\n * Retrieves a single character from this file.\n *\n * @method\n * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.getc = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeLegacyOperation(this.db.s.topology, getc, [this, options, callback], {\n skipSessions: true\n });\n};\n\nvar getc = function(self, options, callback) {\n if (self.eof()) {\n callback(null, null);\n } else if (self.currentChunk.eof()) {\n nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) {\n self.currentChunk = chunk;\n self.position = self.position + 1;\n callback(err, self.currentChunk.getc());\n });\n } else {\n self.position = self.position + 1;\n callback(null, self.currentChunk.getc());\n }\n};\n\n/**\n * Writes a string to the file with a newline character appended at the end if\n * the given string does not have one.\n *\n * @method\n * @param {string} string the string to write.\n * @param {object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.puts = function(string, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n var finalString = string.match(/\\n$/) == null ? string + '\\n' : string;\n return executeLegacyOperation(\n this.db.s.topology,\n this.write.bind(this),\n [finalString, options, callback],\n { skipSessions: true }\n );\n};\n\n/**\n * Return a modified Readable stream including a possible transform method.\n *\n * @method\n * @return {GridStoreStream}\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.stream = function() {\n return new GridStoreStream(this);\n};\n\n/**\n * Writes some data. This method will work properly only if initialized with mode \"w\" or \"w+\".\n *\n * @method\n * @param {(string|Buffer)} data the data to write.\n * @param {boolean} [close] closes this file after writing if set to true.\n * @param {object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.write = function write(data, close, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeLegacyOperation(\n this.db.s.topology,\n _writeNormal,\n [this, data, close, options, callback],\n { skipSessions: true }\n );\n};\n\n/**\n * Handles the destroy part of a stream\n *\n * @method\n * @result {null}\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.destroy = function destroy() {\n // close and do not emit any more events. queued data is not sent.\n if (!this.writable) return;\n this.readable = false;\n if (this.writable) {\n this.writable = false;\n this._q.length = 0;\n this.emit('close');\n }\n};\n\n/**\n * Stores a file from the file system to the GridFS database.\n *\n * @method\n * @param {(string|Buffer|FileHandle)} file the file to store.\n * @param {object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.writeFile = function(file, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeLegacyOperation(this.db.s.topology, writeFile, [this, file, options, callback], {\n skipSessions: true\n });\n};\n\nvar writeFile = function(self, file, options, callback) {\n if (typeof file === 'string') {\n fs.open(file, 'r', function(err, fd) {\n if (err) return callback(err);\n self.writeFile(fd, callback);\n });\n return;\n }\n\n self.open(function(err, self) {\n if (err) return callback(err, self);\n\n fs.fstat(file, function(err, stats) {\n if (err) return callback(err, self);\n\n var offset = 0;\n var index = 0;\n\n // Write a chunk\n var writeChunk = function() {\n // Allocate the buffer\n var _buffer = Buffer.alloc(self.chunkSize);\n // Read the file\n fs.read(file, _buffer, 0, _buffer.length, offset, function(err, bytesRead, data) {\n if (err) return callback(err, self);\n\n offset = offset + bytesRead;\n\n // Create a new chunk for the data\n var chunk = new Chunk(self, { n: index++ }, self.writeConcern);\n chunk.write(data.slice(0, bytesRead), function(err, chunk) {\n if (err) return callback(err, self);\n\n chunk.save({}, function(err) {\n if (err) return callback(err, self);\n\n self.position = self.position + bytesRead;\n\n // Point to current chunk\n self.currentChunk = chunk;\n\n if (offset >= stats.size) {\n fs.close(file, function(err) {\n if (err) return callback(err);\n\n self.close(function(err) {\n if (err) return callback(err, self);\n return callback(null, self);\n });\n });\n } else {\n return process.nextTick(writeChunk);\n }\n });\n });\n });\n };\n\n // Process the first write\n process.nextTick(writeChunk);\n });\n });\n};\n\n/**\n * Saves this file to the database. This will overwrite the old entry if it\n * already exists. This will work properly only if mode was initialized to\n * \"w\" or \"w+\".\n *\n * @method\n * @param {object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.close = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeLegacyOperation(this.db.s.topology, close, [this, options, callback], {\n skipSessions: true\n });\n};\n\nvar close = function(self, options, callback) {\n if (self.mode[0] === 'w') {\n // Set up options\n options = Object.assign({}, self.writeConcern, options);\n\n if (self.currentChunk != null && self.currentChunk.position > 0) {\n self.currentChunk.save({}, function(err) {\n if (err && typeof callback === 'function') return callback(err);\n\n self.collection(function(err, files) {\n if (err && typeof callback === 'function') return callback(err);\n\n // Build the mongo object\n if (self.uploadDate != null) {\n buildMongoObject(self, function(err, mongoObject) {\n if (err) {\n if (typeof callback === 'function') return callback(err);\n else throw err;\n }\n\n files.save(mongoObject, options, function(err) {\n if (typeof callback === 'function') callback(err, mongoObject);\n });\n });\n } else {\n self.uploadDate = new Date();\n buildMongoObject(self, function(err, mongoObject) {\n if (err) {\n if (typeof callback === 'function') return callback(err);\n else throw err;\n }\n\n files.save(mongoObject, options, function(err) {\n if (typeof callback === 'function') callback(err, mongoObject);\n });\n });\n }\n });\n });\n } else {\n self.collection(function(err, files) {\n if (err && typeof callback === 'function') return callback(err);\n\n self.uploadDate = new Date();\n buildMongoObject(self, function(err, mongoObject) {\n if (err) {\n if (typeof callback === 'function') return callback(err);\n else throw err;\n }\n\n files.save(mongoObject, options, function(err) {\n if (typeof callback === 'function') callback(err, mongoObject);\n });\n });\n });\n }\n } else if (self.mode[0] === 'r') {\n if (typeof callback === 'function') callback(null, null);\n } else {\n if (typeof callback === 'function')\n callback(MongoError.create({ message: f('Illegal mode %s', self.mode), driver: true }));\n }\n};\n\n/**\n * The collection callback format.\n * @callback GridStore~collectionCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {Collection} collection The collection from the command execution.\n */\n\n/**\n * Retrieve this file's chunks collection.\n *\n * @method\n * @param {GridStore~collectionCallback} callback the command callback.\n * @return {Collection}\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.chunkCollection = function(callback) {\n if (typeof callback === 'function') return this.db.collection(this.root + '.chunks', callback);\n return this.db.collection(this.root + '.chunks');\n};\n\n/**\n * Deletes all the chunks of this file in the database.\n *\n * @method\n * @param {object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~resultCallback} [callback] the command callback.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.unlink = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeLegacyOperation(this.db.s.topology, unlink, [this, options, callback], {\n skipSessions: true\n });\n};\n\nvar unlink = function(self, options, callback) {\n deleteChunks(self, function(err) {\n if (err !== null) {\n err.message = 'at deleteChunks: ' + err.message;\n return callback(err);\n }\n\n self.collection(function(err, collection) {\n if (err !== null) {\n err.message = 'at collection: ' + err.message;\n return callback(err);\n }\n\n collection.remove({ _id: self.fileId }, self.writeConcern, function(err) {\n callback(err, self);\n });\n });\n });\n};\n\n/**\n * Retrieves the file collection associated with this object.\n *\n * @method\n * @param {GridStore~collectionCallback} callback the command callback.\n * @return {Collection}\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.collection = function(callback) {\n if (typeof callback === 'function') this.db.collection(this.root + '.files', callback);\n return this.db.collection(this.root + '.files');\n};\n\n/**\n * The readlines callback format.\n * @callback GridStore~readlinesCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {string[]} strings The array of strings returned.\n */\n\n/**\n * Read the entire file as a list of strings splitting by the provided separator.\n *\n * @method\n * @param {string} [separator] The character to be recognized as the newline separator.\n * @param {object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~readlinesCallback} [callback] the command callback.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.readlines = function(separator, options, callback) {\n var args = Array.prototype.slice.call(arguments, 0);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n separator = args.length ? args.shift() : '\\n';\n separator = separator || '\\n';\n options = args.length ? args.shift() : {};\n\n return executeLegacyOperation(\n this.db.s.topology,\n readlines,\n [this, separator, options, callback],\n { skipSessions: true }\n );\n};\n\nvar readlines = function(self, separator, options, callback) {\n self.read(function(err, data) {\n if (err) return callback(err);\n\n var items = data.toString().split(separator);\n items = items.length > 0 ? items.splice(0, items.length - 1) : [];\n for (var i = 0; i < items.length; i++) {\n items[i] = items[i] + separator;\n }\n\n callback(null, items);\n });\n};\n\n/**\n * Deletes all the chunks of this file in the database if mode was set to \"w\" or\n * \"w+\" and resets the read/write head to the initial position.\n *\n * @method\n * @param {object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.rewind = function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n return executeLegacyOperation(this.db.s.topology, rewind, [this, options, callback], {\n skipSessions: true\n });\n};\n\nvar rewind = function(self, options, callback) {\n if (self.currentChunk.chunkNumber !== 0) {\n if (self.mode[0] === 'w') {\n deleteChunks(self, function(err) {\n if (err) return callback(err);\n self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern);\n self.position = 0;\n callback(null, self);\n });\n } else {\n self.currentChunk(0, function(err, chunk) {\n if (err) return callback(err);\n self.currentChunk = chunk;\n self.currentChunk.rewind();\n self.position = 0;\n callback(null, self);\n });\n }\n } else {\n self.currentChunk.rewind();\n self.position = 0;\n callback(null, self);\n }\n};\n\n/**\n * The read callback format.\n * @callback GridStore~readCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {Buffer} data The data read from the GridStore object\n */\n\n/**\n * Retrieves the contents of this file and advances the read/write head. Works with Buffers only.\n *\n * There are 3 signatures for this method:\n *\n * (callback)\n * (length, callback)\n * (length, buffer, callback)\n *\n * @method\n * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified.\n * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method.\n * @param {object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~readCallback} [callback] the command callback.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.read = function(length, buffer, options, callback) {\n var args = Array.prototype.slice.call(arguments, 0);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n length = args.length ? args.shift() : null;\n buffer = args.length ? args.shift() : null;\n options = args.length ? args.shift() : {};\n\n return executeLegacyOperation(\n this.db.s.topology,\n read,\n [this, length, buffer, options, callback],\n { skipSessions: true }\n );\n};\n\nvar read = function(self, length, buffer, options, callback) {\n // The data is a c-terminated string and thus the length - 1\n var finalLength = length == null ? self.length - self.position : length;\n var finalBuffer = buffer == null ? Buffer.alloc(finalLength) : buffer;\n // Add a index to buffer to keep track of writing position or apply current index\n finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0;\n\n if (self.currentChunk.length() - self.currentChunk.position + finalBuffer._index >= finalLength) {\n var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index);\n // Copy content to final buffer\n slice.copy(finalBuffer, finalBuffer._index);\n // Update internal position\n self.position = self.position + finalBuffer.length;\n // Check if we don't have a file at all\n if (finalLength === 0 && finalBuffer.length === 0)\n return callback(MongoError.create({ message: 'File does not exist', driver: true }), null);\n // Else return data\n return callback(null, finalBuffer);\n }\n\n // Read the next chunk\n slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position);\n // Copy content to final buffer\n slice.copy(finalBuffer, finalBuffer._index);\n // Update index position\n finalBuffer._index += slice.length;\n\n // Load next chunk and read more\n nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) {\n if (err) return callback(err);\n\n if (chunk.length() > 0) {\n self.currentChunk = chunk;\n self.read(length, finalBuffer, callback);\n } else {\n if (finalBuffer._index > 0) {\n callback(null, finalBuffer);\n } else {\n callback(\n MongoError.create({\n message: 'no chunks found for file, possibly corrupt',\n driver: true\n }),\n null\n );\n }\n }\n });\n};\n\n/**\n * The tell callback format.\n * @callback GridStore~tellCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {number} position The current read position in the GridStore.\n */\n\n/**\n * Retrieves the position of the read/write head of this file.\n *\n * @method\n * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified.\n * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method.\n * @param {object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~tellCallback} [callback] the command callback.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.tell = function(callback) {\n var self = this;\n // We provided a callback leg\n if (typeof callback === 'function') return callback(null, this.position);\n // Return promise\n return new self.promiseLibrary(function(resolve) {\n resolve(self.position);\n });\n};\n\n/**\n * The tell callback format.\n * @callback GridStore~gridStoreCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {GridStore} gridStore The gridStore.\n */\n\n/**\n * Moves the read/write head to a new location.\n *\n * There are 3 signatures for this method\n *\n * Seek Location Modes\n * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file.\n * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file.\n * - **GridStore.IO_SEEK_END**, set the position from the end of the file.\n *\n * @method\n * @param {number} [position] the position to seek to\n * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes.\n * @param {object} [options] Optional settings\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~gridStoreCallback} [callback] the command callback.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.prototype.seek = function(position, seekLocation, options, callback) {\n var args = Array.prototype.slice.call(arguments, 1);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n seekLocation = args.length ? args.shift() : null;\n options = args.length ? args.shift() : {};\n\n return executeLegacyOperation(\n this.db.s.topology,\n seek,\n [this, position, seekLocation, options, callback],\n { skipSessions: true }\n );\n};\n\nvar seek = function(self, position, seekLocation, options, callback) {\n // Seek only supports read mode\n if (self.mode !== 'r') {\n return callback(\n MongoError.create({ message: 'seek is only supported for mode r', driver: true })\n );\n }\n\n var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation;\n var finalPosition = position;\n var targetPosition = 0;\n\n // Calculate the position\n if (seekLocationFinal === GridStore.IO_SEEK_CUR) {\n targetPosition = self.position + finalPosition;\n } else if (seekLocationFinal === GridStore.IO_SEEK_END) {\n targetPosition = self.length + finalPosition;\n } else {\n targetPosition = finalPosition;\n }\n\n // Get the chunk\n var newChunkNumber = Math.floor(targetPosition / self.chunkSize);\n var seekChunk = function() {\n nthChunk(self, newChunkNumber, function(err, chunk) {\n if (err) return callback(err, null);\n if (chunk == null) return callback(new Error('no chunk found'));\n\n // Set the current chunk\n self.currentChunk = chunk;\n self.position = targetPosition;\n self.currentChunk.position = self.position % self.chunkSize;\n callback(err, self);\n });\n };\n\n seekChunk();\n};\n\n/**\n * @ignore\n */\nvar _open = function(self, options, callback) {\n var collection = self.collection();\n // Create the query\n var query =\n self.referenceBy === REFERENCE_BY_ID ? { _id: self.fileId } : { filename: self.filename };\n query = null == self.fileId && self.filename == null ? null : query;\n options.readPreference = self.readPreference;\n\n // Fetch the chunks\n if (query != null) {\n collection.findOne(query, options, function(err, doc) {\n if (err) {\n return error(err);\n }\n\n // Check if the collection for the files exists otherwise prepare the new one\n if (doc != null) {\n self.fileId = doc._id;\n // Prefer a new filename over the existing one if this is a write\n self.filename =\n self.mode === 'r' || self.filename === undefined ? doc.filename : self.filename;\n self.contentType = doc.contentType;\n self.internalChunkSize = doc.chunkSize;\n self.uploadDate = doc.uploadDate;\n self.aliases = doc.aliases;\n self.length = doc.length;\n self.metadata = doc.metadata;\n self.internalMd5 = doc.md5;\n } else if (self.mode !== 'r') {\n self.fileId = self.fileId == null ? new ObjectID() : self.fileId;\n self.contentType = GridStore.DEFAULT_CONTENT_TYPE;\n self.internalChunkSize =\n self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize;\n self.length = 0;\n } else {\n self.length = 0;\n var txtId = self.fileId._bsontype === 'ObjectID' ? self.fileId.toHexString() : self.fileId;\n return error(\n MongoError.create({\n message: f(\n 'file with id %s not opened for writing',\n self.referenceBy === REFERENCE_BY_ID ? txtId : self.filename\n ),\n driver: true\n }),\n self\n );\n }\n\n // Process the mode of the object\n if (self.mode === 'r') {\n nthChunk(self, 0, options, function(err, chunk) {\n if (err) return error(err);\n self.currentChunk = chunk;\n self.position = 0;\n callback(null, self);\n });\n } else if (self.mode === 'w' && doc) {\n // Delete any existing chunks\n deleteChunks(self, options, function(err) {\n if (err) return error(err);\n self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern);\n self.contentType =\n self.options['content_type'] == null ? self.contentType : self.options['content_type'];\n self.internalChunkSize =\n self.options['chunk_size'] == null\n ? self.internalChunkSize\n : self.options['chunk_size'];\n self.metadata =\n self.options['metadata'] == null ? self.metadata : self.options['metadata'];\n self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];\n self.position = 0;\n callback(null, self);\n });\n } else if (self.mode === 'w') {\n self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern);\n self.contentType =\n self.options['content_type'] == null ? self.contentType : self.options['content_type'];\n self.internalChunkSize =\n self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size'];\n self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];\n self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];\n self.position = 0;\n callback(null, self);\n } else if (self.mode === 'w+') {\n nthChunk(self, lastChunkNumber(self), options, function(err, chunk) {\n if (err) return error(err);\n // Set the current chunk\n self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk;\n self.currentChunk.position = self.currentChunk.data.length();\n self.metadata =\n self.options['metadata'] == null ? self.metadata : self.options['metadata'];\n self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];\n self.position = self.length;\n callback(null, self);\n });\n }\n });\n } else {\n // Write only mode\n self.fileId = null == self.fileId ? new ObjectID() : self.fileId;\n self.contentType = GridStore.DEFAULT_CONTENT_TYPE;\n self.internalChunkSize =\n self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize;\n self.length = 0;\n\n // No file exists set up write mode\n if (self.mode === 'w') {\n // Delete any existing chunks\n deleteChunks(self, options, function(err) {\n if (err) return error(err);\n self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern);\n self.contentType =\n self.options['content_type'] == null ? self.contentType : self.options['content_type'];\n self.internalChunkSize =\n self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size'];\n self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];\n self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];\n self.position = 0;\n callback(null, self);\n });\n } else if (self.mode === 'w+') {\n nthChunk(self, lastChunkNumber(self), options, function(err, chunk) {\n if (err) return error(err);\n // Set the current chunk\n self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk;\n self.currentChunk.position = self.currentChunk.data.length();\n self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];\n self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];\n self.position = self.length;\n callback(null, self);\n });\n }\n }\n\n // only pass error to callback once\n function error(err) {\n if (error.err) return;\n callback((error.err = err));\n }\n};\n\n/**\n * @ignore\n */\nvar writeBuffer = function(self, buffer, close, callback) {\n if (typeof close === 'function') {\n callback = close;\n close = null;\n }\n var finalClose = typeof close === 'boolean' ? close : false;\n\n if (self.mode !== 'w') {\n callback(\n MongoError.create({\n message: f(\n 'file with id %s not opened for writing',\n self.referenceBy === REFERENCE_BY_ID ? self.referenceBy : self.filename\n ),\n driver: true\n }),\n null\n );\n } else {\n if (self.currentChunk.position + buffer.length >= self.chunkSize) {\n // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left\n // to a new chunk (recursively)\n var previousChunkNumber = self.currentChunk.chunkNumber;\n var leftOverDataSize = self.chunkSize - self.currentChunk.position;\n var firstChunkData = buffer.slice(0, leftOverDataSize);\n var leftOverData = buffer.slice(leftOverDataSize);\n // A list of chunks to write out\n var chunksToWrite = [self.currentChunk.write(firstChunkData)];\n // If we have more data left than the chunk size let's keep writing new chunks\n while (leftOverData.length >= self.chunkSize) {\n // Create a new chunk and write to it\n var newChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern);\n firstChunkData = leftOverData.slice(0, self.chunkSize);\n leftOverData = leftOverData.slice(self.chunkSize);\n // Update chunk number\n previousChunkNumber = previousChunkNumber + 1;\n // Write data\n newChunk.write(firstChunkData);\n // Push chunk to save list\n chunksToWrite.push(newChunk);\n }\n\n // Set current chunk with remaining data\n self.currentChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern);\n // If we have left over data write it\n if (leftOverData.length > 0) self.currentChunk.write(leftOverData);\n\n // Update the position for the gridstore\n self.position = self.position + buffer.length;\n // Total number of chunks to write\n var numberOfChunksToWrite = chunksToWrite.length;\n\n for (var i = 0; i < chunksToWrite.length; i++) {\n chunksToWrite[i].save({}, function(err) {\n if (err) return callback(err);\n\n numberOfChunksToWrite = numberOfChunksToWrite - 1;\n\n if (numberOfChunksToWrite <= 0) {\n // We care closing the file before returning\n if (finalClose) {\n return self.close(function(err) {\n callback(err, self);\n });\n }\n\n // Return normally\n return callback(null, self);\n }\n });\n }\n } else {\n // Update the position for the gridstore\n self.position = self.position + buffer.length;\n // We have less data than the chunk size just write it and callback\n self.currentChunk.write(buffer);\n // We care closing the file before returning\n if (finalClose) {\n return self.close(function(err) {\n callback(err, self);\n });\n }\n // Return normally\n return callback(null, self);\n }\n }\n};\n\n/**\n * Creates a mongoDB object representation of this object.\n *\n *
\n *        {\n *          '_id' : , // {number} id for this file\n *          'filename' : , // {string} name for this file\n *          'contentType' : , // {string} mime type for this file\n *          'length' : , // {number} size of this file?\n *          'chunksize' : , // {number} chunk size used by this file\n *          'uploadDate' : , // {Date}\n *          'aliases' : , // {array of string}\n *          'metadata' : , // {string}\n *        }\n *        
\n *\n * @ignore\n */\nvar buildMongoObject = function(self, callback) {\n // Calcuate the length\n var mongoObject = {\n _id: self.fileId,\n filename: self.filename,\n contentType: self.contentType,\n length: self.position ? self.position : 0,\n chunkSize: self.chunkSize,\n uploadDate: self.uploadDate,\n aliases: self.aliases,\n metadata: self.metadata\n };\n\n var md5Command = { filemd5: self.fileId, root: self.root };\n self.db.command(md5Command, function(err, results) {\n if (err) return callback(err);\n\n mongoObject.md5 = results.md5;\n callback(null, mongoObject);\n });\n};\n\n/**\n * Gets the nth chunk of this file.\n * @ignore\n */\nvar nthChunk = function(self, chunkNumber, options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n options = options || self.writeConcern;\n options.readPreference = self.readPreference;\n // Get the nth chunk\n self\n .chunkCollection()\n .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) {\n if (err) return callback(err);\n\n var finalChunk = chunk == null ? {} : chunk;\n callback(null, new Chunk(self, finalChunk, self.writeConcern));\n });\n};\n\n/**\n * @ignore\n */\nvar lastChunkNumber = function(self) {\n return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize);\n};\n\n/**\n * Deletes all the chunks of this file in the database.\n *\n * @ignore\n */\nvar deleteChunks = function(self, options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n options = options || self.writeConcern;\n\n if (self.fileId != null) {\n self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) {\n if (err) return callback(err, false);\n callback(null, true);\n });\n } else {\n callback(null, true);\n }\n};\n\n/**\n * The collection to be used for holding the files and chunks collection.\n *\n * @classconstant DEFAULT_ROOT_COLLECTION\n */\nGridStore.DEFAULT_ROOT_COLLECTION = 'fs';\n\n/**\n * Default file mime type\n *\n * @classconstant DEFAULT_CONTENT_TYPE\n */\nGridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream';\n\n/**\n * Seek mode where the given length is absolute.\n *\n * @classconstant IO_SEEK_SET\n */\nGridStore.IO_SEEK_SET = 0;\n\n/**\n * Seek mode where the given length is an offset to the current read/write head.\n *\n * @classconstant IO_SEEK_CUR\n */\nGridStore.IO_SEEK_CUR = 1;\n\n/**\n * Seek mode where the given length is an offset to the end of the file.\n *\n * @classconstant IO_SEEK_END\n */\nGridStore.IO_SEEK_END = 2;\n\n/**\n * Checks if a file exists in the database.\n *\n * @method\n * @static\n * @param {Db} db the database to query.\n * @param {string} name The name of the file to look for.\n * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~resultCallback} [callback] result from exists.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.exist = function(db, fileIdObject, rootCollection, options, callback) {\n var args = Array.prototype.slice.call(arguments, 2);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n rootCollection = args.length ? args.shift() : null;\n options = args.length ? args.shift() : {};\n options = options || {};\n\n return executeLegacyOperation(\n db.s.topology,\n exists,\n [db, fileIdObject, rootCollection, options, callback],\n { skipSessions: true }\n );\n};\n\nvar exists = function(db, fileIdObject, rootCollection, options, callback) {\n // Establish read preference\n var readPreference = options.readPreference || ReadPreference.PRIMARY;\n // Fetch collection\n var rootCollectionFinal =\n rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION;\n db.collection(rootCollectionFinal + '.files', function(err, collection) {\n if (err) return callback(err);\n\n // Build query\n var query =\n typeof fileIdObject === 'string' ||\n Object.prototype.toString.call(fileIdObject) === '[object RegExp]'\n ? { filename: fileIdObject }\n : { _id: fileIdObject }; // Attempt to locate file\n\n // We have a specific query\n if (\n fileIdObject != null &&\n typeof fileIdObject === 'object' &&\n Object.prototype.toString.call(fileIdObject) !== '[object RegExp]'\n ) {\n query = fileIdObject;\n }\n\n // Check if the entry exists\n collection.findOne(query, { readPreference: readPreference }, function(err, item) {\n if (err) return callback(err);\n callback(null, item == null ? false : true);\n });\n });\n};\n\n/**\n * Gets the list of files stored in the GridFS.\n *\n * @method\n * @static\n * @param {Db} db the database to query.\n * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~resultCallback} [callback] result from exists.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.list = function(db, rootCollection, options, callback) {\n var args = Array.prototype.slice.call(arguments, 1);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n rootCollection = args.length ? args.shift() : null;\n options = args.length ? args.shift() : {};\n options = options || {};\n\n return executeLegacyOperation(db.s.topology, list, [db, rootCollection, options, callback], {\n skipSessions: true\n });\n};\n\nvar list = function(db, rootCollection, options, callback) {\n // Ensure we have correct values\n if (rootCollection != null && typeof rootCollection === 'object') {\n options = rootCollection;\n rootCollection = null;\n }\n\n // Establish read preference\n var readPreference = options.readPreference || ReadPreference.primary;\n // Check if we are returning by id not filename\n var byId = options['id'] != null ? options['id'] : false;\n // Fetch item\n var rootCollectionFinal =\n rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION;\n var items = [];\n db.collection(rootCollectionFinal + '.files', function(err, collection) {\n if (err) return callback(err);\n\n collection.find({}, { readPreference: readPreference }, function(err, cursor) {\n if (err) return callback(err);\n\n cursor.each(function(err, item) {\n if (item != null) {\n items.push(byId ? item._id : item.filename);\n } else {\n callback(err, items);\n }\n });\n });\n });\n};\n\n/**\n * Reads the contents of a file.\n *\n * This method has the following signatures\n *\n * (db, name, callback)\n * (db, name, length, callback)\n * (db, name, length, offset, callback)\n * (db, name, length, offset, options, callback)\n *\n * @method\n * @static\n * @param {Db} db the database to query.\n * @param {string} name The name of the file.\n * @param {number} [length] The size of data to read.\n * @param {number} [offset] The offset from the head of the file of which to start reading from.\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~readCallback} [callback] the command callback.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.read = function(db, name, length, offset, options, callback) {\n var args = Array.prototype.slice.call(arguments, 2);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n length = args.length ? args.shift() : null;\n offset = args.length ? args.shift() : null;\n options = args.length ? args.shift() : null;\n options = options || {};\n\n return executeLegacyOperation(\n db.s.topology,\n readStatic,\n [db, name, length, offset, options, callback],\n { skipSessions: true }\n );\n};\n\nvar readStatic = function(db, name, length, offset, options, callback) {\n new GridStore(db, name, 'r', options).open(function(err, gridStore) {\n if (err) return callback(err);\n // Make sure we are not reading out of bounds\n if (offset && offset >= gridStore.length)\n return callback('offset larger than size of file', null);\n if (length && length > gridStore.length)\n return callback('length is larger than the size of the file', null);\n if (offset && length && offset + length > gridStore.length)\n return callback('offset and length is larger than the size of the file', null);\n\n if (offset != null) {\n gridStore.seek(offset, function(err, gridStore) {\n if (err) return callback(err);\n gridStore.read(length, callback);\n });\n } else {\n gridStore.read(length, callback);\n }\n });\n};\n\n/**\n * Read the entire file as a list of strings splitting by the provided separator.\n *\n * @method\n * @static\n * @param {Db} db the database to query.\n * @param {(String|object)} name the name of the file.\n * @param {string} [separator] The character to be recognized as the newline separator.\n * @param {object} [options] Optional settings.\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~readlinesCallback} [callback] the command callback.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.readlines = function(db, name, separator, options, callback) {\n var args = Array.prototype.slice.call(arguments, 2);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n separator = args.length ? args.shift() : null;\n options = args.length ? args.shift() : null;\n options = options || {};\n\n return executeLegacyOperation(\n db.s.topology,\n readlinesStatic,\n [db, name, separator, options, callback],\n { skipSessions: true }\n );\n};\n\nvar readlinesStatic = function(db, name, separator, options, callback) {\n var finalSeperator = separator == null ? '\\n' : separator;\n new GridStore(db, name, 'r', options).open(function(err, gridStore) {\n if (err) return callback(err);\n gridStore.readlines(finalSeperator, callback);\n });\n};\n\n/**\n * Deletes the chunks and metadata information of a file from GridFS.\n *\n * @method\n * @static\n * @param {Db} db The database to query.\n * @param {(string|array)} names The name/names of the files to delete.\n * @param {object} [options] Optional settings.\n * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @param {GridStore~resultCallback} [callback] the command callback.\n * @return {Promise} returns Promise if no callback passed\n * @deprecated Use GridFSBucket API instead\n */\nGridStore.unlink = function(db, names, options, callback) {\n var args = Array.prototype.slice.call(arguments, 2);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n options = args.length ? args.shift() : {};\n options = options || {};\n\n return executeLegacyOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], {\n skipSessions: true\n });\n};\n\nvar unlinkStatic = function(self, db, names, options, callback) {\n // Get the write concern\n var writeConcern = _getWriteConcern(db, options);\n\n // List of names\n if (names.constructor === Array) {\n var tc = 0;\n for (var i = 0; i < names.length; i++) {\n ++tc;\n GridStore.unlink(db, names[i], options, function() {\n if (--tc === 0) {\n callback(null, self);\n }\n });\n }\n } else {\n new GridStore(db, names, 'w', options).open(function(err, gridStore) {\n if (err) return callback(err);\n deleteChunks(gridStore, function(err) {\n if (err) return callback(err);\n gridStore.collection(function(err, collection) {\n if (err) return callback(err);\n collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) {\n callback(err, self);\n });\n });\n });\n });\n }\n};\n\n/**\n * @ignore\n */\nvar _writeNormal = function(self, data, close, options, callback) {\n // If we have a buffer write it using the writeBuffer method\n if (Buffer.isBuffer(data)) {\n return writeBuffer(self, data, close, callback);\n } else {\n return writeBuffer(self, Buffer.from(data, 'binary'), close, callback);\n }\n};\n\n/**\n * @ignore\n */\nvar _setWriteConcernHash = function(options) {\n var finalOptions = {};\n if (options.w != null) finalOptions.w = options.w;\n if (options.journal === true) finalOptions.j = options.journal;\n if (options.j === true) finalOptions.j = options.j;\n if (options.fsync === true) finalOptions.fsync = options.fsync;\n if (options.wtimeout != null) finalOptions.wtimeout = options.wtimeout;\n return finalOptions;\n};\n\n/**\n * @ignore\n */\nvar _getWriteConcern = function(self, options) {\n // Final options\n var finalOptions = { w: 1 };\n options = options || {};\n\n // Local options verification\n if (\n options.w != null ||\n typeof options.j === 'boolean' ||\n typeof options.journal === 'boolean' ||\n typeof options.fsync === 'boolean'\n ) {\n finalOptions = _setWriteConcernHash(options);\n } else if (options.safe != null && typeof options.safe === 'object') {\n finalOptions = _setWriteConcernHash(options.safe);\n } else if (typeof options.safe === 'boolean') {\n finalOptions = { w: options.safe ? 1 : 0 };\n } else if (\n self.options.w != null ||\n typeof self.options.j === 'boolean' ||\n typeof self.options.journal === 'boolean' ||\n typeof self.options.fsync === 'boolean'\n ) {\n finalOptions = _setWriteConcernHash(self.options);\n } else if (\n self.safe &&\n (self.safe.w != null ||\n typeof self.safe.j === 'boolean' ||\n typeof self.safe.journal === 'boolean' ||\n typeof self.safe.fsync === 'boolean')\n ) {\n finalOptions = _setWriteConcernHash(self.safe);\n } else if (typeof self.safe === 'boolean') {\n finalOptions = { w: self.safe ? 1 : 0 };\n }\n\n // Ensure we don't have an invalid combination of write concerns\n if (\n finalOptions.w < 1 &&\n (finalOptions.journal === true || finalOptions.j === true || finalOptions.fsync === true)\n )\n throw MongoError.create({\n message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true',\n driver: true\n });\n\n // Return the options\n return finalOptions;\n};\n\n/**\n * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly)\n *\n * @class\n * @extends external:Duplex\n * @return {GridStoreStream} a GridStoreStream instance.\n * @deprecated Use GridFSBucket API instead\n */\nvar GridStoreStream = function(gs) {\n // Initialize the duplex stream\n Duplex.call(this);\n\n // Get the gridstore\n this.gs = gs;\n\n // End called\n this.endCalled = false;\n\n // If we have a seek\n this.totalBytesToRead = this.gs.length - this.gs.position;\n this.seekPosition = this.gs.position;\n};\n\n//\n// Inherit duplex\ninherits(GridStoreStream, Duplex);\n\nGridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe;\n\n// Set up override\nGridStoreStream.prototype.pipe = function(destination) {\n var self = this;\n\n // Only open gridstore if not already open\n if (!self.gs.isOpen) {\n self.gs.open(function(err) {\n if (err) return self.emit('error', err);\n self.totalBytesToRead = self.gs.length - self.gs.position;\n self._pipe.apply(self, [destination]);\n });\n } else {\n self.totalBytesToRead = self.gs.length - self.gs.position;\n self._pipe.apply(self, [destination]);\n }\n\n return destination;\n};\n\n// Called by stream\nGridStoreStream.prototype._read = function() {\n var self = this;\n\n var read = function() {\n // Read data\n self.gs.read(length, function(err, buffer) {\n if (err && !self.endCalled) return self.emit('error', err);\n\n // Stream is closed\n if (self.endCalled || buffer == null) return self.push(null);\n // Remove bytes read\n if (buffer.length <= self.totalBytesToRead) {\n self.totalBytesToRead = self.totalBytesToRead - buffer.length;\n self.push(buffer);\n } else if (buffer.length > self.totalBytesToRead) {\n self.totalBytesToRead = self.totalBytesToRead - buffer._index;\n self.push(buffer.slice(0, buffer._index));\n }\n\n // Finished reading\n if (self.totalBytesToRead <= 0) {\n self.endCalled = true;\n }\n });\n };\n\n // Set read length\n var length =\n self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize;\n if (!self.gs.isOpen) {\n self.gs.open(function(err) {\n self.totalBytesToRead = self.gs.length - self.gs.position;\n if (err) return self.emit('error', err);\n read();\n });\n } else {\n read();\n }\n};\n\nGridStoreStream.prototype.destroy = function() {\n this.pause();\n this.endCalled = true;\n this.gs.close();\n this.emit('end');\n};\n\nGridStoreStream.prototype.write = function(chunk) {\n var self = this;\n if (self.endCalled)\n return self.emit(\n 'error',\n MongoError.create({ message: 'attempting to write to stream after end called', driver: true })\n );\n // Do we have to open the gridstore\n if (!self.gs.isOpen) {\n self.gs.open(function() {\n self.gs.isOpen = true;\n self.gs.write(chunk, function() {\n process.nextTick(function() {\n self.emit('drain');\n });\n });\n });\n return false;\n } else {\n self.gs.write(chunk, function() {\n self.emit('drain');\n });\n return true;\n }\n};\n\nGridStoreStream.prototype.end = function(chunk, encoding, callback) {\n var self = this;\n var args = Array.prototype.slice.call(arguments, 0);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n chunk = args.length ? args.shift() : null;\n encoding = args.length ? args.shift() : null;\n self.endCalled = true;\n\n if (chunk) {\n self.gs.write(chunk, function() {\n self.gs.close(function() {\n if (typeof callback === 'function') callback();\n self.emit('end');\n });\n });\n }\n\n self.gs.close(function() {\n if (typeof callback === 'function') callback();\n self.emit('end');\n });\n};\n\n/**\n * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.\n * @function external:Duplex#read\n * @param {number} size Optional argument to specify how much data to read.\n * @return {(String | Buffer | null)}\n */\n\n/**\n * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.\n * @function external:Duplex#setEncoding\n * @param {string} encoding The encoding to use.\n * @return {null}\n */\n\n/**\n * This method will cause the readable stream to resume emitting data events.\n * @function external:Duplex#resume\n * @return {null}\n */\n\n/**\n * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.\n * @function external:Duplex#pause\n * @return {null}\n */\n\n/**\n * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.\n * @function external:Duplex#pipe\n * @param {Writable} destination The destination for writing data\n * @param {object} [options] Pipe options\n * @return {null}\n */\n\n/**\n * This method will remove the hooks set up for a previous pipe() call.\n * @function external:Duplex#unpipe\n * @param {Writable} [destination] The destination for writing data\n * @return {null}\n */\n\n/**\n * This is useful in certain cases where a stream is being consumed by a parser, which needs to \"un-consume\" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.\n * @function external:Duplex#unshift\n * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue.\n * @return {null}\n */\n\n/**\n * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See \"Compatibility\" below for more information.)\n * @function external:Duplex#wrap\n * @param {Stream} stream An \"old style\" readable stream.\n * @return {null}\n */\n\n/**\n * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled.\n * @function external:Duplex#write\n * @param {(string|Buffer)} chunk The data to write\n * @param {string} encoding The encoding, if chunk is a String\n * @param {function} callback Callback for when this chunk of data is flushed\n * @return {boolean}\n */\n\n/**\n * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event.\n * @function external:Duplex#end\n * @param {(string|Buffer)} chunk The data to write\n * @param {string} encoding The encoding, if chunk is a String\n * @param {function} callback Callback for when this chunk of data is flushed\n * @return {null}\n */\n\n/**\n * GridStoreStream stream data event, fired for each document in the cursor.\n *\n * @event GridStoreStream#data\n * @type {object}\n */\n\n/**\n * GridStoreStream stream end event\n *\n * @event GridStoreStream#end\n * @type {null}\n */\n\n/**\n * GridStoreStream stream close event\n *\n * @event GridStoreStream#close\n * @type {null}\n */\n\n/**\n * GridStoreStream stream readable event\n *\n * @event GridStoreStream#readable\n * @type {null}\n */\n\n/**\n * GridStoreStream stream drain event\n *\n * @event GridStoreStream#drain\n * @type {null}\n */\n\n/**\n * GridStoreStream stream finish event\n *\n * @event GridStoreStream#finish\n * @type {null}\n */\n\n/**\n * GridStoreStream stream pipe event\n *\n * @event GridStoreStream#pipe\n * @type {null}\n */\n\n/**\n * GridStoreStream stream unpipe event\n *\n * @event GridStoreStream#unpipe\n * @type {null}\n */\n\n/**\n * GridStoreStream stream error event\n *\n * @event GridStoreStream#error\n * @type {null}\n */\n\n/**\n * @ignore\n */\nmodule.exports = GridStore;\n","'use strict';\n\nconst ChangeStream = require('./change_stream');\nconst Db = require('./db');\nconst EventEmitter = require('events').EventEmitter;\nconst inherits = require('util').inherits;\nconst MongoError = require('./core').MongoError;\nconst deprecate = require('util').deprecate;\nconst WriteConcern = require('./write_concern');\nconst MongoDBNamespace = require('./utils').MongoDBNamespace;\nconst ReadPreference = require('./core/topologies/read_preference');\nconst maybePromise = require('./utils').maybePromise;\nconst NativeTopology = require('./topologies/native_topology');\nconst connect = require('./operations/connect').connect;\nconst validOptions = require('./operations/connect').validOptions;\n\n/**\n * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB.\n *\n * @example\n * // Connect using a MongoClient instance\n * const MongoClient = require('mongodb').MongoClient;\n * const test = require('assert');\n * // Connection url\n * const url = 'mongodb://localhost:27017';\n * // Database Name\n * const dbName = 'test';\n * // Connect using MongoClient\n * const mongoClient = new MongoClient(url);\n * mongoClient.connect(function(err, client) {\n * const db = client.db(dbName);\n * client.close();\n * });\n *\n * @example\n * // Connect using the MongoClient.connect static method\n * const MongoClient = require('mongodb').MongoClient;\n * const test = require('assert');\n * // Connection url\n * const url = 'mongodb://localhost:27017';\n * // Database Name\n * const dbName = 'test';\n * // Connect using MongoClient\n * MongoClient.connect(url, function(err, client) {\n * const db = client.db(dbName);\n * client.close();\n * });\n */\n\n/**\n * A string specifying the level of a ReadConcern\n * @typedef {'local'|'available'|'majority'|'linearizable'|'snapshot'} ReadConcernLevel\n * @see https://docs.mongodb.com/manual/reference/read-concern/index.html#read-concern-levels\n */\n\n/**\n * Configuration options for drivers wrapping the node driver.\n *\n * @typedef {Object} DriverInfoOptions\n * @property {string} [name] The name of the driver\n * @property {string} [version] The version of the driver\n * @property {string} [platform] Optional platform information\n */\n\n/**\n * Configuration options for drivers wrapping the node driver.\n *\n * @typedef {Object} DriverInfoOptions\n * @property {string} [name] The name of the driver\n * @property {string} [version] The version of the driver\n * @property {string} [platform] Optional platform information\n */\n\n/**\n * Creates a new MongoClient instance\n * @class\n * @param {string} url The connection URI string\n * @param {object} [options] Optional settings\n * @param {number} [options.poolSize=5] The maximum size of the individual server pool\n * @param {boolean} [options.ssl=false] Enable SSL connection. *deprecated* use `tls` variants\n * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority\n * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer *deprecated* use `tls` variants\n * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer *deprecated* use `tls` variants\n * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer *deprecated* use `tls` variants\n * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase *deprecated* use `tls` variants\n * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer *deprecated* use `tls` variants\n * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. *deprecated* use `tls` variants\n * @param {boolean} [options.tls=false] Enable TLS connections\n * @param {boolean} [options.tlsInsecure=false] Relax TLS constraints, disabling validation\n * @param {string} [options.tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection\n * @param {string} [options.tlsCertificateKeyFile] A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated\n * @param {string} [options.tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections\n * @param {boolean} [options.tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid\n * @param {boolean} [options.tlsAllowInvalidHostnames] Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate\n * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances\n * @param {boolean} [options.noDelay=true] TCP Connection no delay\n * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled\n * @param {number} [options.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket\n * @param {number} [options.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out\n * @param {number} [options.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out\n * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default).\n * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure\n * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times\n * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries\n * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies\n * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry\n * @param {string} [options.replicaSet=undefined] The Replicaset set name\n * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection\n * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection\n * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available\n * @param {string} [options.authSource=undefined] Define the database to authenticate against\n * @param {(number|string)} [options.w] The write concern\n * @param {number} [options.wtimeout] The write concern timeout\n * @param {boolean} [options.j=false] Specify a journal write concern\n * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields\n * @param {boolean} [options.raw=false] Return document results as raw BSON buffers\n * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)\n * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys\n * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible\n * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported)\n * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)\n * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)\n * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug)\n * @param {object} [options.logger=undefined] Custom logger object\n * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types\n * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers\n * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution\n * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit\n * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness\n * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections\n * @param {string} [options.auth.user=undefined] The username for auth\n * @param {string} [options.auth.password=undefined] The password for auth\n * @param {string} [options.authMechanism] An authentication mechanism to use for connection authentication, see the {@link https://docs.mongodb.com/manual/reference/connection-string/#urioption.authMechanism|authMechanism} reference for supported options.\n * @param {object} [options.compression] Type of compression to use: snappy or zlib\n * @param {boolean} [options.fsync=false] Specify a file sync write concern\n * @param {array} [options.readPreferenceTags] Read preference tags\n * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor\n * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances\n * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client\n * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections\n * @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser.\n * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer\n * @param {Number} [options.localThresholdMS=15] **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers\n * @param {Number} [options.serverSelectionTimeoutMS=30000] **Only applies to the unified topology** How long to block for server selection before throwing an error\n * @param {Number} [options.heartbeatFrequencyMS=10000] **Only applies to the unified topology** The frequency with which topology updates are scheduled\n * @param {number} [options.maxPoolSize=10] **Only applies to the unified topology** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections.\n * @param {number} [options.minPoolSize=0] **Only applies to the unified topology** The minimum number of connections that MUST exist at any moment in a single connection pool.\n * @param {number} [options.maxIdleTimeMS] **Only applies to the unified topology** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. The default is infinity.\n * @param {number} [options.waitQueueTimeoutMS=0] **Only applies to the unified topology** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit.\n * @param {AutoEncrypter~AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption\n * @param {DriverInfoOptions} [options.driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver\n * @param {boolean} [options.directConnection=false] Enable directConnection\n * @param {MongoClient~connectCallback} [callback] The command result callback\n * @return {MongoClient} a MongoClient instance\n */\nfunction MongoClient(url, options) {\n if (!(this instanceof MongoClient)) return new MongoClient(url, options);\n // Set up event emitter\n EventEmitter.call(this);\n\n // The internal state\n this.s = {\n url: url,\n options: options || {},\n promiseLibrary: (options && options.promiseLibrary) || Promise,\n dbCache: new Map(),\n sessions: new Set(),\n writeConcern: WriteConcern.fromOptions(options),\n namespace: new MongoDBNamespace('admin')\n };\n}\n\n/**\n * @ignore\n */\ninherits(MongoClient, EventEmitter);\n\nObject.defineProperty(MongoClient.prototype, 'writeConcern', {\n enumerable: true,\n get: function() {\n return this.s.writeConcern;\n }\n});\n\nObject.defineProperty(MongoClient.prototype, 'readPreference', {\n enumerable: true,\n get: function() {\n return ReadPreference.primary;\n }\n});\n\n/**\n * The callback format for results\n * @callback MongoClient~connectCallback\n * @param {MongoError} error An error instance representing the error during the execution.\n * @param {MongoClient} client The connected client.\n */\n\n/**\n * Connect to MongoDB using a url as documented at\n *\n * docs.mongodb.org/manual/reference/connection-string/\n *\n * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver\n *\n * @method\n * @param {MongoClient~connectCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nMongoClient.prototype.connect = function(callback) {\n if (typeof callback === 'string') {\n throw new TypeError('`connect` only accepts a callback');\n }\n\n const client = this;\n return maybePromise(this, callback, cb => {\n const err = validOptions(client.s.options);\n if (err) return cb(err);\n\n connect(client, client.s.url, client.s.options, err => {\n if (err) return cb(err);\n cb(null, client);\n });\n });\n};\n\nMongoClient.prototype.logout = deprecate(function(options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n if (typeof callback === 'function') callback(null, true);\n}, 'Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient');\n\n/**\n * Close the db and its underlying connections\n * @method\n * @param {boolean} [force=false] Force close, emitting no events\n * @param {Db~noResultCallback} [callback] The result callback\n * @return {Promise} returns Promise if no callback passed\n */\nMongoClient.prototype.close = function(force, callback) {\n if (typeof force === 'function') {\n callback = force;\n force = false;\n }\n\n const client = this;\n return maybePromise(this, callback, cb => {\n const completeClose = err => {\n client.emit('close', client);\n\n if (!(client.topology instanceof NativeTopology)) {\n for (const item of client.s.dbCache) {\n item[1].emit('close', client);\n }\n }\n\n client.removeAllListeners('close');\n cb(err);\n };\n\n if (client.topology == null) {\n completeClose();\n return;\n }\n\n client.topology.close(force, err => {\n const autoEncrypter = client.topology.s.options.autoEncrypter;\n if (!autoEncrypter) {\n completeClose(err);\n return;\n }\n\n autoEncrypter.teardown(force, err2 => completeClose(err || err2));\n });\n });\n};\n\n/**\n * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are\n * related in a parent-child relationship to the original instance so that events are correctly emitted on child\n * db instances. Child db instances are cached so performing db('db1') twice will return the same instance.\n * You can control these behaviors with the options noListener and returnNonCachedInstance.\n *\n * @method\n * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string.\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection.\n * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created\n * @return {Db}\n */\nMongoClient.prototype.db = function(dbName, options) {\n options = options || {};\n\n // Default to db from connection string if not provided\n if (!dbName) {\n dbName = this.s.options.dbName;\n }\n\n // Copy the options and add out internal override of the not shared flag\n const finalOptions = Object.assign({}, this.s.options, options);\n\n // Do we have the db in the cache already\n if (this.s.dbCache.has(dbName) && finalOptions.returnNonCachedInstance !== true) {\n return this.s.dbCache.get(dbName);\n }\n\n // Add promiseLibrary\n finalOptions.promiseLibrary = this.s.promiseLibrary;\n\n // If no topology throw an error message\n if (!this.topology) {\n throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db');\n }\n\n // Return the db object\n const db = new Db(dbName, this.topology, finalOptions);\n\n // Add the db to the cache\n this.s.dbCache.set(dbName, db);\n // Return the database\n return db;\n};\n\n/**\n * Check if MongoClient is connected\n *\n * @method\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection.\n * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created\n * @return {boolean}\n */\nMongoClient.prototype.isConnected = function(options) {\n options = options || {};\n\n if (!this.topology) return false;\n return this.topology.isConnected(options);\n};\n\n/**\n * Connect to MongoDB using a url as documented at\n *\n * docs.mongodb.org/manual/reference/connection-string/\n *\n * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver\n *\n * @method\n * @static\n * @param {string} url The connection URI string\n * @param {object} [options] Optional settings\n * @param {number} [options.poolSize=5] The maximum size of the individual server pool\n * @param {boolean} [options.ssl=false] Enable SSL connection. *deprecated* use `tls` variants\n * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority\n * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer *deprecated* use `tls` variants\n * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer *deprecated* use `tls` variants\n * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer *deprecated* use `tls` variants\n * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase *deprecated* use `tls` variants\n * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer *deprecated* use `tls` variants\n * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. *deprecated* use `tls` variants\n * @param {boolean} [options.tls=false] Enable TLS connections\n * @param {boolean} [options.tlsInsecure=false] Relax TLS constraints, disabling validation\n * @param {string} [options.tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection\n * @param {string} [options.tlsCertificateKeyFile] A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated\n * @param {string} [options.tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections\n * @param {boolean} [options.tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid\n * @param {boolean} [options.tlsAllowInvalidHostnames] Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate\n * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances\n * @param {boolean} [options.noDelay=true] TCP Connection no delay\n * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled\n * @param {number} [options.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket\n * @param {number} [options.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out\n * @param {number} [options.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out\n * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default).\n * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure\n * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times\n * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries\n * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies\n * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry\n * @param {string} [options.replicaSet=undefined] The Replicaset set name\n * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection\n * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection\n * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available\n * @param {string} [options.authSource=undefined] Define the database to authenticate against\n * @param {(number|string)} [options.w] The write concern\n * @param {number} [options.wtimeout] The write concern timeout\n * @param {boolean} [options.j=false] Specify a journal write concern\n * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver\n * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object\n * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields\n * @param {boolean} [options.raw=false] Return document results as raw BSON buffers\n * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited\n * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)\n * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys\n * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible\n * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported)\n * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)\n * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)\n * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug)\n * @param {object} [options.logger=undefined] Custom logger object\n * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types\n * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers\n * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution\n * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit\n * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness\n * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections\n * @param {string} [options.auth.user=undefined] The username for auth\n * @param {string} [options.auth.password=undefined] The password for auth\n * @param {string} [options.authMechanism] An authentication mechanism to use for connection authentication, see the {@link https://docs.mongodb.com/manual/reference/connection-string/#urioption.authMechanism|authMechanism} reference for supported options.\n * @param {object} [options.compression] Type of compression to use: snappy or zlib\n * @param {boolean} [options.fsync=false] Specify a file sync write concern\n * @param {array} [options.readPreferenceTags] Read preference tags\n * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor\n * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances\n * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client\n * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections\n * @param {boolean} [options.directConnection=false] Enable directConnection\n * @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser.\n * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer\n * @param {Number} [options.localThresholdMS=15] **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers\n * @param {Number} [options.serverSelectionTimeoutMS=30000] **Only applies to the unified topology** How long to block for server selection before throwing an error\n * @param {Number} [options.heartbeatFrequencyMS=10000] **Only applies to the unified topology** The frequency with which topology updates are scheduled\n * @param {number} [options.maxPoolSize=10] **Only applies to the unified topology** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections.\n * @param {number} [options.minPoolSize=0] **Only applies to the unified topology** The minimum number of connections that MUST exist at any moment in a single connection pool.\n * @param {number} [options.maxIdleTimeMS] **Only applies to the unified topology** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. The default is infinity.\n * @param {number} [options.waitQueueTimeoutMS=0] **Only applies to the unified topology** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit.\n * @param {AutoEncrypter~AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption\n * @param {DriverInfoOptions} [options.driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver\n * @param {MongoClient~connectCallback} [callback] The command result callback\n * @return {Promise} returns Promise if no callback passed\n */\nMongoClient.connect = function(url, options, callback) {\n const args = Array.prototype.slice.call(arguments, 1);\n callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n options = args.length ? args.shift() : null;\n options = options || {};\n\n // Create client\n const mongoClient = new MongoClient(url, options);\n // Execute the connect method\n return mongoClient.connect(callback);\n};\n\n/**\n * Starts a new session on the server\n *\n * @param {SessionOptions} [options] optional settings for a driver session\n * @return {ClientSession} the newly established session\n */\nMongoClient.prototype.startSession = function(options) {\n options = Object.assign({ explicit: true }, options);\n if (!this.topology) {\n throw new MongoError('Must connect to a server before calling this method');\n }\n\n if (!this.topology.hasSessionSupport()) {\n throw new MongoError('Current topology does not support sessions');\n }\n\n return this.topology.startSession(options, this.s.options);\n};\n\n/**\n * Runs a given operation with an implicitly created session. The lifetime of the session\n * will be handled without the need for user interaction.\n *\n * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function)\n *\n * @param {Object} [options] Optional settings to be appled to implicitly created session\n * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}`\n * @return {Promise}\n */\nMongoClient.prototype.withSession = function(options, operation) {\n if (typeof options === 'function') (operation = options), (options = undefined);\n const session = this.startSession(options);\n\n let cleanupHandler = (err, result, opts) => {\n // prevent multiple calls to cleanupHandler\n cleanupHandler = () => {\n throw new ReferenceError('cleanupHandler was called too many times');\n };\n\n opts = Object.assign({ throw: true }, opts);\n session.endSession();\n\n if (err) {\n if (opts.throw) throw err;\n return Promise.reject(err);\n }\n };\n\n try {\n const result = operation(session);\n return Promise.resolve(result)\n .then(result => cleanupHandler(null, result))\n .catch(err => cleanupHandler(err, null, { throw: true }));\n } catch (err) {\n return cleanupHandler(err, null, { throw: false });\n }\n};\n/**\n * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin,\n * and config databases.\n * @method\n * @since 3.1.0\n * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.\n * @param {object} [options] Optional settings\n * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.\n * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.\n * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query\n * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.\n * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.\n * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp\n * @param {ClientSession} [options.session] optional session to use for this operation\n * @return {ChangeStream} a ChangeStream instance.\n */\nMongoClient.prototype.watch = function(pipeline, options) {\n pipeline = pipeline || [];\n options = options || {};\n\n // Allow optionally not specifying a pipeline\n if (!Array.isArray(pipeline)) {\n options = pipeline;\n pipeline = [];\n }\n\n return new ChangeStream(this, pipeline, options);\n};\n\n/**\n * Return the mongo client logger\n * @method\n * @return {Logger} return the mongo client logger\n * @ignore\n */\nMongoClient.prototype.getLogger = function() {\n return this.s.options.logger;\n};\n\nmodule.exports = MongoClient;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst CommandOperation = require('./command');\nconst defineAspects = require('./operation').defineAspects;\nconst crypto = require('crypto');\nconst handleCallback = require('../utils').handleCallback;\nconst toError = require('../utils').toError;\n\nclass AddUserOperation extends CommandOperation {\n constructor(db, username, password, options) {\n super(db, options);\n\n this.username = username;\n this.password = password;\n }\n\n _buildCommand() {\n const db = this.db;\n const username = this.username;\n const password = this.password;\n const options = this.options;\n\n // Get additional values\n let roles = Array.isArray(options.roles) ? options.roles : [];\n\n // If not roles defined print deprecated message\n // TODO: handle deprecation properly\n if (roles.length === 0) {\n console.log('Creating a user without roles is deprecated in MongoDB >= 2.6');\n }\n\n // Check the db name and add roles if needed\n if (\n (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') &&\n !Array.isArray(options.roles)\n ) {\n roles = ['root'];\n } else if (!Array.isArray(options.roles)) {\n roles = ['dbOwner'];\n }\n\n const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7;\n\n let userPassword = password;\n\n if (!digestPassword) {\n // Use node md5 generator\n const md5 = crypto.createHash('md5');\n // Generate keys used for authentication\n md5.update(username + ':mongo:' + password);\n userPassword = md5.digest('hex');\n }\n\n // Build the command to execute\n const command = {\n createUser: username,\n customData: options.customData || {},\n roles: roles,\n digestPassword\n };\n\n // No password\n if (typeof password === 'string') {\n command.pwd = userPassword;\n }\n\n return command;\n }\n\n execute(callback) {\n const options = this.options;\n\n // Error out if digestPassword set\n if (options.digestPassword != null) {\n return callback(\n toError(\n \"The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option.\"\n )\n );\n }\n\n // Attempt to execute auth command\n super.execute((err, r) => {\n if (!err) {\n return handleCallback(callback, err, r);\n }\n\n return handleCallback(callback, err, null);\n });\n }\n}\n\ndefineAspects(AddUserOperation, Aspect.WRITE_OPERATION);\n\nmodule.exports = AddUserOperation;\n","'use strict';\n\nconst CommandOperationV2 = require('./command_v2');\nconst MongoError = require('../core').MongoError;\nconst maxWireVersion = require('../core/utils').maxWireVersion;\nconst ReadPreference = require('../core').ReadPreference;\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\n\nconst DB_AGGREGATE_COLLECTION = 1;\nconst MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8;\n\nclass AggregateOperation extends CommandOperationV2 {\n constructor(parent, pipeline, options) {\n super(parent, options, { fullResponse: true });\n\n this.target =\n parent.s.namespace && parent.s.namespace.collection\n ? parent.s.namespace.collection\n : DB_AGGREGATE_COLLECTION;\n\n this.pipeline = pipeline;\n\n // determine if we have a write stage, override read preference if so\n this.hasWriteStage = false;\n if (typeof options.out === 'string') {\n this.pipeline = this.pipeline.concat({ $out: options.out });\n this.hasWriteStage = true;\n } else if (pipeline.length > 0) {\n const finalStage = pipeline[pipeline.length - 1];\n if (finalStage.$out || finalStage.$merge) {\n this.hasWriteStage = true;\n }\n }\n\n if (this.hasWriteStage) {\n this.readPreference = ReadPreference.primary;\n }\n\n if (options.explain && (this.readConcern || this.writeConcern)) {\n throw new MongoError(\n '\"explain\" cannot be used on an aggregate call with readConcern/writeConcern'\n );\n }\n\n if (options.cursor != null && typeof options.cursor !== 'object') {\n throw new MongoError('cursor options must be an object');\n }\n }\n\n get canRetryRead() {\n return !this.hasWriteStage;\n }\n\n addToPipeline(stage) {\n this.pipeline.push(stage);\n }\n\n execute(server, callback) {\n const options = this.options;\n const serverWireVersion = maxWireVersion(server);\n const command = { aggregate: this.target, pipeline: this.pipeline };\n\n if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) {\n this.readConcern = null;\n }\n\n if (serverWireVersion >= 5) {\n if (this.hasWriteStage && this.writeConcern) {\n Object.assign(command, { writeConcern: this.writeConcern });\n }\n }\n\n if (options.bypassDocumentValidation === true) {\n command.bypassDocumentValidation = options.bypassDocumentValidation;\n }\n\n if (typeof options.allowDiskUse === 'boolean') {\n command.allowDiskUse = options.allowDiskUse;\n }\n\n if (options.hint) {\n command.hint = options.hint;\n }\n\n if (options.explain) {\n options.full = false;\n command.explain = options.explain;\n }\n\n command.cursor = options.cursor || {};\n if (options.batchSize && !this.hasWriteStage) {\n command.cursor.batchSize = options.batchSize;\n }\n\n super.executeCommand(server, command, callback);\n }\n}\n\ndefineAspects(AggregateOperation, [\n Aspect.READ_OPERATION,\n Aspect.RETRYABLE,\n Aspect.EXECUTE_WITH_SELECTION\n]);\n\nmodule.exports = AggregateOperation;\n","'use strict';\n\nconst applyRetryableWrites = require('../utils').applyRetryableWrites;\nconst applyWriteConcern = require('../utils').applyWriteConcern;\nconst MongoError = require('../core').MongoError;\nconst OperationBase = require('./operation').OperationBase;\n\nclass BulkWriteOperation extends OperationBase {\n constructor(collection, operations, options) {\n super(options);\n\n this.collection = collection;\n this.operations = operations;\n }\n\n execute(callback) {\n const coll = this.collection;\n const operations = this.operations;\n let options = this.options;\n\n // Add ignoreUndfined\n if (coll.s.options.ignoreUndefined) {\n options = Object.assign({}, options);\n options.ignoreUndefined = coll.s.options.ignoreUndefined;\n }\n\n // Create the bulk operation\n const bulk =\n options.ordered === true || options.ordered == null\n ? coll.initializeOrderedBulkOp(options)\n : coll.initializeUnorderedBulkOp(options);\n\n // Do we have a collation\n let collation = false;\n\n // for each op go through and add to the bulk\n try {\n for (let i = 0; i < operations.length; i++) {\n // Get the operation type\n const key = Object.keys(operations[i])[0];\n // Check if we have a collation\n if (operations[i][key].collation) {\n collation = true;\n }\n\n // Pass to the raw bulk\n bulk.raw(operations[i]);\n }\n } catch (err) {\n return callback(err, null);\n }\n\n // Final options for retryable writes and write concern\n let finalOptions = Object.assign({}, options);\n finalOptions = applyRetryableWrites(finalOptions, coll.s.db);\n finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);\n\n const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {};\n const capabilities = coll.s.topology.capabilities();\n\n // Did the user pass in a collation, check if our write server supports it\n if (collation && capabilities && !capabilities.commandsTakeCollation) {\n return callback(new MongoError('server/primary/mongos does not support collation'));\n }\n\n // Execute the bulk\n bulk.execute(writeCon, finalOptions, (err, r) => {\n // We have connection level error\n if (!r && err) {\n return callback(err, null);\n }\n\n r.insertedCount = r.nInserted;\n r.matchedCount = r.nMatched;\n r.modifiedCount = r.nModified || 0;\n r.deletedCount = r.nRemoved;\n r.upsertedCount = r.getUpsertedIds().length;\n r.upsertedIds = {};\n r.insertedIds = {};\n\n // Update the n\n r.n = r.insertedCount;\n\n // Inserted documents\n const inserted = r.getInsertedIds();\n // Map inserted ids\n for (let i = 0; i < inserted.length; i++) {\n r.insertedIds[inserted[i].index] = inserted[i]._id;\n }\n\n // Upserted documents\n const upserted = r.getUpsertedIds();\n // Map upserted ids\n for (let i = 0; i < upserted.length; i++) {\n r.upsertedIds[upserted[i].index] = upserted[i]._id;\n }\n\n // Return the results\n callback(null, r);\n });\n }\n}\n\nmodule.exports = BulkWriteOperation;\n","'use strict';\n\nconst applyWriteConcern = require('../utils').applyWriteConcern;\nconst Code = require('../core').BSON.Code;\nconst createIndexDb = require('./db_ops').createIndex;\nconst decorateWithCollation = require('../utils').decorateWithCollation;\nconst decorateWithReadConcern = require('../utils').decorateWithReadConcern;\nconst ensureIndexDb = require('./db_ops').ensureIndex;\nconst evaluate = require('./db_ops').evaluate;\nconst executeCommand = require('./db_ops').executeCommand;\nconst handleCallback = require('../utils').handleCallback;\nconst indexInformationDb = require('./db_ops').indexInformation;\nconst Long = require('../core').BSON.Long;\nconst MongoError = require('../core').MongoError;\nconst ReadPreference = require('../core').ReadPreference;\nconst insertDocuments = require('./common_functions').insertDocuments;\nconst updateDocuments = require('./common_functions').updateDocuments;\n\n/**\n * Group function helper\n * @ignore\n */\n// var groupFunction = function () {\n// var c = db[ns].find(condition);\n// var map = new Map();\n// var reduce_function = reduce;\n//\n// while (c.hasNext()) {\n// var obj = c.next();\n// var key = {};\n//\n// for (var i = 0, len = keys.length; i < len; ++i) {\n// var k = keys[i];\n// key[k] = obj[k];\n// }\n//\n// var aggObj = map.get(key);\n//\n// if (aggObj == null) {\n// var newObj = Object.extend({}, key);\n// aggObj = Object.extend(newObj, initial);\n// map.put(key, aggObj);\n// }\n//\n// reduce_function(obj, aggObj);\n// }\n//\n// return { \"result\": map.values() };\n// }.toString();\nconst groupFunction =\n 'function () {\\nvar c = db[ns].find(condition);\\nvar map = new Map();\\nvar reduce_function = reduce;\\n\\nwhile (c.hasNext()) {\\nvar obj = c.next();\\nvar key = {};\\n\\nfor (var i = 0, len = keys.length; i < len; ++i) {\\nvar k = keys[i];\\nkey[k] = obj[k];\\n}\\n\\nvar aggObj = map.get(key);\\n\\nif (aggObj == null) {\\nvar newObj = Object.extend({}, key);\\naggObj = Object.extend(newObj, initial);\\nmap.put(key, aggObj);\\n}\\n\\nreduce_function(obj, aggObj);\\n}\\n\\nreturn { \"result\": map.values() };\\n}';\n\n/**\n * Create an index on the db and collection.\n *\n * @method\n * @param {Collection} a Collection instance.\n * @param {(string|object)} fieldOrSpec Defines the index.\n * @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options.\n * @param {Collection~resultCallback} [callback] The command result callback\n */\nfunction createIndex(coll, fieldOrSpec, options, callback) {\n createIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback);\n}\n\n/**\n * Create multiple indexes in the collection. This method is only supported for\n * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported\n * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/.\n *\n * @method\n * @param {Collection} a Collection instance.\n * @param {array} indexSpecs An array of index specifications to be created\n * @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options.\n * @param {Collection~resultCallback} [callback] The command result callback\n */\nfunction createIndexes(coll, indexSpecs, options, callback) {\n const capabilities = coll.s.topology.capabilities();\n\n // Ensure we generate the correct name if the parameter is not set\n for (let i = 0; i < indexSpecs.length; i++) {\n if (indexSpecs[i].name == null) {\n const keys = [];\n\n // Did the user pass in a collation, check if our write server supports it\n if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) {\n return callback(new MongoError('server/primary/mongos does not support collation'));\n }\n\n for (let name in indexSpecs[i].key) {\n keys.push(`${name}_${indexSpecs[i].key[name]}`);\n }\n\n // Set the name\n indexSpecs[i].name = keys.join('_');\n }\n }\n\n options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY });\n\n // Execute the index\n executeCommand(\n coll.s.db,\n {\n createIndexes: coll.collectionName,\n indexes: indexSpecs\n },\n options,\n callback\n );\n}\n\n/**\n * Ensure that an index exists. If the index does not exist, this function creates it.\n *\n * @method\n * @param {Collection} a Collection instance.\n * @param {(string|object)} fieldOrSpec Defines the index.\n * @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options.\n * @param {Collection~resultCallback} [callback] The command result callback\n */\nfunction ensureIndex(coll, fieldOrSpec, options, callback) {\n ensureIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback);\n}\n\n/**\n * Run a group command across a collection.\n *\n * @method\n * @param {Collection} a Collection instance.\n * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by.\n * @param {object} condition An optional condition that must be true for a row to be considered.\n * @param {object} initial Initial value of the aggregation counter object.\n * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated\n * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned.\n * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true.\n * @param {object} [options] Optional settings. See Collection.prototype.group for a list of options.\n * @param {Collection~resultCallback} [callback] The command result callback\n * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework.\n */\nfunction group(coll, keys, condition, initial, reduce, finalize, command, options, callback) {\n // Execute using the command\n if (command) {\n const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce);\n\n const selector = {\n group: {\n ns: coll.collectionName,\n $reduce: reduceFunction,\n cond: condition,\n initial: initial,\n out: 'inline'\n }\n };\n\n // if finalize is defined\n if (finalize != null) selector.group['finalize'] = finalize;\n // Set up group selector\n if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) {\n selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys);\n } else {\n const hash = {};\n keys.forEach(key => {\n hash[key] = 1;\n });\n selector.group.key = hash;\n }\n\n options = Object.assign({}, options);\n // Ensure we have the right read preference inheritance\n options.readPreference = ReadPreference.resolve(coll, options);\n\n // Do we have a readConcern specified\n decorateWithReadConcern(selector, coll, options);\n\n // Have we specified collation\n try {\n decorateWithCollation(selector, coll, options);\n } catch (err) {\n return callback(err, null);\n }\n\n // Execute command\n executeCommand(coll.s.db, selector, options, (err, result) => {\n if (err) return handleCallback(callback, err, null);\n handleCallback(callback, null, result.retval);\n });\n } else {\n // Create execution scope\n const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {};\n\n scope.ns = coll.collectionName;\n scope.keys = keys;\n scope.condition = condition;\n scope.initial = initial;\n\n // Pass in the function text to execute within mongodb.\n const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';');\n\n evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => {\n if (err) return handleCallback(callback, err, null);\n handleCallback(callback, null, results.result || results);\n });\n }\n}\n\n/**\n * Retrieve all the indexes on the collection.\n *\n * @method\n * @param {Collection} a Collection instance.\n * @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options.\n * @param {Collection~resultCallback} [callback] The command result callback\n */\nfunction indexes(coll, options, callback) {\n options = Object.assign({}, { full: true }, options);\n indexInformationDb(coll.s.db, coll.collectionName, options, callback);\n}\n\n/**\n * Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist.\n *\n * @method\n * @param {Collection} a Collection instance.\n * @param {(string|array)} indexes One or more index names to check.\n * @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options.\n * @param {Collection~resultCallback} [callback] The command result callback\n */\nfunction indexExists(coll, indexes, options, callback) {\n indexInformation(coll, options, (err, indexInformation) => {\n // If we have an error return\n if (err != null) return handleCallback(callback, err, null);\n // Let's check for the index names\n if (!Array.isArray(indexes))\n return handleCallback(callback, null, indexInformation[indexes] != null);\n // Check in list of indexes\n for (let i = 0; i < indexes.length; i++) {\n if (indexInformation[indexes[i]] == null) {\n return handleCallback(callback, null, false);\n }\n }\n\n // All keys found return true\n return handleCallback(callback, null, true);\n });\n}\n\n/**\n * Retrieve this collection's index info.\n *\n * @method\n * @param {Collection} a Collection instance.\n * @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options.\n * @param {Collection~resultCallback} [callback] The command result callback\n */\nfunction indexInformation(coll, options, callback) {\n indexInformationDb(coll.s.db, coll.collectionName, options, callback);\n}\n\n/**\n * Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are\n * no ordering guarantees for returned results.\n *\n * @method\n * @param {Collection} a Collection instance.\n * @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options.\n * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback\n */\nfunction parallelCollectionScan(coll, options, callback) {\n // Create command object\n const commandObject = {\n parallelCollectionScan: coll.collectionName,\n numCursors: options.numCursors\n };\n\n // Do we have a readConcern specified\n decorateWithReadConcern(commandObject, coll, options);\n\n // Store the raw value\n const raw = options.raw;\n delete options['raw'];\n\n // Execute the command\n executeCommand(coll.s.db, commandObject, options, (err, result) => {\n if (err) return handleCallback(callback, err, null);\n if (result == null)\n return handleCallback(\n callback,\n new Error('no result returned for parallelCollectionScan'),\n null\n );\n\n options = Object.assign({ explicitlyIgnoreSession: true }, options);\n\n const cursors = [];\n // Add the raw back to the option\n if (raw) options.raw = raw;\n // Create command cursors for each item\n for (let i = 0; i < result.cursors.length; i++) {\n const rawId = result.cursors[i].cursor.id;\n // Convert cursorId to Long if needed\n const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId;\n // Add a command cursor\n cursors.push(coll.s.topology.cursor(coll.namespace, cursorId, options));\n }\n\n handleCallback(callback, null, cursors);\n });\n}\n\n/**\n * Save a document.\n *\n * @method\n * @param {Collection} a Collection instance.\n * @param {object} doc Document to save\n * @param {object} [options] Optional settings. See Collection.prototype.save for a list of options.\n * @param {Collection~writeOpCallback} [callback] The command result callback\n * @deprecated use insertOne, insertMany, updateOne or updateMany\n */\nfunction save(coll, doc, options, callback) {\n // Get the write concern options\n const finalOptions = applyWriteConcern(\n Object.assign({}, options),\n { db: coll.s.db, collection: coll },\n options\n );\n // Establish if we need to perform an insert or update\n if (doc._id != null) {\n finalOptions.upsert = true;\n return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback);\n }\n\n // Insert the document\n insertDocuments(coll, [doc], finalOptions, (err, result) => {\n if (callback == null) return;\n if (doc == null) return handleCallback(callback, null, null);\n if (err) return handleCallback(callback, err, null);\n handleCallback(callback, null, result);\n });\n}\n\nmodule.exports = {\n createIndex,\n createIndexes,\n ensureIndex,\n group,\n indexes,\n indexExists,\n indexInformation,\n parallelCollectionScan,\n save\n};\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst handleCallback = require('../utils').handleCallback;\n\nlet collection;\nfunction loadCollection() {\n if (!collection) {\n collection = require('../collection');\n }\n return collection;\n}\n\nclass CollectionsOperation extends OperationBase {\n constructor(db, options) {\n super(options);\n\n this.db = db;\n }\n\n execute(callback) {\n const db = this.db;\n let options = this.options;\n\n let Collection = loadCollection();\n\n options = Object.assign({}, options, { nameOnly: true });\n // Let's get the collection names\n db.listCollections({}, options).toArray((err, documents) => {\n if (err != null) return handleCallback(callback, err, null);\n // Filter collections removing any illegal ones\n documents = documents.filter(doc => {\n return doc.name.indexOf('$') === -1;\n });\n\n // Return the collection objects\n handleCallback(\n callback,\n null,\n documents.map(d => {\n return new Collection(\n db,\n db.s.topology,\n db.databaseName,\n d.name,\n db.s.pkFactory,\n db.s.options\n );\n })\n );\n });\n }\n}\n\nmodule.exports = CollectionsOperation;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst OperationBase = require('./operation').OperationBase;\nconst applyWriteConcern = require('../utils').applyWriteConcern;\nconst debugOptions = require('../utils').debugOptions;\nconst handleCallback = require('../utils').handleCallback;\nconst MongoError = require('../core').MongoError;\nconst ReadPreference = require('../core').ReadPreference;\nconst MongoDBNamespace = require('../utils').MongoDBNamespace;\n\nconst debugFields = [\n 'authSource',\n 'w',\n 'wtimeout',\n 'j',\n 'native_parser',\n 'forceServerObjectId',\n 'serializeFunctions',\n 'raw',\n 'promoteLongs',\n 'promoteValues',\n 'promoteBuffers',\n 'bufferMaxEntries',\n 'numberOfRetries',\n 'retryMiliSeconds',\n 'readPreference',\n 'pkFactory',\n 'parentDb',\n 'promiseLibrary',\n 'noListener'\n];\n\nclass CommandOperation extends OperationBase {\n constructor(db, options, collection, command) {\n super(options);\n\n if (!this.hasAspect(Aspect.WRITE_OPERATION)) {\n if (collection != null) {\n this.options.readPreference = ReadPreference.resolve(collection, options);\n } else {\n this.options.readPreference = ReadPreference.resolve(db, options);\n }\n } else {\n if (collection != null) {\n applyWriteConcern(this.options, { db, coll: collection }, this.options);\n } else {\n applyWriteConcern(this.options, { db }, this.options);\n }\n this.options.readPreference = ReadPreference.primary;\n }\n\n this.db = db;\n\n if (command != null) {\n this.command = command;\n }\n\n if (collection != null) {\n this.collection = collection;\n }\n }\n\n _buildCommand() {\n if (this.command != null) {\n return this.command;\n }\n }\n\n execute(callback) {\n const db = this.db;\n const options = Object.assign({}, this.options);\n\n // Did the user destroy the topology\n if (db.serverConfig && db.serverConfig.isDestroyed()) {\n return callback(new MongoError('topology was destroyed'));\n }\n\n let command;\n try {\n command = this._buildCommand();\n } catch (e) {\n return callback(e);\n }\n\n // Get the db name we are executing against\n const dbName = options.dbName || options.authdb || db.databaseName;\n\n // Convert the readPreference if its not a write\n if (this.hasAspect(Aspect.WRITE_OPERATION)) {\n if (options.writeConcern && (!options.session || !options.session.inTransaction())) {\n command.writeConcern = options.writeConcern;\n }\n }\n\n // Debug information\n if (db.s.logger.isDebug()) {\n db.s.logger.debug(\n `executing command ${JSON.stringify(\n command\n )} against ${dbName}.$cmd with options [${JSON.stringify(\n debugOptions(debugFields, options)\n )}]`\n );\n }\n\n const namespace =\n this.namespace != null ? this.namespace : new MongoDBNamespace(dbName, '$cmd');\n\n // Execute command\n db.s.topology.command(namespace, command, options, (err, result) => {\n if (err) return handleCallback(callback, err);\n if (options.full) return handleCallback(callback, null, result);\n handleCallback(callback, null, result.result);\n });\n }\n}\n\nmodule.exports = CommandOperation;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst OperationBase = require('./operation').OperationBase;\nconst ReadPreference = require('../core').ReadPreference;\nconst ReadConcern = require('../read_concern');\nconst WriteConcern = require('../write_concern');\nconst maxWireVersion = require('../core/utils').maxWireVersion;\nconst commandSupportsReadConcern = require('../core/sessions').commandSupportsReadConcern;\nconst MongoError = require('../core/error').MongoError;\n\nconst SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5;\n\nclass CommandOperationV2 extends OperationBase {\n constructor(parent, options, operationOptions) {\n super(options);\n\n this.ns = parent.s.namespace.withCollection('$cmd');\n const propertyProvider = this.hasAspect(Aspect.NO_INHERIT_OPTIONS) ? undefined : parent;\n this.readPreference = ReadPreference.resolve(propertyProvider, this.options);\n this.readConcern = resolveReadConcern(propertyProvider, this.options);\n this.writeConcern = resolveWriteConcern(propertyProvider, this.options);\n this.explain = false;\n\n if (operationOptions && typeof operationOptions.fullResponse === 'boolean') {\n this.fullResponse = true;\n }\n\n // TODO: A lot of our code depends on having the read preference in the options. This should\n // go away, but also requires massive test rewrites.\n this.options.readPreference = this.readPreference;\n\n // TODO(NODE-2056): make logger another \"inheritable\" property\n if (parent.s.logger) {\n this.logger = parent.s.logger;\n } else if (parent.s.db && parent.s.db.logger) {\n this.logger = parent.s.db.logger;\n }\n }\n\n executeCommand(server, cmd, callback) {\n // TODO: consider making this a non-enumerable property\n this.server = server;\n\n const options = this.options;\n const serverWireVersion = maxWireVersion(server);\n const inTransaction = this.session && this.session.inTransaction();\n\n if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) {\n Object.assign(cmd, { readConcern: this.readConcern });\n }\n\n if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) {\n callback(\n new MongoError(\n `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`\n )\n );\n return;\n }\n\n if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) {\n if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION)) {\n Object.assign(cmd, { writeConcern: this.writeConcern });\n }\n\n if (options.collation && typeof options.collation === 'object') {\n Object.assign(cmd, { collation: options.collation });\n }\n }\n\n if (typeof options.maxTimeMS === 'number') {\n cmd.maxTimeMS = options.maxTimeMS;\n }\n\n if (typeof options.comment === 'string') {\n cmd.comment = options.comment;\n }\n\n if (this.logger && this.logger.isDebug()) {\n this.logger.debug(`executing command ${JSON.stringify(cmd)} against ${this.ns}`);\n }\n\n server.command(this.ns.toString(), cmd, this.options, (err, result) => {\n if (err) {\n callback(err, null);\n return;\n }\n\n if (this.fullResponse) {\n callback(null, result);\n return;\n }\n\n callback(null, result.result);\n });\n }\n}\n\nfunction resolveWriteConcern(parent, options) {\n return WriteConcern.fromOptions(options) || (parent && parent.writeConcern);\n}\n\nfunction resolveReadConcern(parent, options) {\n return ReadConcern.fromOptions(options) || (parent && parent.readConcern);\n}\n\nmodule.exports = CommandOperationV2;\n","'use strict';\n\nconst applyRetryableWrites = require('../utils').applyRetryableWrites;\nconst applyWriteConcern = require('../utils').applyWriteConcern;\nconst decorateWithCollation = require('../utils').decorateWithCollation;\nconst decorateWithReadConcern = require('../utils').decorateWithReadConcern;\nconst executeCommand = require('./db_ops').executeCommand;\nconst formattedOrderClause = require('../utils').formattedOrderClause;\nconst handleCallback = require('../utils').handleCallback;\nconst MongoError = require('../core').MongoError;\nconst ReadPreference = require('../core').ReadPreference;\nconst toError = require('../utils').toError;\nconst CursorState = require('../core/cursor').CursorState;\n\n/**\n * Build the count command.\n *\n * @method\n * @param {collectionOrCursor} an instance of a collection or cursor\n * @param {object} query The query for the count.\n * @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options.\n */\nfunction buildCountCommand(collectionOrCursor, query, options) {\n const skip = options.skip;\n const limit = options.limit;\n let hint = options.hint;\n const maxTimeMS = options.maxTimeMS;\n query = query || {};\n\n // Final query\n const cmd = {\n count: options.collectionName,\n query: query\n };\n\n if (collectionOrCursor.s.numberOfRetries) {\n // collectionOrCursor is a cursor\n if (collectionOrCursor.options.hint) {\n hint = collectionOrCursor.options.hint;\n } else if (collectionOrCursor.cmd.hint) {\n hint = collectionOrCursor.cmd.hint;\n }\n decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.cmd);\n } else {\n decorateWithCollation(cmd, collectionOrCursor, options);\n }\n\n // Add limit, skip and maxTimeMS if defined\n if (typeof skip === 'number') cmd.skip = skip;\n if (typeof limit === 'number') cmd.limit = limit;\n if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS;\n if (hint) cmd.hint = hint;\n\n // Do we have a readConcern specified\n decorateWithReadConcern(cmd, collectionOrCursor);\n\n return cmd;\n}\n\nfunction deleteCallback(err, r, callback) {\n if (callback == null) return;\n if (err && callback) return callback(err);\n if (r == null) return callback(null, { result: { ok: 1 } });\n r.deletedCount = r.result.n;\n if (callback) callback(null, r);\n}\n\n/**\n * Find and update a document.\n *\n * @method\n * @param {Collection} a Collection instance.\n * @param {object} query Query object to locate the object to modify.\n * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate.\n * @param {object} doc The fields/vals to be updated.\n * @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options.\n * @param {Collection~findAndModifyCallback} [callback] The command result callback\n * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead\n */\nfunction findAndModify(coll, query, sort, doc, options, callback) {\n // Create findAndModify command object\n const queryObject = {\n findAndModify: coll.collectionName,\n query: query\n };\n\n sort = formattedOrderClause(sort);\n if (sort) {\n queryObject.sort = sort;\n }\n\n queryObject.new = options.new ? true : false;\n queryObject.remove = options.remove ? true : false;\n queryObject.upsert = options.upsert ? true : false;\n\n const projection = options.projection || options.fields;\n\n if (projection) {\n queryObject.fields = projection;\n }\n\n if (options.arrayFilters) {\n queryObject.arrayFilters = options.arrayFilters;\n delete options.arrayFilters;\n }\n\n if (doc && !options.remove) {\n queryObject.update = doc;\n }\n\n if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS;\n\n // Either use override on the function, or go back to default on either the collection\n // level or db\n options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions;\n\n // No check on the documents\n options.checkKeys = false;\n\n // Final options for retryable writes and write concern\n let finalOptions = Object.assign({}, options);\n finalOptions = applyRetryableWrites(finalOptions, coll.s.db);\n finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);\n\n // Decorate the findAndModify command with the write Concern\n if (finalOptions.writeConcern) {\n queryObject.writeConcern = finalOptions.writeConcern;\n }\n\n // Have we specified bypassDocumentValidation\n if (finalOptions.bypassDocumentValidation === true) {\n queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation;\n }\n\n finalOptions.readPreference = ReadPreference.primary;\n\n // Have we specified collation\n try {\n decorateWithCollation(queryObject, coll, finalOptions);\n } catch (err) {\n return callback(err, null);\n }\n\n // Execute the command\n executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => {\n if (err) return handleCallback(callback, err, null);\n\n return handleCallback(callback, null, result);\n });\n}\n\n/**\n * Retrieves this collections index info.\n *\n * @method\n * @param {Db} db The Db instance on which to retrieve the index info.\n * @param {string} name The name of the collection.\n * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options.\n * @param {Db~resultCallback} [callback] The command result callback\n */\nfunction indexInformation(db, name, options, callback) {\n // If we specified full information\n const full = options['full'] == null ? false : options['full'];\n\n // Did the user destroy the topology\n if (db.serverConfig && db.serverConfig.isDestroyed())\n return callback(new MongoError('topology was destroyed'));\n // Process all the results from the index command and collection\n function processResults(indexes) {\n // Contains all the information\n let info = {};\n // Process all the indexes\n for (let i = 0; i < indexes.length; i++) {\n const index = indexes[i];\n // Let's unpack the object\n info[index.name] = [];\n for (let name in index.key) {\n info[index.name].push([name, index.key[name]]);\n }\n }\n\n return info;\n }\n\n // Get the list of indexes of the specified collection\n db.collection(name)\n .listIndexes(options)\n .toArray((err, indexes) => {\n if (err) return callback(toError(err));\n if (!Array.isArray(indexes)) return handleCallback(callback, null, []);\n if (full) return handleCallback(callback, null, indexes);\n handleCallback(callback, null, processResults(indexes));\n });\n}\n\nfunction prepareDocs(coll, docs, options) {\n const forceServerObjectId =\n typeof options.forceServerObjectId === 'boolean'\n ? options.forceServerObjectId\n : coll.s.db.options.forceServerObjectId;\n\n // no need to modify the docs if server sets the ObjectId\n if (forceServerObjectId === true) {\n return docs;\n }\n\n return docs.map(doc => {\n if (forceServerObjectId !== true && doc._id == null) {\n doc._id = coll.s.pkFactory.createPk();\n }\n\n return doc;\n });\n}\n\n// Get the next available document from the cursor, returns null if no more documents are available.\nfunction nextObject(cursor, callback) {\n if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) {\n return handleCallback(\n callback,\n MongoError.create({ message: 'Cursor is closed', driver: true })\n );\n }\n\n if (cursor.s.state === CursorState.INIT && cursor.cmd && cursor.cmd.sort) {\n try {\n cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort);\n } catch (err) {\n return handleCallback(callback, err);\n }\n }\n\n // Get the next object\n cursor._next((err, doc) => {\n cursor.s.state = CursorState.OPEN;\n if (err) return handleCallback(callback, err);\n handleCallback(callback, null, doc);\n });\n}\n\nfunction insertDocuments(coll, docs, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n // Ensure we are operating on an array op docs\n docs = Array.isArray(docs) ? docs : [docs];\n\n // Final options for retryable writes and write concern\n let finalOptions = Object.assign({}, options);\n finalOptions = applyRetryableWrites(finalOptions, coll.s.db);\n finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);\n\n // If keep going set unordered\n if (finalOptions.keepGoing === true) finalOptions.ordered = false;\n finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions;\n\n docs = prepareDocs(coll, docs, options);\n\n // File inserts\n coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (err, result) => {\n if (callback == null) return;\n if (err) return handleCallback(callback, err);\n if (result == null) return handleCallback(callback, null, null);\n if (result.result.code) return handleCallback(callback, toError(result.result));\n if (result.result.writeErrors)\n return handleCallback(callback, toError(result.result.writeErrors[0]));\n // Add docs to the list\n result.ops = docs;\n // Return the results\n handleCallback(callback, null, result);\n });\n}\n\nfunction removeDocuments(coll, selector, options, callback) {\n if (typeof options === 'function') {\n (callback = options), (options = {});\n } else if (typeof selector === 'function') {\n callback = selector;\n options = {};\n selector = {};\n }\n\n // Create an empty options object if the provided one is null\n options = options || {};\n\n // Final options for retryable writes and write concern\n let finalOptions = Object.assign({}, options);\n finalOptions = applyRetryableWrites(finalOptions, coll.s.db);\n finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);\n\n // If selector is null set empty\n if (selector == null) selector = {};\n\n // Build the op\n const op = { q: selector, limit: 0 };\n if (options.single) {\n op.limit = 1;\n } else if (finalOptions.retryWrites) {\n finalOptions.retryWrites = false;\n }\n if (options.hint) {\n op.hint = options.hint;\n }\n\n // Have we specified collation\n try {\n decorateWithCollation(finalOptions, coll, options);\n } catch (err) {\n return callback(err, null);\n }\n\n // Execute the remove\n coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (err, result) => {\n if (callback == null) return;\n if (err) return handleCallback(callback, err, null);\n if (result == null) return handleCallback(callback, null, null);\n if (result.result.code) return handleCallback(callback, toError(result.result));\n if (result.result.writeErrors) {\n return handleCallback(callback, toError(result.result.writeErrors[0]));\n }\n\n // Return the results\n handleCallback(callback, null, result);\n });\n}\n\nfunction updateDocuments(coll, selector, document, options, callback) {\n if ('function' === typeof options) (callback = options), (options = null);\n if (options == null) options = {};\n if (!('function' === typeof callback)) callback = null;\n\n // If we are not providing a selector or document throw\n if (selector == null || typeof selector !== 'object')\n return callback(toError('selector must be a valid JavaScript object'));\n if (document == null || typeof document !== 'object')\n return callback(toError('document must be a valid JavaScript object'));\n\n // Final options for retryable writes and write concern\n let finalOptions = Object.assign({}, options);\n finalOptions = applyRetryableWrites(finalOptions, coll.s.db);\n finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);\n\n // Do we return the actual result document\n // Either use override on the function, or go back to default on either the collection\n // level or db\n finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions;\n\n // Execute the operation\n const op = { q: selector, u: document };\n op.upsert = options.upsert !== void 0 ? !!options.upsert : false;\n op.multi = options.multi !== void 0 ? !!options.multi : false;\n\n if (options.hint) {\n op.hint = options.hint;\n }\n\n if (finalOptions.arrayFilters) {\n op.arrayFilters = finalOptions.arrayFilters;\n delete finalOptions.arrayFilters;\n }\n\n if (finalOptions.retryWrites && op.multi) {\n finalOptions.retryWrites = false;\n }\n\n // Have we specified collation\n try {\n decorateWithCollation(finalOptions, coll, options);\n } catch (err) {\n return callback(err, null);\n }\n\n // Update options\n coll.s.topology.update(coll.s.namespace, [op], finalOptions, (err, result) => {\n if (callback == null) return;\n if (err) return handleCallback(callback, err, null);\n if (result == null) return handleCallback(callback, null, null);\n if (result.result.code) return handleCallback(callback, toError(result.result));\n if (result.result.writeErrors)\n return handleCallback(callback, toError(result.result.writeErrors[0]));\n // Return the results\n handleCallback(callback, null, result);\n });\n}\n\nfunction updateCallback(err, r, callback) {\n if (callback == null) return;\n if (err) return callback(err);\n if (r == null) return callback(null, { result: { ok: 1 } });\n r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;\n r.upsertedId =\n Array.isArray(r.result.upserted) && r.result.upserted.length > 0\n ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id`\n : null;\n r.upsertedCount =\n Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;\n r.matchedCount =\n Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;\n callback(null, r);\n}\n\nmodule.exports = {\n buildCountCommand,\n deleteCallback,\n findAndModify,\n indexInformation,\n nextObject,\n prepareDocs,\n insertDocuments,\n removeDocuments,\n updateDocuments,\n updateCallback\n};\n",null,"'use strict';\n\nconst buildCountCommand = require('./common_functions').buildCountCommand;\nconst OperationBase = require('./operation').OperationBase;\n\nclass CountOperation extends OperationBase {\n constructor(cursor, applySkipLimit, options) {\n super(options);\n\n this.cursor = cursor;\n this.applySkipLimit = applySkipLimit;\n }\n\n execute(callback) {\n const cursor = this.cursor;\n const applySkipLimit = this.applySkipLimit;\n const options = this.options;\n\n if (applySkipLimit) {\n if (typeof cursor.cursorSkip() === 'number') options.skip = cursor.cursorSkip();\n if (typeof cursor.cursorLimit() === 'number') options.limit = cursor.cursorLimit();\n }\n\n // Ensure we have the right read preference inheritance\n if (options.readPreference) {\n cursor.setReadPreference(options.readPreference);\n }\n\n if (\n typeof options.maxTimeMS !== 'number' &&\n cursor.cmd &&\n typeof cursor.cmd.maxTimeMS === 'number'\n ) {\n options.maxTimeMS = cursor.cmd.maxTimeMS;\n }\n\n let finalOptions = {};\n finalOptions.skip = options.skip;\n finalOptions.limit = options.limit;\n finalOptions.hint = options.hint;\n finalOptions.maxTimeMS = options.maxTimeMS;\n\n // Command\n finalOptions.collectionName = cursor.namespace.collection;\n\n let command;\n try {\n command = buildCountCommand(cursor, cursor.cmd.query, finalOptions);\n } catch (err) {\n return callback(err);\n }\n\n // Set cursor server to the same as the topology\n cursor.server = cursor.topology.s.coreTopology;\n\n // Execute the command\n cursor.topology.command(\n cursor.namespace.withCollection('$cmd'),\n command,\n cursor.options,\n (err, result) => {\n callback(err, result ? result.result.n : null);\n }\n );\n }\n}\n\nmodule.exports = CountOperation;\n","'use strict';\n\nconst AggregateOperation = require('./aggregate');\n\nclass CountDocumentsOperation extends AggregateOperation {\n constructor(collection, query, options) {\n const pipeline = [{ $match: query }];\n if (typeof options.skip === 'number') {\n pipeline.push({ $skip: options.skip });\n }\n\n if (typeof options.limit === 'number') {\n pipeline.push({ $limit: options.limit });\n }\n\n pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } });\n\n super(collection, pipeline, options);\n }\n\n execute(server, callback) {\n super.execute(server, (err, result) => {\n if (err) {\n callback(err, null);\n return;\n }\n\n // NOTE: We're avoiding creating a cursor here to reduce the callstack.\n const response = result.result;\n if (response.cursor == null || response.cursor.firstBatch == null) {\n callback(null, 0);\n return;\n }\n\n const docs = response.cursor.firstBatch;\n callback(null, docs.length ? docs[0].n : 0);\n });\n }\n}\n\nmodule.exports = CountDocumentsOperation;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\nconst CommandOperation = require('./command');\nconst applyWriteConcern = require('../utils').applyWriteConcern;\nconst loadCollection = require('../dynamic_loaders').loadCollection;\nconst MongoError = require('../core').MongoError;\nconst ReadPreference = require('../core').ReadPreference;\n\nconst ILLEGAL_COMMAND_FIELDS = new Set([\n 'w',\n 'wtimeout',\n 'j',\n 'fsync',\n 'autoIndexId',\n 'strict',\n 'serializeFunctions',\n 'pkFactory',\n 'raw',\n 'readPreference',\n 'session',\n 'readConcern',\n 'writeConcern'\n]);\n\nclass CreateCollectionOperation extends CommandOperation {\n constructor(db, name, options) {\n super(db, options);\n this.name = name;\n }\n\n _buildCommand() {\n const name = this.name;\n const options = this.options;\n\n const cmd = { create: name };\n for (let n in options) {\n if (\n options[n] != null &&\n typeof options[n] !== 'function' &&\n !ILLEGAL_COMMAND_FIELDS.has(n)\n ) {\n cmd[n] = options[n];\n }\n }\n\n return cmd;\n }\n\n execute(callback) {\n const db = this.db;\n const name = this.name;\n const options = this.options;\n const Collection = loadCollection();\n\n let listCollectionOptions = Object.assign({ nameOnly: true, strict: false }, options);\n listCollectionOptions = applyWriteConcern(listCollectionOptions, { db }, listCollectionOptions);\n\n function done(err) {\n if (err) {\n return callback(err);\n }\n\n try {\n callback(\n null,\n new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options)\n );\n } catch (err) {\n callback(err);\n }\n }\n\n const strictMode = listCollectionOptions.strict;\n if (strictMode) {\n db.listCollections({ name }, listCollectionOptions)\n .setReadPreference(ReadPreference.PRIMARY)\n .toArray((err, collections) => {\n if (err) {\n return callback(err);\n }\n\n if (collections.length > 0) {\n return callback(\n new MongoError(`Collection ${name} already exists. Currently in strict mode.`)\n );\n }\n\n super.execute(done);\n });\n\n return;\n }\n\n // otherwise just execute the command\n super.execute(done);\n }\n}\n\ndefineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION);\nmodule.exports = CreateCollectionOperation;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\nconst CommandOperationV2 = require('./command_v2');\nconst MongoError = require('../core').MongoError;\nconst parseIndexOptions = require('../utils').parseIndexOptions;\nconst maxWireVersion = require('../core/utils').maxWireVersion;\n\nconst VALID_INDEX_OPTIONS = new Set([\n 'background',\n 'unique',\n 'name',\n 'partialFilterExpression',\n 'sparse',\n 'expireAfterSeconds',\n 'storageEngine',\n 'collation',\n\n // text indexes\n 'weights',\n 'default_language',\n 'language_override',\n 'textIndexVersion',\n\n // 2d-sphere indexes\n '2dsphereIndexVersion',\n\n // 2d indexes\n 'bits',\n 'min',\n 'max',\n\n // geoHaystack Indexes\n 'bucketSize',\n\n // wildcard indexes\n 'wildcardProjection'\n]);\n\nclass CreateIndexesOperation extends CommandOperationV2 {\n /**\n * @ignore\n */\n constructor(parent, collection, indexes, options) {\n super(parent, options);\n this.collection = collection;\n\n // createIndex can be called with a variety of styles:\n // coll.createIndex('a');\n // coll.createIndex({ a: 1 });\n // coll.createIndex([['a', 1]]);\n // createIndexes is always called with an array of index spec objects\n if (!Array.isArray(indexes) || Array.isArray(indexes[0])) {\n this.onlyReturnNameOfCreatedIndex = true;\n // TODO: remove in v4 (breaking change); make createIndex return full response as createIndexes does\n\n const indexParameters = parseIndexOptions(indexes);\n // Generate the index name\n const name = typeof options.name === 'string' ? options.name : indexParameters.name;\n // Set up the index\n const indexSpec = { name, key: indexParameters.fieldHash };\n // merge valid index options into the index spec\n for (let optionName in options) {\n if (VALID_INDEX_OPTIONS.has(optionName)) {\n indexSpec[optionName] = options[optionName];\n }\n }\n this.indexes = [indexSpec];\n return;\n }\n\n this.indexes = indexes;\n }\n\n /**\n * @ignore\n */\n execute(server, callback) {\n const options = this.options;\n const indexes = this.indexes;\n\n const serverWireVersion = maxWireVersion(server);\n\n // Ensure we generate the correct name if the parameter is not set\n for (let i = 0; i < indexes.length; i++) {\n // Did the user pass in a collation, check if our write server supports it\n if (indexes[i].collation && serverWireVersion < 5) {\n callback(\n new MongoError(\n `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`\n )\n );\n return;\n }\n\n if (indexes[i].name == null) {\n const keys = [];\n\n for (let name in indexes[i].key) {\n keys.push(`${name}_${indexes[i].key[name]}`);\n }\n\n // Set the name\n indexes[i].name = keys.join('_');\n }\n }\n\n const cmd = { createIndexes: this.collection, indexes };\n\n if (options.commitQuorum != null) {\n if (serverWireVersion < 9) {\n callback(\n new MongoError('`commitQuorum` option for `createIndexes` not supported on servers < 4.4')\n );\n return;\n }\n cmd.commitQuorum = options.commitQuorum;\n }\n\n // collation is set on each index, it should not be defined at the root\n this.options.collation = undefined;\n\n super.executeCommand(server, cmd, (err, result) => {\n if (err) {\n callback(err);\n return;\n }\n\n callback(null, this.onlyReturnNameOfCreatedIndex ? indexes[0].name : result);\n });\n }\n}\n\ndefineAspects(CreateIndexesOperation, [Aspect.WRITE_OPERATION, Aspect.EXECUTE_WITH_SELECTION]);\n\nmodule.exports = CreateIndexesOperation;\n","'use strict';\n\nconst buildCountCommand = require('./collection_ops').buildCountCommand;\nconst handleCallback = require('../utils').handleCallback;\nconst MongoError = require('../core').MongoError;\nconst push = Array.prototype.push;\nconst CursorState = require('../core/cursor').CursorState;\n\n/**\n * Get the count of documents for this cursor.\n *\n * @method\n * @param {Cursor} cursor The Cursor instance on which to count.\n * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options.\n * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options.\n * @param {Cursor~countResultCallback} [callback] The result callback.\n */\nfunction count(cursor, applySkipLimit, opts, callback) {\n if (applySkipLimit) {\n if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip();\n if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit();\n }\n\n // Ensure we have the right read preference inheritance\n if (opts.readPreference) {\n cursor.setReadPreference(opts.readPreference);\n }\n\n if (\n typeof opts.maxTimeMS !== 'number' &&\n cursor.cmd &&\n typeof cursor.cmd.maxTimeMS === 'number'\n ) {\n opts.maxTimeMS = cursor.cmd.maxTimeMS;\n }\n\n let options = {};\n options.skip = opts.skip;\n options.limit = opts.limit;\n options.hint = opts.hint;\n options.maxTimeMS = opts.maxTimeMS;\n\n // Command\n options.collectionName = cursor.namespace.collection;\n\n let command;\n try {\n command = buildCountCommand(cursor, cursor.cmd.query, options);\n } catch (err) {\n return callback(err);\n }\n\n // Set cursor server to the same as the topology\n cursor.server = cursor.topology.s.coreTopology;\n\n // Execute the command\n cursor.topology.command(\n cursor.namespace.withCollection('$cmd'),\n command,\n cursor.options,\n (err, result) => {\n callback(err, result ? result.result.n : null);\n }\n );\n}\n\n/**\n * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information.\n *\n * @method\n * @deprecated\n * @param {Cursor} cursor The Cursor instance on which to run.\n * @param {Cursor~resultCallback} callback The result callback.\n */\nfunction each(cursor, callback) {\n if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true });\n if (cursor.isNotified()) return;\n if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) {\n return handleCallback(\n callback,\n MongoError.create({ message: 'Cursor is closed', driver: true })\n );\n }\n\n if (cursor.s.state === CursorState.INIT) {\n cursor.s.state = CursorState.OPEN;\n }\n\n // Define function to avoid global scope escape\n let fn = null;\n // Trampoline all the entries\n if (cursor.bufferedCount() > 0) {\n while ((fn = loop(cursor, callback))) fn(cursor, callback);\n each(cursor, callback);\n } else {\n cursor.next((err, item) => {\n if (err) return handleCallback(callback, err);\n if (item == null) {\n return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null));\n }\n\n if (handleCallback(callback, null, item) === false) return;\n each(cursor, callback);\n });\n }\n}\n\n// Trampoline emptying the number of retrieved items\n// without incurring a nextTick operation\nfunction loop(cursor, callback) {\n // No more items we are done\n if (cursor.bufferedCount() === 0) return;\n // Get the next document\n cursor._next(callback);\n // Loop\n return loop;\n}\n\n/**\n * Returns an array of documents. See Cursor.prototype.toArray for more information.\n *\n * @method\n * @param {Cursor} cursor The Cursor instance from which to get the next document.\n * @param {Cursor~toArrayResultCallback} [callback] The result callback.\n */\nfunction toArray(cursor, callback) {\n const items = [];\n\n // Reset cursor\n cursor.rewind();\n cursor.s.state = CursorState.INIT;\n\n // Fetch all the documents\n const fetchDocs = () => {\n cursor._next((err, doc) => {\n if (err) {\n return handleCallback(callback, err);\n }\n\n if (doc == null) {\n return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items));\n }\n\n // Add doc to items\n items.push(doc);\n\n // Get all buffered objects\n if (cursor.bufferedCount() > 0) {\n let docs = cursor.readBufferedDocuments(cursor.bufferedCount());\n\n // Transform the doc if transform method added\n if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') {\n docs = docs.map(cursor.s.transforms.doc);\n }\n\n push.apply(items, docs);\n }\n\n // Attempt a fetch\n fetchDocs();\n });\n };\n\n fetchDocs();\n}\n\nmodule.exports = { count, each, toArray };\n","'use strict';\n\nconst applyWriteConcern = require('../utils').applyWriteConcern;\nconst Code = require('../core').BSON.Code;\nconst debugOptions = require('../utils').debugOptions;\nconst handleCallback = require('../utils').handleCallback;\nconst MongoError = require('../core').MongoError;\nconst parseIndexOptions = require('../utils').parseIndexOptions;\nconst ReadPreference = require('../core').ReadPreference;\nconst toError = require('../utils').toError;\nconst CONSTANTS = require('../constants');\nconst MongoDBNamespace = require('../utils').MongoDBNamespace;\n\nconst debugFields = [\n 'authSource',\n 'w',\n 'wtimeout',\n 'j',\n 'native_parser',\n 'forceServerObjectId',\n 'serializeFunctions',\n 'raw',\n 'promoteLongs',\n 'promoteValues',\n 'promoteBuffers',\n 'bufferMaxEntries',\n 'numberOfRetries',\n 'retryMiliSeconds',\n 'readPreference',\n 'pkFactory',\n 'parentDb',\n 'promiseLibrary',\n 'noListener'\n];\n\n/**\n * Creates an index on the db and collection.\n * @method\n * @param {Db} db The Db instance on which to create an index.\n * @param {string} name Name of the collection to create the index on.\n * @param {(string|object)} fieldOrSpec Defines the index.\n * @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options.\n * @param {Db~resultCallback} [callback] The command result callback\n */\nfunction createIndex(db, name, fieldOrSpec, options, callback) {\n // Get the write concern options\n let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options);\n finalOptions = applyWriteConcern(finalOptions, { db }, options);\n\n // Ensure we have a callback\n if (finalOptions.writeConcern && typeof callback !== 'function') {\n throw MongoError.create({\n message: 'Cannot use a writeConcern without a provided callback',\n driver: true\n });\n }\n\n // Did the user destroy the topology\n if (db.serverConfig && db.serverConfig.isDestroyed())\n return callback(new MongoError('topology was destroyed'));\n\n // Attempt to run using createIndexes command\n createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => {\n if (err == null) return handleCallback(callback, err, result);\n\n /**\n * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert:\n * 67 = 'CannotCreateIndex' (malformed index options)\n * 85 = 'IndexOptionsConflict' (index already exists with different options)\n * 86 = 'IndexKeySpecsConflict' (index already exists with the same name)\n * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes)\n * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown)\n * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`)\n */\n if (\n err.code === 67 ||\n err.code === 11000 ||\n err.code === 85 ||\n err.code === 86 ||\n err.code === 11600 ||\n err.code === 197\n ) {\n return handleCallback(callback, err, result);\n }\n\n // Create command\n const doc = createCreateIndexCommand(db, name, fieldOrSpec, options);\n // Set no key checking\n finalOptions.checkKeys = false;\n // Insert document\n db.s.topology.insert(\n db.s.namespace.withCollection(CONSTANTS.SYSTEM_INDEX_COLLECTION),\n doc,\n finalOptions,\n (err, result) => {\n if (callback == null) return;\n if (err) return handleCallback(callback, err);\n if (result == null) return handleCallback(callback, null, null);\n if (result.result.writeErrors)\n return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null);\n handleCallback(callback, null, doc.name);\n }\n );\n });\n}\n\n// Add listeners to topology\nfunction createListener(db, e, object) {\n function listener(err) {\n if (object.listeners(e).length > 0) {\n object.emit(e, err, db);\n\n // Emit on all associated db's if available\n for (let i = 0; i < db.s.children.length; i++) {\n db.s.children[i].emit(e, err, db.s.children[i]);\n }\n }\n }\n return listener;\n}\n\n/**\n * Ensures that an index exists. If it does not, creates it.\n *\n * @method\n * @param {Db} db The Db instance on which to ensure the index.\n * @param {string} name The index name\n * @param {(string|object)} fieldOrSpec Defines the index.\n * @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options.\n * @param {Db~resultCallback} [callback] The command result callback\n */\nfunction ensureIndex(db, name, fieldOrSpec, options, callback) {\n // Get the write concern options\n const finalOptions = applyWriteConcern({}, { db }, options);\n // Create command\n const selector = createCreateIndexCommand(db, name, fieldOrSpec, options);\n const index_name = selector.name;\n\n // Did the user destroy the topology\n if (db.serverConfig && db.serverConfig.isDestroyed())\n return callback(new MongoError('topology was destroyed'));\n\n // Merge primary readPreference\n finalOptions.readPreference = ReadPreference.PRIMARY;\n\n // Check if the index already exists\n indexInformation(db, name, finalOptions, (err, indexInformation) => {\n if (err != null && err.code !== 26) return handleCallback(callback, err, null);\n // If the index does not exist, create it\n if (indexInformation == null || !indexInformation[index_name]) {\n createIndex(db, name, fieldOrSpec, options, callback);\n } else {\n if (typeof callback === 'function') return handleCallback(callback, null, index_name);\n }\n });\n}\n\n/**\n * Evaluate JavaScript on the server\n *\n * @method\n * @param {Db} db The Db instance.\n * @param {Code} code JavaScript to execute on server.\n * @param {(object|array)} parameters The parameters for the call.\n * @param {object} [options] Optional settings. See Db.prototype.eval for a list of options.\n * @param {Db~resultCallback} [callback] The results callback\n * @deprecated Eval is deprecated on MongoDB 3.2 and forward\n */\nfunction evaluate(db, code, parameters, options, callback) {\n let finalCode = code;\n let finalParameters = [];\n\n // Did the user destroy the topology\n if (db.serverConfig && db.serverConfig.isDestroyed())\n return callback(new MongoError('topology was destroyed'));\n\n // If not a code object translate to one\n if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode);\n // Ensure the parameters are correct\n if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') {\n finalParameters = [parameters];\n } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') {\n finalParameters = parameters;\n }\n\n // Create execution selector\n let cmd = { $eval: finalCode, args: finalParameters };\n // Check if the nolock parameter is passed in\n if (options['nolock']) {\n cmd['nolock'] = options['nolock'];\n }\n\n // Set primary read preference\n options.readPreference = new ReadPreference(ReadPreference.PRIMARY);\n\n // Execute the command\n executeCommand(db, cmd, options, (err, result) => {\n if (err) return handleCallback(callback, err, null);\n if (result && result.ok === 1) return handleCallback(callback, null, result.retval);\n if (result)\n return handleCallback(\n callback,\n MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }),\n null\n );\n handleCallback(callback, err, result);\n });\n}\n\n/**\n * Execute a command\n *\n * @method\n * @param {Db} db The Db instance on which to execute the command.\n * @param {object} command The command hash\n * @param {object} [options] Optional settings. See Db.prototype.command for a list of options.\n * @param {Db~resultCallback} [callback] The command result callback\n */\nfunction executeCommand(db, command, options, callback) {\n // Did the user destroy the topology\n if (db.serverConfig && db.serverConfig.isDestroyed())\n return callback(new MongoError('topology was destroyed'));\n // Get the db name we are executing against\n const dbName = options.dbName || options.authdb || db.databaseName;\n\n // Convert the readPreference if its not a write\n options.readPreference = ReadPreference.resolve(db, options);\n\n // Debug information\n if (db.s.logger.isDebug())\n db.s.logger.debug(\n `executing command ${JSON.stringify(\n command\n )} against ${dbName}.$cmd with options [${JSON.stringify(\n debugOptions(debugFields, options)\n )}]`\n );\n\n // Execute command\n db.s.topology.command(db.s.namespace.withCollection('$cmd'), command, options, (err, result) => {\n if (err) return handleCallback(callback, err);\n if (options.full) return handleCallback(callback, null, result);\n handleCallback(callback, null, result.result);\n });\n}\n\n/**\n * Runs a command on the database as admin.\n *\n * @method\n * @param {Db} db The Db instance on which to execute the command.\n * @param {object} command The command hash\n * @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options.\n * @param {Db~resultCallback} [callback] The command result callback\n */\nfunction executeDbAdminCommand(db, command, options, callback) {\n const namespace = new MongoDBNamespace('admin', '$cmd');\n\n db.s.topology.command(namespace, command, options, (err, result) => {\n // Did the user destroy the topology\n if (db.serverConfig && db.serverConfig.isDestroyed()) {\n return callback(new MongoError('topology was destroyed'));\n }\n\n if (err) return handleCallback(callback, err);\n handleCallback(callback, null, result.result);\n });\n}\n\n/**\n * Retrieves this collections index info.\n *\n * @method\n * @param {Db} db The Db instance on which to retrieve the index info.\n * @param {string} name The name of the collection.\n * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options.\n * @param {Db~resultCallback} [callback] The command result callback\n */\nfunction indexInformation(db, name, options, callback) {\n // If we specified full information\n const full = options['full'] == null ? false : options['full'];\n\n // Did the user destroy the topology\n if (db.serverConfig && db.serverConfig.isDestroyed())\n return callback(new MongoError('topology was destroyed'));\n // Process all the results from the index command and collection\n function processResults(indexes) {\n // Contains all the information\n let info = {};\n // Process all the indexes\n for (let i = 0; i < indexes.length; i++) {\n const index = indexes[i];\n // Let's unpack the object\n info[index.name] = [];\n for (let name in index.key) {\n info[index.name].push([name, index.key[name]]);\n }\n }\n\n return info;\n }\n\n // Get the list of indexes of the specified collection\n db.collection(name)\n .listIndexes(options)\n .toArray((err, indexes) => {\n if (err) return callback(toError(err));\n if (!Array.isArray(indexes)) return handleCallback(callback, null, []);\n if (full) return handleCallback(callback, null, indexes);\n handleCallback(callback, null, processResults(indexes));\n });\n}\n\n/**\n * Retrieve the current profiling information for MongoDB\n *\n * @method\n * @param {Db} db The Db instance on which to retrieve the profiling info.\n * @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options.\n * @param {Db~resultCallback} [callback] The command result callback.\n * @deprecated Query the system.profile collection directly.\n */\nfunction profilingInfo(db, options, callback) {\n try {\n db.collection('system.profile')\n .find({}, options)\n .toArray(callback);\n } catch (err) {\n return callback(err, null);\n }\n}\n\n// Validate the database name\nfunction validateDatabaseName(databaseName) {\n if (typeof databaseName !== 'string')\n throw MongoError.create({ message: 'database name must be a string', driver: true });\n if (databaseName.length === 0)\n throw MongoError.create({ message: 'database name cannot be the empty string', driver: true });\n if (databaseName === '$external') return;\n\n const invalidChars = [' ', '.', '$', '/', '\\\\'];\n for (let i = 0; i < invalidChars.length; i++) {\n if (databaseName.indexOf(invalidChars[i]) !== -1)\n throw MongoError.create({\n message: \"database names cannot contain the character '\" + invalidChars[i] + \"'\",\n driver: true\n });\n }\n}\n\n/**\n * Create the command object for Db.prototype.createIndex.\n *\n * @param {Db} db The Db instance on which to create the command.\n * @param {string} name Name of the collection to create the index on.\n * @param {(string|object)} fieldOrSpec Defines the index.\n * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options.\n * @return {Object} The insert command object.\n */\nfunction createCreateIndexCommand(db, name, fieldOrSpec, options) {\n const indexParameters = parseIndexOptions(fieldOrSpec);\n const fieldHash = indexParameters.fieldHash;\n\n // Generate the index name\n const indexName = typeof options.name === 'string' ? options.name : indexParameters.name;\n const selector = {\n ns: db.s.namespace.withCollection(name).toString(),\n key: fieldHash,\n name: indexName\n };\n\n // Ensure we have a correct finalUnique\n const finalUnique = options == null || 'object' === typeof options ? false : options;\n // Set up options\n options = options == null || typeof options === 'boolean' ? {} : options;\n\n // Add all the options\n const keysToOmit = Object.keys(selector);\n for (let optionName in options) {\n if (keysToOmit.indexOf(optionName) === -1) {\n selector[optionName] = options[optionName];\n }\n }\n\n if (selector['unique'] == null) selector['unique'] = finalUnique;\n\n // Remove any write concern operations\n const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session'];\n for (let i = 0; i < removeKeys.length; i++) {\n delete selector[removeKeys[i]];\n }\n\n // Return the command creation selector\n return selector;\n}\n\n/**\n * Create index using the createIndexes command.\n *\n * @param {Db} db The Db instance on which to execute the command.\n * @param {string} name Name of the collection to create the index on.\n * @param {(string|object)} fieldOrSpec Defines the index.\n * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options.\n * @param {Db~resultCallback} [callback] The command result callback.\n */\nfunction createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) {\n // Build the index\n const indexParameters = parseIndexOptions(fieldOrSpec);\n // Generate the index name\n const indexName = typeof options.name === 'string' ? options.name : indexParameters.name;\n // Set up the index\n const indexes = [{ name: indexName, key: indexParameters.fieldHash }];\n // merge all the options\n const keysToOmit = Object.keys(indexes[0]).concat([\n 'writeConcern',\n 'w',\n 'wtimeout',\n 'j',\n 'fsync',\n 'readPreference',\n 'session'\n ]);\n\n for (let optionName in options) {\n if (keysToOmit.indexOf(optionName) === -1) {\n indexes[0][optionName] = options[optionName];\n }\n }\n\n // Get capabilities\n const capabilities = db.s.topology.capabilities();\n\n // Did the user pass in a collation, check if our write server supports it\n if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) {\n // Create a new error\n const error = new MongoError('server/primary/mongos does not support collation');\n error.code = 67;\n // Return the error\n return callback(error);\n }\n\n // Create command, apply write concern to command\n const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options);\n\n // ReadPreference primary\n options.readPreference = ReadPreference.PRIMARY;\n\n // Build the command\n executeCommand(db, cmd, options, (err, result) => {\n if (err) return handleCallback(callback, err, null);\n if (result.ok === 0) return handleCallback(callback, toError(result), null);\n // Return the indexName for backward compatibility\n handleCallback(callback, null, indexName);\n });\n}\n\nmodule.exports = {\n createListener,\n createIndex,\n ensureIndex,\n evaluate,\n executeCommand,\n executeDbAdminCommand,\n indexInformation,\n profilingInfo,\n validateDatabaseName\n};\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst deleteCallback = require('./common_functions').deleteCallback;\nconst removeDocuments = require('./common_functions').removeDocuments;\n\nclass DeleteManyOperation extends OperationBase {\n constructor(collection, filter, options) {\n super(options);\n\n this.collection = collection;\n this.filter = filter;\n }\n\n execute(callback) {\n const coll = this.collection;\n const filter = this.filter;\n const options = this.options;\n\n options.single = false;\n removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback));\n }\n}\n\nmodule.exports = DeleteManyOperation;\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst deleteCallback = require('./common_functions').deleteCallback;\nconst removeDocuments = require('./common_functions').removeDocuments;\n\nclass DeleteOneOperation extends OperationBase {\n constructor(collection, filter, options) {\n super(options);\n\n this.collection = collection;\n this.filter = filter;\n }\n\n execute(callback) {\n const coll = this.collection;\n const filter = this.filter;\n const options = this.options;\n\n options.single = true;\n removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback));\n }\n}\n\nmodule.exports = DeleteOneOperation;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\nconst CommandOperationV2 = require('./command_v2');\nconst decorateWithCollation = require('../utils').decorateWithCollation;\nconst decorateWithReadConcern = require('../utils').decorateWithReadConcern;\n\n/**\n * Return a list of distinct values for the given key across a collection.\n *\n * @class\n * @property {Collection} a Collection instance.\n * @property {string} key Field of the document to find distinct values for.\n * @property {object} query The query for filtering the set of documents to which we apply the distinct filter.\n * @property {object} [options] Optional settings. See Collection.prototype.distinct for a list of options.\n */\nclass DistinctOperation extends CommandOperationV2 {\n /**\n * Construct a Distinct operation.\n *\n * @param {Collection} a Collection instance.\n * @param {string} key Field of the document to find distinct values for.\n * @param {object} query The query for filtering the set of documents to which we apply the distinct filter.\n * @param {object} [options] Optional settings. See Collection.prototype.distinct for a list of options.\n */\n constructor(collection, key, query, options) {\n super(collection, options);\n\n this.collection = collection;\n this.key = key;\n this.query = query;\n }\n\n /**\n * Execute the operation.\n *\n * @param {Collection~resultCallback} [callback] The command result callback\n */\n execute(server, callback) {\n const coll = this.collection;\n const key = this.key;\n const query = this.query;\n const options = this.options;\n\n // Distinct command\n const cmd = {\n distinct: coll.collectionName,\n key: key,\n query: query\n };\n\n // Add maxTimeMS if defined\n if (typeof options.maxTimeMS === 'number') {\n cmd.maxTimeMS = options.maxTimeMS;\n }\n\n // Do we have a readConcern specified\n decorateWithReadConcern(cmd, coll, options);\n\n // Have we specified collation\n try {\n decorateWithCollation(cmd, coll, options);\n } catch (err) {\n return callback(err, null);\n }\n\n super.executeCommand(server, cmd, (err, result) => {\n if (err) {\n callback(err);\n return;\n }\n\n callback(null, this.options.full ? result : result.values);\n });\n }\n}\n\ndefineAspects(DistinctOperation, [\n Aspect.READ_OPERATION,\n Aspect.RETRYABLE,\n Aspect.EXECUTE_WITH_SELECTION\n]);\n\nmodule.exports = DistinctOperation;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst CommandOperation = require('./command');\nconst defineAspects = require('./operation').defineAspects;\nconst handleCallback = require('../utils').handleCallback;\n\nclass DropOperation extends CommandOperation {\n constructor(db, options) {\n const finalOptions = Object.assign({}, options, db.s.options);\n\n if (options.session) {\n finalOptions.session = options.session;\n }\n\n super(db, finalOptions);\n }\n\n execute(callback) {\n super.execute((err, result) => {\n if (err) return handleCallback(callback, err);\n if (result.ok) return handleCallback(callback, null, true);\n handleCallback(callback, null, false);\n });\n }\n}\n\ndefineAspects(DropOperation, Aspect.WRITE_OPERATION);\n\nclass DropCollectionOperation extends DropOperation {\n constructor(db, name, options) {\n super(db, options);\n\n this.name = name;\n this.namespace = `${db.namespace}.${name}`;\n }\n\n _buildCommand() {\n return { drop: this.name };\n }\n}\n\nclass DropDatabaseOperation extends DropOperation {\n _buildCommand() {\n return { dropDatabase: 1 };\n }\n}\n\nmodule.exports = {\n DropOperation,\n DropCollectionOperation,\n DropDatabaseOperation\n};\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\nconst CommandOperation = require('./command');\nconst applyWriteConcern = require('../utils').applyWriteConcern;\nconst handleCallback = require('../utils').handleCallback;\n\nclass DropIndexOperation extends CommandOperation {\n constructor(collection, indexName, options) {\n super(collection.s.db, options, collection);\n\n this.collection = collection;\n this.indexName = indexName;\n }\n\n _buildCommand() {\n const collection = this.collection;\n const indexName = this.indexName;\n const options = this.options;\n\n let cmd = { dropIndexes: collection.collectionName, index: indexName };\n\n // Decorate command with writeConcern if supported\n cmd = applyWriteConcern(cmd, { db: collection.s.db, collection }, options);\n\n return cmd;\n }\n\n execute(callback) {\n // Execute command\n super.execute((err, result) => {\n if (typeof callback !== 'function') return;\n if (err) return handleCallback(callback, err, null);\n handleCallback(callback, null, result);\n });\n }\n}\n\ndefineAspects(DropIndexOperation, Aspect.WRITE_OPERATION);\n\nmodule.exports = DropIndexOperation;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\nconst DropIndexOperation = require('./drop_index');\nconst handleCallback = require('../utils').handleCallback;\n\nclass DropIndexesOperation extends DropIndexOperation {\n constructor(collection, options) {\n super(collection, '*', options);\n }\n\n execute(callback) {\n super.execute(err => {\n if (err) return handleCallback(callback, err, false);\n handleCallback(callback, null, true);\n });\n }\n}\n\ndefineAspects(DropIndexesOperation, Aspect.WRITE_OPERATION);\n\nmodule.exports = DropIndexesOperation;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\nconst CommandOperationV2 = require('./command_v2');\n\nclass EstimatedDocumentCountOperation extends CommandOperationV2 {\n constructor(collection, query, options) {\n if (typeof options === 'undefined') {\n options = query;\n query = undefined;\n }\n\n super(collection, options);\n this.collectionName = collection.s.namespace.collection;\n if (query) {\n this.query = query;\n }\n }\n\n execute(server, callback) {\n const options = this.options;\n const cmd = { count: this.collectionName };\n\n if (this.query) {\n cmd.query = this.query;\n }\n\n if (typeof options.skip === 'number') {\n cmd.skip = options.skip;\n }\n\n if (typeof options.limit === 'number') {\n cmd.limit = options.limit;\n }\n\n if (options.hint) {\n cmd.hint = options.hint;\n }\n\n super.executeCommand(server, cmd, (err, response) => {\n if (err) {\n callback(err);\n return;\n }\n\n callback(null, response.n);\n });\n }\n}\n\ndefineAspects(EstimatedDocumentCountOperation, [\n Aspect.READ_OPERATION,\n Aspect.RETRYABLE,\n Aspect.EXECUTE_WITH_SELECTION\n]);\n\nmodule.exports = EstimatedDocumentCountOperation;\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst handleCallback = require('../utils').handleCallback;\nconst MongoError = require('../core').MongoError;\nconst MongoDBNamespace = require('../utils').MongoDBNamespace;\n\nclass ExecuteDbAdminCommandOperation extends OperationBase {\n constructor(db, selector, options) {\n super(options);\n\n this.db = db;\n this.selector = selector;\n }\n\n execute(callback) {\n const db = this.db;\n const selector = this.selector;\n const options = this.options;\n\n const namespace = new MongoDBNamespace('admin', '$cmd');\n db.s.topology.command(namespace, selector, options, (err, result) => {\n // Did the user destroy the topology\n if (db.serverConfig && db.serverConfig.isDestroyed()) {\n return callback(new MongoError('topology was destroyed'));\n }\n\n if (err) return handleCallback(callback, err);\n handleCallback(callback, null, result.result);\n });\n }\n}\n\nmodule.exports = ExecuteDbAdminCommandOperation;\n","'use strict';\n\nconst MongoError = require('../core/error').MongoError;\nconst Aspect = require('./operation').Aspect;\nconst OperationBase = require('./operation').OperationBase;\nconst ReadPreference = require('../core/topologies/read_preference');\nconst isRetryableError = require('../core/error').isRetryableError;\nconst maxWireVersion = require('../core/utils').maxWireVersion;\nconst isUnifiedTopology = require('../core/utils').isUnifiedTopology;\n\n/**\n * Executes the given operation with provided arguments.\n *\n * This method reduces large amounts of duplication in the entire codebase by providing\n * a single point for determining whether callbacks or promises should be used. Additionally\n * it allows for a single point of entry to provide features such as implicit sessions, which\n * are required by the Driver Sessions specification in the event that a ClientSession is\n * not provided\n *\n * @param {object} topology The topology to execute this operation on\n * @param {Operation} operation The operation to execute\n * @param {function} callback The command result callback\n */\nfunction executeOperation(topology, operation, callback) {\n if (topology == null) {\n throw new TypeError('This method requires a valid topology instance');\n }\n\n if (!(operation instanceof OperationBase)) {\n throw new TypeError('This method requires a valid operation instance');\n }\n\n if (isUnifiedTopology(topology) && topology.shouldCheckForSessionSupport()) {\n return selectServerForSessionSupport(topology, operation, callback);\n }\n\n const Promise = topology.s.promiseLibrary;\n\n // The driver sessions spec mandates that we implicitly create sessions for operations\n // that are not explicitly provided with a session.\n let session, owner;\n if (topology.hasSessionSupport()) {\n if (operation.session == null) {\n owner = Symbol();\n session = topology.startSession({ owner });\n operation.session = session;\n } else if (operation.session.hasEnded) {\n throw new MongoError('Use of expired sessions is not permitted');\n }\n }\n\n let result;\n if (typeof callback !== 'function') {\n result = new Promise((resolve, reject) => {\n callback = (err, res) => {\n if (err) return reject(err);\n resolve(res);\n };\n });\n }\n\n function executeCallback(err, result) {\n if (session && session.owner === owner) {\n session.endSession();\n if (operation.session === session) {\n operation.clearSession();\n }\n }\n\n callback(err, result);\n }\n\n try {\n if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) {\n executeWithServerSelection(topology, operation, executeCallback);\n } else {\n operation.execute(executeCallback);\n }\n } catch (e) {\n if (session && session.owner === owner) {\n session.endSession();\n if (operation.session === session) {\n operation.clearSession();\n }\n }\n\n throw e;\n }\n\n return result;\n}\n\nfunction supportsRetryableReads(server) {\n return maxWireVersion(server) >= 6;\n}\n\nfunction executeWithServerSelection(topology, operation, callback) {\n const readPreference = operation.readPreference || ReadPreference.primary;\n const inTransaction = operation.session && operation.session.inTransaction();\n\n if (inTransaction && !readPreference.equals(ReadPreference.primary)) {\n callback(\n new MongoError(\n `Read preference in a transaction must be primary, not: ${readPreference.mode}`\n )\n );\n\n return;\n }\n\n const serverSelectionOptions = {\n readPreference,\n session: operation.session\n };\n\n function callbackWithRetry(err, result) {\n if (err == null) {\n return callback(null, result);\n }\n\n if (!isRetryableError(err)) {\n return callback(err);\n }\n\n // select a new server, and attempt to retry the operation\n topology.selectServer(serverSelectionOptions, (err, server) => {\n if (err || !supportsRetryableReads(server)) {\n callback(err, null);\n return;\n }\n\n operation.execute(server, callback);\n });\n }\n\n // select a server, and execute the operation against it\n topology.selectServer(serverSelectionOptions, (err, server) => {\n if (err) {\n callback(err, null);\n return;\n }\n\n const shouldRetryReads =\n topology.s.options.retryReads !== false &&\n operation.session &&\n !inTransaction &&\n supportsRetryableReads(server) &&\n operation.canRetryRead;\n\n if (operation.hasAspect(Aspect.RETRYABLE) && shouldRetryReads) {\n operation.execute(server, callbackWithRetry);\n return;\n }\n\n operation.execute(server, callback);\n });\n}\n\n// TODO: This is only supported for unified topology, it should go away once\n// we remove support for legacy topology types.\nfunction selectServerForSessionSupport(topology, operation, callback) {\n const Promise = topology.s.promiseLibrary;\n\n let result;\n if (typeof callback !== 'function') {\n result = new Promise((resolve, reject) => {\n callback = (err, result) => {\n if (err) return reject(err);\n resolve(result);\n };\n });\n }\n\n topology.selectServer(ReadPreference.primaryPreferred, err => {\n if (err) {\n callback(err);\n return;\n }\n\n executeOperation(topology, operation, callback);\n });\n\n return result;\n}\n\nmodule.exports = executeOperation;\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\nconst ReadPreference = require('../core').ReadPreference;\nconst maxWireVersion = require('../core/utils').maxWireVersion;\nconst MongoError = require('../core/error').MongoError;\n\nclass FindOperation extends OperationBase {\n constructor(collection, ns, command, options) {\n super(options);\n\n this.ns = ns;\n this.cmd = command;\n this.readPreference = ReadPreference.resolve(collection, this.options);\n }\n\n execute(server, callback) {\n // copied from `CommandOperationV2`, to be subclassed in the future\n this.server = server;\n\n if (typeof this.cmd.allowDiskUse !== 'undefined' && maxWireVersion(server) < 4) {\n callback(new MongoError('The `allowDiskUse` option is not supported on MongoDB < 3.2'));\n return;\n }\n\n // TOOD: use `MongoDBNamespace` through and through\n const cursorState = this.cursorState || {};\n server.query(this.ns.toString(), this.cmd, cursorState, this.options, callback);\n }\n}\n\ndefineAspects(FindOperation, [\n Aspect.READ_OPERATION,\n Aspect.RETRYABLE,\n Aspect.EXECUTE_WITH_SELECTION\n]);\n\nmodule.exports = FindOperation;\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst applyRetryableWrites = require('../utils').applyRetryableWrites;\nconst applyWriteConcern = require('../utils').applyWriteConcern;\nconst decorateWithCollation = require('../utils').decorateWithCollation;\nconst executeCommand = require('./db_ops').executeCommand;\nconst formattedOrderClause = require('../utils').formattedOrderClause;\nconst handleCallback = require('../utils').handleCallback;\nconst ReadPreference = require('../core').ReadPreference;\nconst maxWireVersion = require('../core/utils').maxWireVersion;\nconst MongoError = require('../error').MongoError;\n\nclass FindAndModifyOperation extends OperationBase {\n constructor(collection, query, sort, doc, options) {\n super(options);\n\n this.collection = collection;\n this.query = query;\n this.sort = sort;\n this.doc = doc;\n }\n\n execute(callback) {\n const coll = this.collection;\n const query = this.query;\n const sort = formattedOrderClause(this.sort);\n const doc = this.doc;\n let options = this.options;\n\n // Create findAndModify command object\n const queryObject = {\n findAndModify: coll.collectionName,\n query: query\n };\n\n if (sort) {\n queryObject.sort = sort;\n }\n\n queryObject.new = options.new ? true : false;\n queryObject.remove = options.remove ? true : false;\n queryObject.upsert = options.upsert ? true : false;\n\n const projection = options.projection || options.fields;\n\n if (projection) {\n queryObject.fields = projection;\n }\n\n if (options.arrayFilters) {\n queryObject.arrayFilters = options.arrayFilters;\n }\n\n if (doc && !options.remove) {\n queryObject.update = doc;\n }\n\n if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS;\n\n // Either use override on the function, or go back to default on either the collection\n // level or db\n options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions;\n\n // No check on the documents\n options.checkKeys = false;\n\n // Final options for retryable writes and write concern\n options = applyRetryableWrites(options, coll.s.db);\n options = applyWriteConcern(options, { db: coll.s.db, collection: coll }, options);\n\n // Decorate the findAndModify command with the write Concern\n if (options.writeConcern) {\n queryObject.writeConcern = options.writeConcern;\n }\n\n // Have we specified bypassDocumentValidation\n if (options.bypassDocumentValidation === true) {\n queryObject.bypassDocumentValidation = options.bypassDocumentValidation;\n }\n\n options.readPreference = ReadPreference.primary;\n\n // Have we specified collation\n try {\n decorateWithCollation(queryObject, coll, options);\n } catch (err) {\n return callback(err, null);\n }\n\n if (options.hint) {\n // TODO: once this method becomes a CommandOperationV2 we will have the server\n // in place to check.\n const unacknowledgedWrite = options.writeConcern && options.writeConcern.w === 0;\n if (unacknowledgedWrite || maxWireVersion(coll.s.topology) < 8) {\n callback(\n new MongoError('The current topology does not support a hint on findAndModify commands')\n );\n\n return;\n }\n\n queryObject.hint = options.hint;\n }\n\n // Execute the command\n executeCommand(coll.s.db, queryObject, options, (err, result) => {\n if (err) return handleCallback(callback, err, null);\n\n return handleCallback(callback, null, result);\n });\n }\n}\n\nmodule.exports = FindAndModifyOperation;\n","'use strict';\n\nconst handleCallback = require('../utils').handleCallback;\nconst OperationBase = require('./operation').OperationBase;\nconst toError = require('../utils').toError;\n\nclass FindOneOperation extends OperationBase {\n constructor(collection, query, options) {\n super(options);\n\n this.collection = collection;\n this.query = query;\n }\n\n execute(callback) {\n const coll = this.collection;\n const query = this.query;\n const options = this.options;\n\n try {\n const cursor = coll\n .find(query, options)\n .limit(-1)\n .batchSize(1);\n\n // Return the item\n cursor.next((err, item) => {\n if (err != null) return handleCallback(callback, toError(err), null);\n handleCallback(callback, null, item);\n });\n } catch (e) {\n callback(e);\n }\n }\n}\n\nmodule.exports = FindOneOperation;\n","'use strict';\n\nconst FindAndModifyOperation = require('./find_and_modify');\n\nclass FindOneAndDeleteOperation extends FindAndModifyOperation {\n constructor(collection, filter, options) {\n // Final options\n const finalOptions = Object.assign({}, options);\n finalOptions.fields = options.projection;\n finalOptions.remove = true;\n\n // Basic validation\n if (filter == null || typeof filter !== 'object') {\n throw new TypeError('Filter parameter must be an object');\n }\n\n super(collection, filter, finalOptions.sort, null, finalOptions);\n }\n}\n\nmodule.exports = FindOneAndDeleteOperation;\n","'use strict';\n\nconst FindAndModifyOperation = require('./find_and_modify');\nconst hasAtomicOperators = require('../utils').hasAtomicOperators;\n\nclass FindOneAndReplaceOperation extends FindAndModifyOperation {\n constructor(collection, filter, replacement, options) {\n // Final options\n const finalOptions = Object.assign({}, options);\n finalOptions.fields = options.projection;\n finalOptions.update = true;\n finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false;\n finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false;\n\n if (filter == null || typeof filter !== 'object') {\n throw new TypeError('Filter parameter must be an object');\n }\n\n if (replacement == null || typeof replacement !== 'object') {\n throw new TypeError('Replacement parameter must be an object');\n }\n\n if (hasAtomicOperators(replacement)) {\n throw new TypeError('Replacement document must not contain atomic operators');\n }\n\n super(collection, filter, finalOptions.sort, replacement, finalOptions);\n }\n}\n\nmodule.exports = FindOneAndReplaceOperation;\n","'use strict';\n\nconst FindAndModifyOperation = require('./find_and_modify');\nconst hasAtomicOperators = require('../utils').hasAtomicOperators;\n\nclass FindOneAndUpdateOperation extends FindAndModifyOperation {\n constructor(collection, filter, update, options) {\n // Final options\n const finalOptions = Object.assign({}, options);\n finalOptions.fields = options.projection;\n finalOptions.update = true;\n finalOptions.new =\n typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false;\n finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false;\n\n if (filter == null || typeof filter !== 'object') {\n throw new TypeError('Filter parameter must be an object');\n }\n\n if (update == null || typeof update !== 'object') {\n throw new TypeError('Update parameter must be an object');\n }\n\n if (!hasAtomicOperators(update)) {\n throw new TypeError('Update document requires atomic operators');\n }\n\n super(collection, filter, finalOptions.sort, update, finalOptions);\n }\n}\n\nmodule.exports = FindOneAndUpdateOperation;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\nconst OperationBase = require('./operation').OperationBase;\nconst decorateCommand = require('../utils').decorateCommand;\nconst decorateWithReadConcern = require('../utils').decorateWithReadConcern;\nconst executeCommand = require('./db_ops').executeCommand;\nconst handleCallback = require('../utils').handleCallback;\nconst ReadPreference = require('../core').ReadPreference;\nconst toError = require('../utils').toError;\n\n/**\n * Execute a geo search using a geo haystack index on a collection.\n *\n * @class\n * @property {Collection} a Collection instance.\n * @property {number} x Point to search on the x axis, ensure the indexes are ordered in the same order.\n * @property {number} y Point to search on the y axis, ensure the indexes are ordered in the same order.\n * @property {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options.\n */\nclass GeoHaystackSearchOperation extends OperationBase {\n /**\n * Construct a GeoHaystackSearch operation.\n *\n * @param {Collection} a Collection instance.\n * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order.\n * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order.\n * @param {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options.\n */\n constructor(collection, x, y, options) {\n super(options);\n\n this.collection = collection;\n this.x = x;\n this.y = y;\n }\n\n /**\n * Execute the operation.\n *\n * @param {Collection~resultCallback} [callback] The command result callback\n */\n execute(callback) {\n const coll = this.collection;\n const x = this.x;\n const y = this.y;\n let options = this.options;\n\n // Build command object\n let commandObject = {\n geoSearch: coll.collectionName,\n near: [x, y]\n };\n\n // Remove read preference from hash if it exists\n commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']);\n\n options = Object.assign({}, options);\n // Ensure we have the right read preference inheritance\n options.readPreference = ReadPreference.resolve(coll, options);\n\n // Do we have a readConcern specified\n decorateWithReadConcern(commandObject, coll, options);\n\n // Execute the command\n executeCommand(coll.s.db, commandObject, options, (err, res) => {\n if (err) return handleCallback(callback, err);\n if (res.err || res.errmsg) handleCallback(callback, toError(res));\n // should we only be returning res.results here? Not sure if the user\n // should see the other return information\n handleCallback(callback, null, res);\n });\n }\n}\n\ndefineAspects(GeoHaystackSearchOperation, Aspect.READ_OPERATION);\n\nmodule.exports = GeoHaystackSearchOperation;\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst handleCallback = require('../utils').handleCallback;\nconst indexInformationDb = require('./db_ops').indexInformation;\n\nclass IndexExistsOperation extends OperationBase {\n constructor(collection, indexes, options) {\n super(options);\n\n this.collection = collection;\n this.indexes = indexes;\n }\n\n execute(callback) {\n const coll = this.collection;\n const indexes = this.indexes;\n const options = this.options;\n\n indexInformationDb(coll.s.db, coll.collectionName, options, (err, indexInformation) => {\n // If we have an error return\n if (err != null) return handleCallback(callback, err, null);\n // Let's check for the index names\n if (!Array.isArray(indexes))\n return handleCallback(callback, null, indexInformation[indexes] != null);\n // Check in list of indexes\n for (let i = 0; i < indexes.length; i++) {\n if (indexInformation[indexes[i]] == null) {\n return handleCallback(callback, null, false);\n }\n }\n\n // All keys found return true\n return handleCallback(callback, null, true);\n });\n }\n}\n\nmodule.exports = IndexExistsOperation;\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst indexInformation = require('./common_functions').indexInformation;\n\nclass IndexInformationOperation extends OperationBase {\n constructor(db, name, options) {\n super(options);\n\n this.db = db;\n this.name = name;\n }\n\n execute(callback) {\n const db = this.db;\n const name = this.name;\n const options = this.options;\n\n indexInformation(db, name, options, callback);\n }\n}\n\nmodule.exports = IndexInformationOperation;\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst indexInformation = require('./common_functions').indexInformation;\n\nclass IndexesOperation extends OperationBase {\n constructor(collection, options) {\n super(options);\n\n this.collection = collection;\n }\n\n execute(callback) {\n const coll = this.collection;\n let options = this.options;\n\n options = Object.assign({}, { full: true }, options);\n indexInformation(coll.s.db, coll.collectionName, options, callback);\n }\n}\n\nmodule.exports = IndexesOperation;\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst BulkWriteOperation = require('./bulk_write');\nconst MongoError = require('../core').MongoError;\nconst prepareDocs = require('./common_functions').prepareDocs;\n\nclass InsertManyOperation extends OperationBase {\n constructor(collection, docs, options) {\n super(options);\n\n this.collection = collection;\n this.docs = docs;\n }\n\n execute(callback) {\n const coll = this.collection;\n let docs = this.docs;\n const options = this.options;\n\n if (!Array.isArray(docs)) {\n return callback(\n MongoError.create({ message: 'docs parameter must be an array of documents', driver: true })\n );\n }\n\n // If keep going set unordered\n options['serializeFunctions'] = options['serializeFunctions'] || coll.s.serializeFunctions;\n\n docs = prepareDocs(coll, docs, options);\n\n // Generate the bulk write operations\n const operations = [\n {\n insertMany: docs\n }\n ];\n\n const bulkWriteOperation = new BulkWriteOperation(coll, operations, options);\n\n bulkWriteOperation.execute((err, result) => {\n if (err) return callback(err, null);\n callback(null, mapInsertManyResults(docs, result));\n });\n }\n}\n\nfunction mapInsertManyResults(docs, r) {\n const finalResult = {\n result: { ok: 1, n: r.insertedCount },\n ops: docs,\n insertedCount: r.insertedCount,\n insertedIds: r.insertedIds\n };\n\n if (r.getLastOp()) {\n finalResult.result.opTime = r.getLastOp();\n }\n\n return finalResult;\n}\n\nmodule.exports = InsertManyOperation;\n","'use strict';\n\nconst MongoError = require('../core').MongoError;\nconst OperationBase = require('./operation').OperationBase;\nconst insertDocuments = require('./common_functions').insertDocuments;\n\nclass InsertOneOperation extends OperationBase {\n constructor(collection, doc, options) {\n super(options);\n\n this.collection = collection;\n this.doc = doc;\n }\n\n execute(callback) {\n const coll = this.collection;\n const doc = this.doc;\n const options = this.options;\n\n if (Array.isArray(doc)) {\n return callback(\n MongoError.create({ message: 'doc parameter must be an object', driver: true })\n );\n }\n\n insertDocuments(coll, [doc], options, (err, r) => {\n if (callback == null) return;\n if (err && callback) return callback(err);\n // Workaround for pre 2.6 servers\n if (r == null) return callback(null, { result: { ok: 1 } });\n // Add values to top level to ensure crud spec compatibility\n r.insertedCount = r.result.n;\n r.insertedId = doc._id;\n if (callback) callback(null, r);\n });\n }\n}\n\nmodule.exports = InsertOneOperation;\n","'use strict';\n\nconst OptionsOperation = require('./options_operation');\nconst handleCallback = require('../utils').handleCallback;\n\nclass IsCappedOperation extends OptionsOperation {\n constructor(collection, options) {\n super(collection, options);\n }\n\n execute(callback) {\n super.execute((err, document) => {\n if (err) return handleCallback(callback, err);\n handleCallback(callback, null, !!(document && document.capped));\n });\n }\n}\n\nmodule.exports = IsCappedOperation;\n","'use strict';\n\nconst CommandOperationV2 = require('./command_v2');\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\nconst maxWireVersion = require('../core/utils').maxWireVersion;\nconst CONSTANTS = require('../constants');\n\nconst LIST_COLLECTIONS_WIRE_VERSION = 3;\n\nfunction listCollectionsTransforms(databaseName) {\n const matching = `${databaseName}.`;\n\n return {\n doc: doc => {\n const index = doc.name.indexOf(matching);\n // Remove database name if available\n if (doc.name && index === 0) {\n doc.name = doc.name.substr(index + matching.length);\n }\n\n return doc;\n }\n };\n}\n\nclass ListCollectionsOperation extends CommandOperationV2 {\n constructor(db, filter, options) {\n super(db, options, { fullResponse: true });\n\n this.db = db;\n this.filter = filter;\n this.nameOnly = !!this.options.nameOnly;\n\n if (typeof this.options.batchSize === 'number') {\n this.batchSize = this.options.batchSize;\n }\n }\n\n execute(server, callback) {\n if (maxWireVersion(server) < LIST_COLLECTIONS_WIRE_VERSION) {\n let filter = this.filter;\n const databaseName = this.db.s.namespace.db;\n\n // If we have legacy mode and have not provided a full db name filter it\n if (\n typeof filter.name === 'string' &&\n !new RegExp('^' + databaseName + '\\\\.').test(filter.name)\n ) {\n filter = Object.assign({}, filter);\n filter.name = this.db.s.namespace.withCollection(filter.name).toString();\n }\n\n // No filter, filter by current database\n if (filter == null) {\n filter.name = `/${databaseName}/`;\n }\n\n // Rewrite the filter to use $and to filter out indexes\n if (filter.name) {\n filter = { $and: [{ name: filter.name }, { name: /^((?!\\$).)*$/ }] };\n } else {\n filter = { name: /^((?!\\$).)*$/ };\n }\n\n const transforms = listCollectionsTransforms(databaseName);\n server.query(\n `${databaseName}.${CONSTANTS.SYSTEM_NAMESPACE_COLLECTION}`,\n { query: filter },\n { batchSize: this.batchSize || 1000 },\n {},\n (err, result) => {\n if (\n result &&\n result.message &&\n result.message.documents &&\n Array.isArray(result.message.documents)\n ) {\n result.message.documents = result.message.documents.map(transforms.doc);\n }\n\n callback(err, result);\n }\n );\n\n return;\n }\n\n const command = {\n listCollections: 1,\n filter: this.filter,\n cursor: this.batchSize ? { batchSize: this.batchSize } : {},\n nameOnly: this.nameOnly\n };\n\n return super.executeCommand(server, command, callback);\n }\n}\n\ndefineAspects(ListCollectionsOperation, [\n Aspect.READ_OPERATION,\n Aspect.RETRYABLE,\n Aspect.EXECUTE_WITH_SELECTION\n]);\n\nmodule.exports = ListCollectionsOperation;\n","'use strict';\n\nconst CommandOperationV2 = require('./command_v2');\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\nconst MongoDBNamespace = require('../utils').MongoDBNamespace;\n\nclass ListDatabasesOperation extends CommandOperationV2 {\n constructor(db, options) {\n super(db, options);\n this.ns = new MongoDBNamespace('admin', '$cmd');\n }\n\n execute(server, callback) {\n const cmd = { listDatabases: 1 };\n if (this.options.nameOnly) {\n cmd.nameOnly = Number(cmd.nameOnly);\n }\n\n if (this.options.filter) {\n cmd.filter = this.options.filter;\n }\n\n if (typeof this.options.authorizedDatabases === 'boolean') {\n cmd.authorizedDatabases = this.options.authorizedDatabases;\n }\n\n super.executeCommand(server, cmd, callback);\n }\n}\n\ndefineAspects(ListDatabasesOperation, [\n Aspect.READ_OPERATION,\n Aspect.RETRYABLE,\n Aspect.EXECUTE_WITH_SELECTION\n]);\n\nmodule.exports = ListDatabasesOperation;\n","'use strict';\n\nconst CommandOperationV2 = require('./command_v2');\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\nconst maxWireVersion = require('../core/utils').maxWireVersion;\n\nconst LIST_INDEXES_WIRE_VERSION = 3;\n\nclass ListIndexesOperation extends CommandOperationV2 {\n constructor(collection, options) {\n super(collection, options, { fullResponse: true });\n\n this.collectionNamespace = collection.s.namespace;\n }\n\n execute(server, callback) {\n const serverWireVersion = maxWireVersion(server);\n if (serverWireVersion < LIST_INDEXES_WIRE_VERSION) {\n const systemIndexesNS = this.collectionNamespace.withCollection('system.indexes').toString();\n const collectionNS = this.collectionNamespace.toString();\n\n server.query(systemIndexesNS, { query: { ns: collectionNS } }, {}, this.options, callback);\n return;\n }\n\n const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {};\n super.executeCommand(\n server,\n { listIndexes: this.collectionNamespace.collection, cursor },\n callback\n );\n }\n}\n\ndefineAspects(ListIndexesOperation, [\n Aspect.READ_OPERATION,\n Aspect.RETRYABLE,\n Aspect.EXECUTE_WITH_SELECTION\n]);\n\nmodule.exports = ListIndexesOperation;\n","'use strict';\n\nconst applyWriteConcern = require('../utils').applyWriteConcern;\nconst Code = require('../core').BSON.Code;\nconst decorateWithCollation = require('../utils').decorateWithCollation;\nconst decorateWithReadConcern = require('../utils').decorateWithReadConcern;\nconst executeCommand = require('./db_ops').executeCommand;\nconst handleCallback = require('../utils').handleCallback;\nconst isObject = require('../utils').isObject;\nconst loadDb = require('../dynamic_loaders').loadDb;\nconst OperationBase = require('./operation').OperationBase;\nconst ReadPreference = require('../core').ReadPreference;\nconst toError = require('../utils').toError;\n\nconst exclusionList = [\n 'readPreference',\n 'session',\n 'bypassDocumentValidation',\n 'w',\n 'wtimeout',\n 'j',\n 'writeConcern'\n];\n\n/**\n * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection.\n *\n * @class\n * @property {Collection} a Collection instance.\n * @property {(function|string)} map The mapping function.\n * @property {(function|string)} reduce The reduce function.\n * @property {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options.\n */\nclass MapReduceOperation extends OperationBase {\n /**\n * Constructs a MapReduce operation.\n *\n * @param {Collection} a Collection instance.\n * @param {(function|string)} map The mapping function.\n * @param {(function|string)} reduce The reduce function.\n * @param {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options.\n */\n constructor(collection, map, reduce, options) {\n super(options);\n\n this.collection = collection;\n this.map = map;\n this.reduce = reduce;\n }\n\n /**\n * Execute the operation.\n *\n * @param {Collection~resultCallback} [callback] The command result callback\n */\n execute(callback) {\n const coll = this.collection;\n const map = this.map;\n const reduce = this.reduce;\n let options = this.options;\n\n const mapCommandHash = {\n mapReduce: coll.collectionName,\n map: map,\n reduce: reduce\n };\n\n // Add any other options passed in\n for (let n in options) {\n if ('scope' === n) {\n mapCommandHash[n] = processScope(options[n]);\n } else {\n // Only include if not in exclusion list\n if (exclusionList.indexOf(n) === -1) {\n mapCommandHash[n] = options[n];\n }\n }\n }\n\n options = Object.assign({}, options);\n\n // Ensure we have the right read preference inheritance\n options.readPreference = ReadPreference.resolve(coll, options);\n\n // If we have a read preference and inline is not set as output fail hard\n if (\n options.readPreference !== false &&\n options.readPreference !== 'primary' &&\n options['out'] &&\n options['out'].inline !== 1 &&\n options['out'] !== 'inline'\n ) {\n // Force readPreference to primary\n options.readPreference = 'primary';\n // Decorate command with writeConcern if supported\n applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options);\n } else {\n decorateWithReadConcern(mapCommandHash, coll, options);\n }\n\n // Is bypassDocumentValidation specified\n if (options.bypassDocumentValidation === true) {\n mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation;\n }\n\n // Have we specified collation\n try {\n decorateWithCollation(mapCommandHash, coll, options);\n } catch (err) {\n return callback(err, null);\n }\n\n // Execute command\n executeCommand(coll.s.db, mapCommandHash, options, (err, result) => {\n if (err) return handleCallback(callback, err);\n // Check if we have an error\n if (1 !== result.ok || result.err || result.errmsg) {\n return handleCallback(callback, toError(result));\n }\n\n // Create statistics value\n const stats = {};\n if (result.timeMillis) stats['processtime'] = result.timeMillis;\n if (result.counts) stats['counts'] = result.counts;\n if (result.timing) stats['timing'] = result.timing;\n\n // invoked with inline?\n if (result.results) {\n // If we wish for no verbosity\n if (options['verbose'] == null || !options['verbose']) {\n return handleCallback(callback, null, result.results);\n }\n\n return handleCallback(callback, null, { results: result.results, stats: stats });\n }\n\n // The returned collection\n let collection = null;\n\n // If we have an object it's a different db\n if (result.result != null && typeof result.result === 'object') {\n const doc = result.result;\n // Return a collection from another db\n let Db = loadDb();\n collection = new Db(doc.db, coll.s.db.s.topology, coll.s.db.s.options).collection(\n doc.collection\n );\n } else {\n // Create a collection object that wraps the result collection\n collection = coll.s.db.collection(result.result);\n }\n\n // If we wish for no verbosity\n if (options['verbose'] == null || !options['verbose']) {\n return handleCallback(callback, err, collection);\n }\n\n // Return stats as third set of values\n handleCallback(callback, err, { collection: collection, stats: stats });\n });\n }\n}\n\n/**\n * Functions that are passed as scope args must\n * be converted to Code instances.\n * @ignore\n */\nfunction processScope(scope) {\n if (!isObject(scope) || scope._bsontype === 'ObjectID') {\n return scope;\n }\n\n const keys = Object.keys(scope);\n let key;\n const new_scope = {};\n\n for (let i = keys.length - 1; i >= 0; i--) {\n key = keys[i];\n if ('function' === typeof scope[key]) {\n new_scope[key] = new Code(String(scope[key]));\n } else {\n new_scope[key] = processScope(scope[key]);\n }\n }\n\n return new_scope;\n}\n\nmodule.exports = MapReduceOperation;\n","'use strict';\n\nconst Aspect = {\n READ_OPERATION: Symbol('READ_OPERATION'),\n WRITE_OPERATION: Symbol('WRITE_OPERATION'),\n RETRYABLE: Symbol('RETRYABLE'),\n EXECUTE_WITH_SELECTION: Symbol('EXECUTE_WITH_SELECTION'),\n NO_INHERIT_OPTIONS: Symbol('NO_INHERIT_OPTIONS')\n};\n\n/**\n * This class acts as a parent class for any operation and is responsible for setting this.options,\n * as well as setting and getting a session.\n * Additionally, this class implements `hasAspect`, which determines whether an operation has\n * a specific aspect.\n */\nclass OperationBase {\n constructor(options) {\n this.options = Object.assign({}, options);\n }\n\n hasAspect(aspect) {\n if (this.constructor.aspects == null) {\n return false;\n }\n return this.constructor.aspects.has(aspect);\n }\n\n set session(session) {\n Object.assign(this.options, { session });\n }\n\n get session() {\n return this.options.session;\n }\n\n clearSession() {\n delete this.options.session;\n }\n\n get canRetryRead() {\n return true;\n }\n\n execute() {\n throw new TypeError('`execute` must be implemented for OperationBase subclasses');\n }\n}\n\nfunction defineAspects(operation, aspects) {\n if (!Array.isArray(aspects) && !(aspects instanceof Set)) {\n aspects = [aspects];\n }\n aspects = new Set(aspects);\n Object.defineProperty(operation, 'aspects', {\n value: aspects,\n writable: false\n });\n return aspects;\n}\n\nmodule.exports = {\n Aspect,\n defineAspects,\n OperationBase\n};\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst handleCallback = require('../utils').handleCallback;\nconst MongoError = require('../core').MongoError;\n\nclass OptionsOperation extends OperationBase {\n constructor(collection, options) {\n super(options);\n\n this.collection = collection;\n }\n\n execute(callback) {\n const coll = this.collection;\n const opts = this.options;\n\n coll.s.db.listCollections({ name: coll.collectionName }, opts).toArray((err, collections) => {\n if (err) return handleCallback(callback, err);\n if (collections.length === 0) {\n return handleCallback(\n callback,\n MongoError.create({ message: `collection ${coll.namespace} not found`, driver: true })\n );\n }\n\n handleCallback(callback, err, collections[0].options || null);\n });\n }\n}\n\nmodule.exports = OptionsOperation;\n","'use strict';\n\nconst CommandOperation = require('./command');\n\nclass ProfilingLevelOperation extends CommandOperation {\n constructor(db, command, options) {\n super(db, options);\n }\n\n _buildCommand() {\n const command = { profile: -1 };\n\n return command;\n }\n\n execute(callback) {\n super.execute((err, doc) => {\n if (err == null && doc.ok === 1) {\n const was = doc.was;\n if (was === 0) return callback(null, 'off');\n if (was === 1) return callback(null, 'slow_only');\n if (was === 2) return callback(null, 'all');\n return callback(new Error('Error: illegal profiling level value ' + was), null);\n } else {\n err != null ? callback(err, null) : callback(new Error('Error with profile command'), null);\n }\n });\n }\n}\n\nmodule.exports = ProfilingLevelOperation;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst defineAspects = require('./operation').defineAspects;\nconst CommandOperationV2 = require('./command_v2');\nconst serverType = require('../core/sdam/common').serverType;\nconst ServerType = require('../core/sdam/common').ServerType;\nconst MongoError = require('../core').MongoError;\n\nclass ReIndexOperation extends CommandOperationV2 {\n constructor(collection, options) {\n super(collection, options);\n this.collectionName = collection.collectionName;\n }\n\n execute(server, callback) {\n if (serverType(server) !== ServerType.Standalone) {\n callback(new MongoError(`reIndex can only be executed on standalone servers.`));\n return;\n }\n super.executeCommand(server, { reIndex: this.collectionName }, (err, result) => {\n if (err) {\n callback(err);\n return;\n }\n callback(null, !!result.ok);\n });\n }\n}\n\ndefineAspects(ReIndexOperation, [Aspect.EXECUTE_WITH_SELECTION]);\n\nmodule.exports = ReIndexOperation;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst CommandOperation = require('./command');\nconst defineAspects = require('./operation').defineAspects;\nconst handleCallback = require('../utils').handleCallback;\nconst WriteConcern = require('../write_concern');\n\nclass RemoveUserOperation extends CommandOperation {\n constructor(db, username, options) {\n const commandOptions = {};\n\n const writeConcern = WriteConcern.fromOptions(options);\n if (writeConcern != null) {\n commandOptions.writeConcern = writeConcern;\n }\n\n if (options.dbName) {\n commandOptions.dbName = options.dbName;\n }\n\n // Add maxTimeMS to options if set\n if (typeof options.maxTimeMS === 'number') {\n commandOptions.maxTimeMS = options.maxTimeMS;\n }\n\n super(db, commandOptions);\n\n this.username = username;\n }\n\n _buildCommand() {\n const username = this.username;\n\n // Build the command to execute\n const command = { dropUser: username };\n\n return command;\n }\n\n execute(callback) {\n // Attempt to execute command\n super.execute((err, result) => {\n if (err) return handleCallback(callback, err, null);\n handleCallback(callback, err, result.ok ? true : false);\n });\n }\n}\n\ndefineAspects(RemoveUserOperation, Aspect.WRITE_OPERATION);\n\nmodule.exports = RemoveUserOperation;\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst applyWriteConcern = require('../utils').applyWriteConcern;\nconst checkCollectionName = require('../utils').checkCollectionName;\nconst executeDbAdminCommand = require('./db_ops').executeDbAdminCommand;\nconst handleCallback = require('../utils').handleCallback;\nconst loadCollection = require('../dynamic_loaders').loadCollection;\nconst toError = require('../utils').toError;\n\nclass RenameOperation extends OperationBase {\n constructor(collection, newName, options) {\n super(options);\n\n this.collection = collection;\n this.newName = newName;\n }\n\n execute(callback) {\n const coll = this.collection;\n const newName = this.newName;\n const options = this.options;\n\n let Collection = loadCollection();\n // Check the collection name\n checkCollectionName(newName);\n // Build the command\n const renameCollection = coll.namespace;\n const toCollection = coll.s.namespace.withCollection(newName).toString();\n const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false;\n const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget };\n\n // Decorate command with writeConcern if supported\n applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options);\n\n // Execute against admin\n executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => {\n if (err) return handleCallback(callback, err, null);\n // We have an error\n if (doc.errmsg) return handleCallback(callback, toError(doc), null);\n try {\n return handleCallback(\n callback,\n null,\n new Collection(\n coll.s.db,\n coll.s.topology,\n coll.s.namespace.db,\n newName,\n coll.s.pkFactory,\n coll.s.options\n )\n );\n } catch (err) {\n return handleCallback(callback, toError(err), null);\n }\n });\n }\n}\n\nmodule.exports = RenameOperation;\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst updateDocuments = require('./common_functions').updateDocuments;\nconst hasAtomicOperators = require('../utils').hasAtomicOperators;\n\nclass ReplaceOneOperation extends OperationBase {\n constructor(collection, filter, replacement, options) {\n super(options);\n\n if (hasAtomicOperators(replacement)) {\n throw new TypeError('Replacement document must not contain atomic operators');\n }\n\n this.collection = collection;\n this.filter = filter;\n this.replacement = replacement;\n }\n\n execute(callback) {\n const coll = this.collection;\n const filter = this.filter;\n const replacement = this.replacement;\n const options = this.options;\n\n // Set single document update\n options.multi = false;\n\n // Execute update\n updateDocuments(coll, filter, replacement, options, (err, r) =>\n replaceCallback(err, r, replacement, callback)\n );\n }\n}\n\nfunction replaceCallback(err, r, doc, callback) {\n if (callback == null) return;\n if (err && callback) return callback(err);\n if (r == null) return callback(null, { result: { ok: 1 } });\n\n r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;\n r.upsertedId =\n Array.isArray(r.result.upserted) && r.result.upserted.length > 0\n ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id`\n : null;\n r.upsertedCount =\n Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;\n r.matchedCount =\n Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;\n r.ops = [doc]; // TODO: Should we still have this?\n if (callback) callback(null, r);\n}\n\nmodule.exports = ReplaceOneOperation;\n","'use strict';\n\nconst CommandOperationV2 = require('./command_v2');\nconst defineAspects = require('./operation').defineAspects;\nconst Aspect = require('./operation').Aspect;\n\nclass RunCommandOperation extends CommandOperationV2 {\n constructor(parent, command, options) {\n super(parent, options);\n this.command = command;\n }\n execute(server, callback) {\n const command = this.command;\n this.executeCommand(server, command, callback);\n }\n}\ndefineAspects(RunCommandOperation, [Aspect.EXECUTE_WITH_SELECTION, Aspect.NO_INHERIT_OPTIONS]);\n\nmodule.exports = RunCommandOperation;\n","'use strict';\n\nconst CommandOperation = require('./command');\nconst levelValues = new Set(['off', 'slow_only', 'all']);\n\nclass SetProfilingLevelOperation extends CommandOperation {\n constructor(db, level, options) {\n let profile = 0;\n\n if (level === 'off') {\n profile = 0;\n } else if (level === 'slow_only') {\n profile = 1;\n } else if (level === 'all') {\n profile = 2;\n }\n\n super(db, options);\n this.level = level;\n this.profile = profile;\n }\n\n _buildCommand() {\n const profile = this.profile;\n\n // Set up the profile number\n const command = { profile };\n\n return command;\n }\n\n execute(callback) {\n const level = this.level;\n\n if (!levelValues.has(level)) {\n return callback(new Error('Error: illegal profiling level value ' + level));\n }\n\n super.execute((err, doc) => {\n if (err == null && doc.ok === 1) return callback(null, level);\n return err != null\n ? callback(err, null)\n : callback(new Error('Error with profile command'), null);\n });\n }\n}\n\nmodule.exports = SetProfilingLevelOperation;\n","'use strict';\n\nconst Aspect = require('./operation').Aspect;\nconst CommandOperation = require('./command');\nconst defineAspects = require('./operation').defineAspects;\n\n/**\n * Get all the collection statistics.\n *\n * @class\n * @property {Collection} a Collection instance.\n * @property {object} [options] Optional settings. See Collection.prototype.stats for a list of options.\n */\nclass StatsOperation extends CommandOperation {\n /**\n * Construct a Stats operation.\n *\n * @param {Collection} a Collection instance.\n * @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options.\n */\n constructor(collection, options) {\n super(collection.s.db, options, collection);\n }\n\n _buildCommand() {\n const collection = this.collection;\n const options = this.options;\n\n // Build command object\n const command = {\n collStats: collection.collectionName\n };\n\n // Check if we have the scale value\n if (options['scale'] != null) {\n command['scale'] = options['scale'];\n }\n\n return command;\n }\n}\n\ndefineAspects(StatsOperation, Aspect.READ_OPERATION);\n\nmodule.exports = StatsOperation;\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst updateCallback = require('./common_functions').updateCallback;\nconst updateDocuments = require('./common_functions').updateDocuments;\nconst hasAtomicOperators = require('../utils').hasAtomicOperators;\n\nclass UpdateManyOperation extends OperationBase {\n constructor(collection, filter, update, options) {\n super(options);\n\n if (!hasAtomicOperators(update)) {\n throw new TypeError('Update document requires atomic operators');\n }\n\n this.collection = collection;\n this.filter = filter;\n this.update = update;\n }\n\n execute(callback) {\n const coll = this.collection;\n const filter = this.filter;\n const update = this.update;\n const options = this.options;\n\n // Set single document update\n options.multi = true;\n // Execute update\n updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback));\n }\n}\n\nmodule.exports = UpdateManyOperation;\n","'use strict';\n\nconst OperationBase = require('./operation').OperationBase;\nconst updateDocuments = require('./common_functions').updateDocuments;\nconst hasAtomicOperators = require('../utils').hasAtomicOperators;\n\nclass UpdateOneOperation extends OperationBase {\n constructor(collection, filter, update, options) {\n super(options);\n\n if (!hasAtomicOperators(update)) {\n throw new TypeError('Update document requires atomic operators');\n }\n\n this.collection = collection;\n this.filter = filter;\n this.update = update;\n }\n\n execute(callback) {\n const coll = this.collection;\n const filter = this.filter;\n const update = this.update;\n const options = this.options;\n\n // Set single document update\n options.multi = false;\n // Execute update\n updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback));\n }\n}\n\nfunction updateCallback(err, r, callback) {\n if (callback == null) return;\n if (err) return callback(err);\n if (r == null) return callback(null, { result: { ok: 1 } });\n r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;\n r.upsertedId =\n Array.isArray(r.result.upserted) && r.result.upserted.length > 0\n ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id`\n : null;\n r.upsertedCount =\n Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;\n r.matchedCount =\n Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;\n callback(null, r);\n}\n\nmodule.exports = UpdateOneOperation;\n","'use strict';\n\nconst CommandOperation = require('./command');\n\nclass ValidateCollectionOperation extends CommandOperation {\n constructor(admin, collectionName, options) {\n // Decorate command with extra options\n let command = { validate: collectionName };\n const keys = Object.keys(options);\n for (let i = 0; i < keys.length; i++) {\n if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') {\n command[keys[i]] = options[keys[i]];\n }\n }\n\n super(admin.s.db, options, null, command);\n this.collectionName = collectionName;\n }\n\n execute(callback) {\n const collectionName = this.collectionName;\n\n super.execute((err, doc) => {\n if (err != null) return callback(err, null);\n\n if (doc.ok === 0) return callback(new Error('Error with validate command'), null);\n if (doc.result != null && doc.result.constructor !== String)\n return callback(new Error('Error with validation data'), null);\n if (doc.result != null && doc.result.match(/exception|corrupt/) != null)\n return callback(new Error('Error: invalid collection ' + collectionName), null);\n if (doc.valid != null && !doc.valid)\n return callback(new Error('Error: invalid collection ' + collectionName), null);\n\n return callback(null, doc);\n });\n }\n}\n\nmodule.exports = ValidateCollectionOperation;\n","'use strict';\n\n/**\n * The **ReadConcern** class is a class that represents a MongoDB ReadConcern.\n * @class\n * @property {string} level The read concern level\n * @see https://docs.mongodb.com/manual/reference/read-concern/index.html\n */\nclass ReadConcern {\n /**\n * Constructs a ReadConcern from the read concern properties.\n * @param {string} [level] The read concern level ({'local'|'available'|'majority'|'linearizable'|'snapshot'})\n */\n constructor(level) {\n if (level != null) {\n this.level = level;\n }\n }\n\n /**\n * Construct a ReadConcern given an options object.\n *\n * @param {object} options The options object from which to extract the write concern.\n * @return {ReadConcern}\n */\n static fromOptions(options) {\n if (options == null) {\n return;\n }\n\n if (options.readConcern) {\n if (options.readConcern instanceof ReadConcern) {\n return options.readConcern;\n }\n\n return new ReadConcern(options.readConcern.level);\n }\n\n if (options.level) {\n return new ReadConcern(options.level);\n }\n }\n\n static get MAJORITY() {\n return 'majority';\n }\n\n static get AVAILABLE() {\n return 'available';\n }\n\n static get LINEARIZABLE() {\n return 'linearizable';\n }\n\n static get SNAPSHOT() {\n return 'snapshot';\n }\n}\n\nmodule.exports = ReadConcern;\n","'use strict';\n\nconst TopologyBase = require('./topology_base').TopologyBase;\nconst MongoError = require('../core').MongoError;\nconst CMongos = require('../core').Mongos;\nconst Cursor = require('../cursor');\nconst Server = require('./server');\nconst Store = require('./topology_base').Store;\nconst MAX_JS_INT = require('../utils').MAX_JS_INT;\nconst translateOptions = require('../utils').translateOptions;\nconst filterOptions = require('../utils').filterOptions;\nconst mergeOptions = require('../utils').mergeOptions;\n\n/**\n * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is\n * used to construct connections.\n *\n * **Mongos Should not be used, use MongoClient.connect**\n */\n\n// Allowed parameters\nvar legalOptionNames = [\n 'ha',\n 'haInterval',\n 'acceptableLatencyMS',\n 'poolSize',\n 'ssl',\n 'checkServerIdentity',\n 'sslValidate',\n 'sslCA',\n 'sslCRL',\n 'sslCert',\n 'ciphers',\n 'ecdhCurve',\n 'sslKey',\n 'sslPass',\n 'socketOptions',\n 'bufferMaxEntries',\n 'store',\n 'auto_reconnect',\n 'autoReconnect',\n 'emitError',\n 'keepAlive',\n 'keepAliveInitialDelay',\n 'noDelay',\n 'connectTimeoutMS',\n 'socketTimeoutMS',\n 'loggerLevel',\n 'logger',\n 'reconnectTries',\n 'appname',\n 'domainsEnabled',\n 'servername',\n 'promoteLongs',\n 'promoteValues',\n 'promoteBuffers',\n 'promiseLibrary',\n 'monitorCommands'\n];\n\n/**\n * Creates a new Mongos instance\n * @class\n * @deprecated\n * @param {Server[]} servers A seedlist of servers participating in the replicaset.\n * @param {object} [options] Optional settings.\n * @param {booelan} [options.ha=true] Turn on high availability monitoring.\n * @param {number} [options.haInterval=5000] Time between each replicaset status check.\n * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons.\n * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection\n * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support)\n * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.\n * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.\n * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.\n * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {string} [options.servername] String containing the server name requested via TLS SNI.\n * @param {object} [options.socketOptions] Socket options\n * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option.\n * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled\n * @param {number} [options.socketOptions.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket\n * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out\n * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out\n * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.\n * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology\n * @fires Mongos#connect\n * @fires Mongos#ha\n * @fires Mongos#joined\n * @fires Mongos#left\n * @fires Mongos#fullsetup\n * @fires Mongos#open\n * @fires Mongos#close\n * @fires Mongos#error\n * @fires Mongos#timeout\n * @fires Mongos#parseError\n * @fires Mongos#commandStarted\n * @fires Mongos#commandSucceeded\n * @fires Mongos#commandFailed\n * @property {string} parserType the parser type used (c++ or js).\n * @return {Mongos} a Mongos instance.\n */\nclass Mongos extends TopologyBase {\n constructor(servers, options) {\n super();\n\n options = options || {};\n var self = this;\n\n // Filter the options\n options = filterOptions(options, legalOptionNames);\n\n // Ensure all the instances are Server\n for (var i = 0; i < servers.length; i++) {\n if (!(servers[i] instanceof Server)) {\n throw MongoError.create({\n message: 'all seed list instances must be of the Server type',\n driver: true\n });\n }\n }\n\n // Stored options\n var storeOptions = {\n force: false,\n bufferMaxEntries:\n typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT\n };\n\n // Shared global store\n var store = options.store || new Store(self, storeOptions);\n\n // Build seed list\n var seedlist = servers.map(function(x) {\n return { host: x.host, port: x.port };\n });\n\n // Get the reconnect option\n var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true;\n reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect;\n\n // Clone options\n var clonedOptions = mergeOptions(\n {},\n {\n disconnectHandler: store,\n cursorFactory: Cursor,\n reconnect: reconnect,\n emitError: typeof options.emitError === 'boolean' ? options.emitError : true,\n size: typeof options.poolSize === 'number' ? options.poolSize : 5,\n monitorCommands:\n typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false\n }\n );\n\n // Translate any SSL options and other connectivity options\n clonedOptions = translateOptions(clonedOptions, options);\n\n // Socket options\n var socketOptions =\n options.socketOptions && Object.keys(options.socketOptions).length > 0\n ? options.socketOptions\n : options;\n\n // Translate all the options to the core types\n clonedOptions = translateOptions(clonedOptions, socketOptions);\n\n // Internal state\n this.s = {\n // Create the Mongos\n coreTopology: new CMongos(seedlist, clonedOptions),\n // Server capabilities\n sCapabilities: null,\n // Debug turned on\n debug: clonedOptions.debug,\n // Store option defaults\n storeOptions: storeOptions,\n // Cloned options\n clonedOptions: clonedOptions,\n // Actual store of callbacks\n store: store,\n // Options\n options: options,\n // Server Session Pool\n sessionPool: null,\n // Active client sessions\n sessions: new Set(),\n // Promise library\n promiseLibrary: options.promiseLibrary || Promise\n };\n }\n\n // Connect\n connect(_options, callback) {\n var self = this;\n if ('function' === typeof _options) (callback = _options), (_options = {});\n if (_options == null) _options = {};\n if (!('function' === typeof callback)) callback = null;\n _options = Object.assign({}, this.s.clonedOptions, _options);\n self.s.options = _options;\n\n // Update bufferMaxEntries\n self.s.storeOptions.bufferMaxEntries =\n typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1;\n\n // Error handler\n var connectErrorHandler = function() {\n return function(err) {\n // Remove all event handlers\n var events = ['timeout', 'error', 'close'];\n events.forEach(function(e) {\n self.removeListener(e, connectErrorHandler);\n });\n\n self.s.coreTopology.removeListener('connect', connectErrorHandler);\n // Force close the topology\n self.close(true);\n\n // Try to callback\n try {\n callback(err);\n } catch (err) {\n process.nextTick(function() {\n throw err;\n });\n }\n };\n };\n\n // Actual handler\n var errorHandler = function(event) {\n return function(err) {\n if (event !== 'error') {\n self.emit(event, err);\n }\n };\n };\n\n // Error handler\n var reconnectHandler = function() {\n self.emit('reconnect');\n self.s.store.execute();\n };\n\n // relay the event\n var relay = function(event) {\n return function(t, server) {\n self.emit(event, t, server);\n };\n };\n\n // Connect handler\n var connectHandler = function() {\n // Clear out all the current handlers left over\n var events = ['timeout', 'error', 'close', 'fullsetup'];\n events.forEach(function(e) {\n self.s.coreTopology.removeAllListeners(e);\n });\n\n // Set up listeners\n self.s.coreTopology.on('timeout', errorHandler('timeout'));\n self.s.coreTopology.on('error', errorHandler('error'));\n self.s.coreTopology.on('close', errorHandler('close'));\n\n // Set up serverConfig listeners\n self.s.coreTopology.on('fullsetup', function() {\n self.emit('fullsetup', self);\n });\n\n // Emit open event\n self.emit('open', null, self);\n\n // Return correctly\n try {\n callback(null, self);\n } catch (err) {\n process.nextTick(function() {\n throw err;\n });\n }\n };\n\n // Clear out all the current handlers left over\n var events = [\n 'timeout',\n 'error',\n 'close',\n 'serverOpening',\n 'serverDescriptionChanged',\n 'serverHeartbeatStarted',\n 'serverHeartbeatSucceeded',\n 'serverHeartbeatFailed',\n 'serverClosed',\n 'topologyOpening',\n 'topologyClosed',\n 'topologyDescriptionChanged',\n 'commandStarted',\n 'commandSucceeded',\n 'commandFailed'\n ];\n events.forEach(function(e) {\n self.s.coreTopology.removeAllListeners(e);\n });\n\n // Set up SDAM listeners\n self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged'));\n self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted'));\n self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded'));\n self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed'));\n self.s.coreTopology.on('serverOpening', relay('serverOpening'));\n self.s.coreTopology.on('serverClosed', relay('serverClosed'));\n self.s.coreTopology.on('topologyOpening', relay('topologyOpening'));\n self.s.coreTopology.on('topologyClosed', relay('topologyClosed'));\n self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged'));\n self.s.coreTopology.on('commandStarted', relay('commandStarted'));\n self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded'));\n self.s.coreTopology.on('commandFailed', relay('commandFailed'));\n\n // Set up listeners\n self.s.coreTopology.once('timeout', connectErrorHandler('timeout'));\n self.s.coreTopology.once('error', connectErrorHandler('error'));\n self.s.coreTopology.once('close', connectErrorHandler('close'));\n self.s.coreTopology.once('connect', connectHandler);\n // Join and leave events\n self.s.coreTopology.on('joined', relay('joined'));\n self.s.coreTopology.on('left', relay('left'));\n\n // Reconnect server\n self.s.coreTopology.on('reconnect', reconnectHandler);\n\n // Start connection\n self.s.coreTopology.connect(_options);\n }\n}\n\nObject.defineProperty(Mongos.prototype, 'haInterval', {\n enumerable: true,\n get: function() {\n return this.s.coreTopology.s.haInterval;\n }\n});\n\n/**\n * A mongos connect event, used to verify that the connection is up and running\n *\n * @event Mongos#connect\n * @type {Mongos}\n */\n\n/**\n * The mongos high availability event\n *\n * @event Mongos#ha\n * @type {function}\n * @param {string} type The stage in the high availability event (start|end)\n * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only\n * @param {number} data.id The id for this high availability request\n * @param {object} data.state An object containing the information about the current replicaset\n */\n\n/**\n * A server member left the mongos set\n *\n * @event Mongos#left\n * @type {function}\n * @param {string} type The type of member that left (primary|secondary|arbiter)\n * @param {Server} server The server object that left\n */\n\n/**\n * A server member joined the mongos set\n *\n * @event Mongos#joined\n * @type {function}\n * @param {string} type The type of member that joined (primary|secondary|arbiter)\n * @param {Server} server The server object that joined\n */\n\n/**\n * Mongos fullsetup event, emitted when all proxies in the topology have been connected to.\n *\n * @event Mongos#fullsetup\n * @type {Mongos}\n */\n\n/**\n * Mongos open event, emitted when mongos can start processing commands.\n *\n * @event Mongos#open\n * @type {Mongos}\n */\n\n/**\n * Mongos close event\n *\n * @event Mongos#close\n * @type {object}\n */\n\n/**\n * Mongos error event, emitted if there is an error listener.\n *\n * @event Mongos#error\n * @type {MongoError}\n */\n\n/**\n * Mongos timeout event\n *\n * @event Mongos#timeout\n * @type {object}\n */\n\n/**\n * Mongos parseError event\n *\n * @event Mongos#parseError\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command was started, if command monitoring is enabled\n *\n * @event Mongos#commandStarted\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command succeeded, if command monitoring is enabled\n *\n * @event Mongos#commandSucceeded\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command failed, if command monitoring is enabled\n *\n * @event Mongos#commandFailed\n * @type {object}\n */\n\nmodule.exports = Mongos;\n","'use strict';\n\nconst Topology = require('../core').Topology;\nconst ServerCapabilities = require('./topology_base').ServerCapabilities;\nconst Cursor = require('../cursor');\nconst translateOptions = require('../utils').translateOptions;\n\nclass NativeTopology extends Topology {\n constructor(servers, options) {\n options = options || {};\n\n let clonedOptions = Object.assign(\n {},\n {\n cursorFactory: Cursor,\n reconnect: false,\n emitError: typeof options.emitError === 'boolean' ? options.emitError : true,\n maxPoolSize:\n typeof options.maxPoolSize === 'number'\n ? options.maxPoolSize\n : typeof options.poolSize === 'number'\n ? options.poolSize\n : 10,\n minPoolSize:\n typeof options.minPoolSize === 'number'\n ? options.minPoolSize\n : typeof options.minSize === 'number'\n ? options.minSize\n : 0,\n monitorCommands:\n typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false\n }\n );\n\n // Translate any SSL options and other connectivity options\n clonedOptions = translateOptions(clonedOptions, options);\n\n // Socket options\n var socketOptions =\n options.socketOptions && Object.keys(options.socketOptions).length > 0\n ? options.socketOptions\n : options;\n\n // Translate all the options to the core types\n clonedOptions = translateOptions(clonedOptions, socketOptions);\n\n super(servers, clonedOptions);\n }\n\n capabilities() {\n if (this.s.sCapabilities) return this.s.sCapabilities;\n if (this.lastIsMaster() == null) return null;\n this.s.sCapabilities = new ServerCapabilities(this.lastIsMaster());\n return this.s.sCapabilities;\n }\n\n // Command\n command(ns, cmd, options, callback) {\n super.command(ns.toString(), cmd, options, callback);\n }\n\n // Insert\n insert(ns, ops, options, callback) {\n super.insert(ns.toString(), ops, options, callback);\n }\n\n // Update\n update(ns, ops, options, callback) {\n super.update(ns.toString(), ops, options, callback);\n }\n\n // Remove\n remove(ns, ops, options, callback) {\n super.remove(ns.toString(), ops, options, callback);\n }\n}\n\nmodule.exports = NativeTopology;\n","'use strict';\n\nconst Server = require('./server');\nconst Cursor = require('../cursor');\nconst MongoError = require('../core').MongoError;\nconst TopologyBase = require('./topology_base').TopologyBase;\nconst Store = require('./topology_base').Store;\nconst CReplSet = require('../core').ReplSet;\nconst MAX_JS_INT = require('../utils').MAX_JS_INT;\nconst translateOptions = require('../utils').translateOptions;\nconst filterOptions = require('../utils').filterOptions;\nconst mergeOptions = require('../utils').mergeOptions;\n\n/**\n * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is\n * used to construct connections.\n *\n * **ReplSet Should not be used, use MongoClient.connect**\n */\n\n// Allowed parameters\nvar legalOptionNames = [\n 'ha',\n 'haInterval',\n 'replicaSet',\n 'rs_name',\n 'secondaryAcceptableLatencyMS',\n 'connectWithNoPrimary',\n 'poolSize',\n 'ssl',\n 'checkServerIdentity',\n 'sslValidate',\n 'sslCA',\n 'sslCert',\n 'ciphers',\n 'ecdhCurve',\n 'sslCRL',\n 'sslKey',\n 'sslPass',\n 'socketOptions',\n 'bufferMaxEntries',\n 'store',\n 'auto_reconnect',\n 'autoReconnect',\n 'emitError',\n 'keepAlive',\n 'keepAliveInitialDelay',\n 'noDelay',\n 'connectTimeoutMS',\n 'socketTimeoutMS',\n 'strategy',\n 'debug',\n 'family',\n 'loggerLevel',\n 'logger',\n 'reconnectTries',\n 'appname',\n 'domainsEnabled',\n 'servername',\n 'promoteLongs',\n 'promoteValues',\n 'promoteBuffers',\n 'maxStalenessSeconds',\n 'promiseLibrary',\n 'minSize',\n 'monitorCommands'\n];\n\n/**\n * Creates a new ReplSet instance\n * @class\n * @deprecated\n * @param {Server[]} servers A seedlist of servers participating in the replicaset.\n * @param {object} [options] Optional settings.\n * @param {boolean} [options.ha=true] Turn on high availability monitoring.\n * @param {number} [options.haInterval=10000] Time between each replicaset status check.\n * @param {string} [options.replicaSet] The name of the replicaset to connect to.\n * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms)\n * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available\n * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons.\n * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support)\n * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.\n * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher.\n * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.\n * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.\n * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {string} [options.servername] String containing the server name requested via TLS SNI.\n * @param {object} [options.socketOptions] Socket options\n * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option.\n * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled\n * @param {number} [options.socketOptions.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket\n * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out\n * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out\n * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.\n * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed);\n * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology\n * @fires ReplSet#connect\n * @fires ReplSet#ha\n * @fires ReplSet#joined\n * @fires ReplSet#left\n * @fires ReplSet#fullsetup\n * @fires ReplSet#open\n * @fires ReplSet#close\n * @fires ReplSet#error\n * @fires ReplSet#timeout\n * @fires ReplSet#parseError\n * @fires ReplSet#commandStarted\n * @fires ReplSet#commandSucceeded\n * @fires ReplSet#commandFailed\n * @property {string} parserType the parser type used (c++ or js).\n * @return {ReplSet} a ReplSet instance.\n */\nclass ReplSet extends TopologyBase {\n constructor(servers, options) {\n super();\n\n options = options || {};\n var self = this;\n\n // Filter the options\n options = filterOptions(options, legalOptionNames);\n\n // Ensure all the instances are Server\n for (var i = 0; i < servers.length; i++) {\n if (!(servers[i] instanceof Server)) {\n throw MongoError.create({\n message: 'all seed list instances must be of the Server type',\n driver: true\n });\n }\n }\n\n // Stored options\n var storeOptions = {\n force: false,\n bufferMaxEntries:\n typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT\n };\n\n // Shared global store\n var store = options.store || new Store(self, storeOptions);\n\n // Build seed list\n var seedlist = servers.map(function(x) {\n return { host: x.host, port: x.port };\n });\n\n // Clone options\n var clonedOptions = mergeOptions(\n {},\n {\n disconnectHandler: store,\n cursorFactory: Cursor,\n reconnect: false,\n emitError: typeof options.emitError === 'boolean' ? options.emitError : true,\n size: typeof options.poolSize === 'number' ? options.poolSize : 5,\n monitorCommands:\n typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false\n }\n );\n\n // Translate any SSL options and other connectivity options\n clonedOptions = translateOptions(clonedOptions, options);\n\n // Socket options\n var socketOptions =\n options.socketOptions && Object.keys(options.socketOptions).length > 0\n ? options.socketOptions\n : options;\n\n // Translate all the options to the core types\n clonedOptions = translateOptions(clonedOptions, socketOptions);\n\n // Create the ReplSet\n var coreTopology = new CReplSet(seedlist, clonedOptions);\n\n // Listen to reconnect event\n coreTopology.on('reconnect', function() {\n self.emit('reconnect');\n store.execute();\n });\n\n // Internal state\n this.s = {\n // Replicaset\n coreTopology: coreTopology,\n // Server capabilities\n sCapabilities: null,\n // Debug tag\n tag: options.tag,\n // Store options\n storeOptions: storeOptions,\n // Cloned options\n clonedOptions: clonedOptions,\n // Store\n store: store,\n // Options\n options: options,\n // Server Session Pool\n sessionPool: null,\n // Active client sessions\n sessions: new Set(),\n // Promise library\n promiseLibrary: options.promiseLibrary || Promise\n };\n\n // Debug\n if (clonedOptions.debug) {\n // Last ismaster\n Object.defineProperty(this, 'replset', {\n enumerable: true,\n get: function() {\n return coreTopology;\n }\n });\n }\n }\n\n // Connect method\n connect(_options, callback) {\n var self = this;\n if ('function' === typeof _options) (callback = _options), (_options = {});\n if (_options == null) _options = {};\n if (!('function' === typeof callback)) callback = null;\n _options = Object.assign({}, this.s.clonedOptions, _options);\n self.s.options = _options;\n\n // Update bufferMaxEntries\n self.s.storeOptions.bufferMaxEntries =\n typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1;\n\n // Actual handler\n var errorHandler = function(event) {\n return function(err) {\n if (event !== 'error') {\n self.emit(event, err);\n }\n };\n };\n\n // Clear out all the current handlers left over\n var events = [\n 'timeout',\n 'error',\n 'close',\n 'serverOpening',\n 'serverDescriptionChanged',\n 'serverHeartbeatStarted',\n 'serverHeartbeatSucceeded',\n 'serverHeartbeatFailed',\n 'serverClosed',\n 'topologyOpening',\n 'topologyClosed',\n 'topologyDescriptionChanged',\n 'commandStarted',\n 'commandSucceeded',\n 'commandFailed',\n 'joined',\n 'left',\n 'ping',\n 'ha'\n ];\n events.forEach(function(e) {\n self.s.coreTopology.removeAllListeners(e);\n });\n\n // relay the event\n var relay = function(event) {\n return function(t, server) {\n self.emit(event, t, server);\n };\n };\n\n // Replset events relay\n var replsetRelay = function(event) {\n return function(t, server) {\n self.emit(event, t, server.lastIsMaster(), server);\n };\n };\n\n // Relay ha\n var relayHa = function(t, state) {\n self.emit('ha', t, state);\n\n if (t === 'start') {\n self.emit('ha_connect', t, state);\n } else if (t === 'end') {\n self.emit('ha_ismaster', t, state);\n }\n };\n\n // Set up serverConfig listeners\n self.s.coreTopology.on('joined', replsetRelay('joined'));\n self.s.coreTopology.on('left', relay('left'));\n self.s.coreTopology.on('ping', relay('ping'));\n self.s.coreTopology.on('ha', relayHa);\n\n // Set up SDAM listeners\n self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged'));\n self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted'));\n self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded'));\n self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed'));\n self.s.coreTopology.on('serverOpening', relay('serverOpening'));\n self.s.coreTopology.on('serverClosed', relay('serverClosed'));\n self.s.coreTopology.on('topologyOpening', relay('topologyOpening'));\n self.s.coreTopology.on('topologyClosed', relay('topologyClosed'));\n self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged'));\n self.s.coreTopology.on('commandStarted', relay('commandStarted'));\n self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded'));\n self.s.coreTopology.on('commandFailed', relay('commandFailed'));\n\n self.s.coreTopology.on('fullsetup', function() {\n self.emit('fullsetup', self, self);\n });\n\n self.s.coreTopology.on('all', function() {\n self.emit('all', null, self);\n });\n\n // Connect handler\n var connectHandler = function() {\n // Set up listeners\n self.s.coreTopology.once('timeout', errorHandler('timeout'));\n self.s.coreTopology.once('error', errorHandler('error'));\n self.s.coreTopology.once('close', errorHandler('close'));\n\n // Emit open event\n self.emit('open', null, self);\n\n // Return correctly\n try {\n callback(null, self);\n } catch (err) {\n process.nextTick(function() {\n throw err;\n });\n }\n };\n\n // Error handler\n var connectErrorHandler = function() {\n return function(err) {\n ['timeout', 'error', 'close'].forEach(function(e) {\n self.s.coreTopology.removeListener(e, connectErrorHandler);\n });\n\n self.s.coreTopology.removeListener('connect', connectErrorHandler);\n // Destroy the replset\n self.s.coreTopology.destroy();\n\n // Try to callback\n try {\n callback(err);\n } catch (err) {\n if (!self.s.coreTopology.isConnected())\n process.nextTick(function() {\n throw err;\n });\n }\n };\n };\n\n // Set up listeners\n self.s.coreTopology.once('timeout', connectErrorHandler('timeout'));\n self.s.coreTopology.once('error', connectErrorHandler('error'));\n self.s.coreTopology.once('close', connectErrorHandler('close'));\n self.s.coreTopology.once('connect', connectHandler);\n\n // Start connection\n self.s.coreTopology.connect(_options);\n }\n\n close(forceClosed, callback) {\n ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e));\n super.close(forceClosed, callback);\n }\n}\n\nObject.defineProperty(ReplSet.prototype, 'haInterval', {\n enumerable: true,\n get: function() {\n return this.s.coreTopology.s.haInterval;\n }\n});\n\n/**\n * A replset connect event, used to verify that the connection is up and running\n *\n * @event ReplSet#connect\n * @type {ReplSet}\n */\n\n/**\n * The replset high availability event\n *\n * @event ReplSet#ha\n * @type {function}\n * @param {string} type The stage in the high availability event (start|end)\n * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only\n * @param {number} data.id The id for this high availability request\n * @param {object} data.state An object containing the information about the current replicaset\n */\n\n/**\n * A server member left the replicaset\n *\n * @event ReplSet#left\n * @type {function}\n * @param {string} type The type of member that left (primary|secondary|arbiter)\n * @param {Server} server The server object that left\n */\n\n/**\n * A server member joined the replicaset\n *\n * @event ReplSet#joined\n * @type {function}\n * @param {string} type The type of member that joined (primary|secondary|arbiter)\n * @param {Server} server The server object that joined\n */\n\n/**\n * ReplSet open event, emitted when replicaset can start processing commands.\n *\n * @event ReplSet#open\n * @type {Replset}\n */\n\n/**\n * ReplSet fullsetup event, emitted when all servers in the topology have been connected to.\n *\n * @event ReplSet#fullsetup\n * @type {Replset}\n */\n\n/**\n * ReplSet close event\n *\n * @event ReplSet#close\n * @type {object}\n */\n\n/**\n * ReplSet error event, emitted if there is an error listener.\n *\n * @event ReplSet#error\n * @type {MongoError}\n */\n\n/**\n * ReplSet timeout event\n *\n * @event ReplSet#timeout\n * @type {object}\n */\n\n/**\n * ReplSet parseError event\n *\n * @event ReplSet#parseError\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command was started, if command monitoring is enabled\n *\n * @event ReplSet#commandStarted\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command succeeded, if command monitoring is enabled\n *\n * @event ReplSet#commandSucceeded\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command failed, if command monitoring is enabled\n *\n * @event ReplSet#commandFailed\n * @type {object}\n */\n\nmodule.exports = ReplSet;\n","'use strict';\n\nconst CServer = require('../core').Server;\nconst Cursor = require('../cursor');\nconst TopologyBase = require('./topology_base').TopologyBase;\nconst Store = require('./topology_base').Store;\nconst MongoError = require('../core').MongoError;\nconst MAX_JS_INT = require('../utils').MAX_JS_INT;\nconst translateOptions = require('../utils').translateOptions;\nconst filterOptions = require('../utils').filterOptions;\nconst mergeOptions = require('../utils').mergeOptions;\n\n/**\n * @fileOverview The **Server** class is a class that represents a single server topology and is\n * used to construct connections.\n *\n * **Server Should not be used, use MongoClient.connect**\n */\n\n// Allowed parameters\nvar legalOptionNames = [\n 'ha',\n 'haInterval',\n 'acceptableLatencyMS',\n 'poolSize',\n 'ssl',\n 'checkServerIdentity',\n 'sslValidate',\n 'sslCA',\n 'sslCRL',\n 'sslCert',\n 'ciphers',\n 'ecdhCurve',\n 'sslKey',\n 'sslPass',\n 'socketOptions',\n 'bufferMaxEntries',\n 'store',\n 'auto_reconnect',\n 'autoReconnect',\n 'emitError',\n 'keepAlive',\n 'keepAliveInitialDelay',\n 'noDelay',\n 'connectTimeoutMS',\n 'socketTimeoutMS',\n 'family',\n 'loggerLevel',\n 'logger',\n 'reconnectTries',\n 'reconnectInterval',\n 'monitoring',\n 'appname',\n 'domainsEnabled',\n 'servername',\n 'promoteLongs',\n 'promoteValues',\n 'promoteBuffers',\n 'compression',\n 'promiseLibrary',\n 'monitorCommands'\n];\n\n/**\n * Creates a new Server instance\n * @class\n * @deprecated\n * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host.\n * @param {number} [port] The server port if IP4.\n * @param {object} [options] Optional settings.\n * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons.\n * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support)\n * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.\n * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.\n * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.\n * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)\n * @param {string} [options.servername] String containing the server name requested via TLS SNI.\n * @param {object} [options.socketOptions] Socket options\n * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error.\n * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option.\n * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled\n * @param {number} [options.socketOptions.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket\n * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out\n * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out\n * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times\n * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries\n * @param {boolean} [options.monitoring=true] Triggers the server instance to call ismaster\n * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled.\n * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.\n * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology\n * @fires Server#connect\n * @fires Server#close\n * @fires Server#error\n * @fires Server#timeout\n * @fires Server#parseError\n * @fires Server#reconnect\n * @fires Server#commandStarted\n * @fires Server#commandSucceeded\n * @fires Server#commandFailed\n * @property {string} parserType the parser type used (c++ or js).\n * @return {Server} a Server instance.\n */\nclass Server extends TopologyBase {\n constructor(host, port, options) {\n super();\n var self = this;\n\n // Filter the options\n options = filterOptions(options, legalOptionNames);\n\n // Promise library\n const promiseLibrary = options.promiseLibrary;\n\n // Stored options\n var storeOptions = {\n force: false,\n bufferMaxEntries:\n typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT\n };\n\n // Shared global store\n var store = options.store || new Store(self, storeOptions);\n\n // Detect if we have a socket connection\n if (host.indexOf('/') !== -1) {\n if (port != null && typeof port === 'object') {\n options = port;\n port = null;\n }\n } else if (port == null) {\n throw MongoError.create({ message: 'port must be specified', driver: true });\n }\n\n // Get the reconnect option\n var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true;\n reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect;\n\n // Clone options\n var clonedOptions = mergeOptions(\n {},\n {\n host: host,\n port: port,\n disconnectHandler: store,\n cursorFactory: Cursor,\n reconnect: reconnect,\n emitError: typeof options.emitError === 'boolean' ? options.emitError : true,\n size: typeof options.poolSize === 'number' ? options.poolSize : 5,\n monitorCommands:\n typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false\n }\n );\n\n // Translate any SSL options and other connectivity options\n clonedOptions = translateOptions(clonedOptions, options);\n\n // Socket options\n var socketOptions =\n options.socketOptions && Object.keys(options.socketOptions).length > 0\n ? options.socketOptions\n : options;\n\n // Translate all the options to the core types\n clonedOptions = translateOptions(clonedOptions, socketOptions);\n\n // Define the internal properties\n this.s = {\n // Create an instance of a server instance from core module\n coreTopology: new CServer(clonedOptions),\n // Server capabilities\n sCapabilities: null,\n // Cloned options\n clonedOptions: clonedOptions,\n // Reconnect\n reconnect: clonedOptions.reconnect,\n // Emit error\n emitError: clonedOptions.emitError,\n // Pool size\n poolSize: clonedOptions.size,\n // Store Options\n storeOptions: storeOptions,\n // Store\n store: store,\n // Host\n host: host,\n // Port\n port: port,\n // Options\n options: options,\n // Server Session Pool\n sessionPool: null,\n // Active client sessions\n sessions: new Set(),\n // Promise library\n promiseLibrary: promiseLibrary || Promise\n };\n }\n\n // Connect\n connect(_options, callback) {\n var self = this;\n if ('function' === typeof _options) (callback = _options), (_options = {});\n if (_options == null) _options = this.s.clonedOptions;\n if (!('function' === typeof callback)) callback = null;\n _options = Object.assign({}, this.s.clonedOptions, _options);\n self.s.options = _options;\n\n // Update bufferMaxEntries\n self.s.storeOptions.bufferMaxEntries =\n typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1;\n\n // Error handler\n var connectErrorHandler = function() {\n return function(err) {\n // Remove all event handlers\n var events = ['timeout', 'error', 'close'];\n events.forEach(function(e) {\n self.s.coreTopology.removeListener(e, connectHandlers[e]);\n });\n\n self.s.coreTopology.removeListener('connect', connectErrorHandler);\n\n // Try to callback\n try {\n callback(err);\n } catch (err) {\n process.nextTick(function() {\n throw err;\n });\n }\n };\n };\n\n // Actual handler\n var errorHandler = function(event) {\n return function(err) {\n if (event !== 'error') {\n self.emit(event, err);\n }\n };\n };\n\n // Error handler\n var reconnectHandler = function() {\n self.emit('reconnect', self);\n self.s.store.execute();\n };\n\n // Reconnect failed\n var reconnectFailedHandler = function(err) {\n self.emit('reconnectFailed', err);\n self.s.store.flush(err);\n };\n\n // Destroy called on topology, perform cleanup\n var destroyHandler = function() {\n self.s.store.flush();\n };\n\n // relay the event\n var relay = function(event) {\n return function(t, server) {\n self.emit(event, t, server);\n };\n };\n\n // Connect handler\n var connectHandler = function() {\n // Clear out all the current handlers left over\n ['timeout', 'error', 'close', 'destroy'].forEach(function(e) {\n self.s.coreTopology.removeAllListeners(e);\n });\n\n // Set up listeners\n self.s.coreTopology.on('timeout', errorHandler('timeout'));\n self.s.coreTopology.once('error', errorHandler('error'));\n self.s.coreTopology.on('close', errorHandler('close'));\n // Only called on destroy\n self.s.coreTopology.on('destroy', destroyHandler);\n\n // Emit open event\n self.emit('open', null, self);\n\n // Return correctly\n try {\n callback(null, self);\n } catch (err) {\n process.nextTick(function() {\n throw err;\n });\n }\n };\n\n // Set up listeners\n var connectHandlers = {\n timeout: connectErrorHandler('timeout'),\n error: connectErrorHandler('error'),\n close: connectErrorHandler('close')\n };\n\n // Clear out all the current handlers left over\n [\n 'timeout',\n 'error',\n 'close',\n 'serverOpening',\n 'serverDescriptionChanged',\n 'serverHeartbeatStarted',\n 'serverHeartbeatSucceeded',\n 'serverHeartbeatFailed',\n 'serverClosed',\n 'topologyOpening',\n 'topologyClosed',\n 'topologyDescriptionChanged',\n 'commandStarted',\n 'commandSucceeded',\n 'commandFailed'\n ].forEach(function(e) {\n self.s.coreTopology.removeAllListeners(e);\n });\n\n // Add the event handlers\n self.s.coreTopology.once('timeout', connectHandlers.timeout);\n self.s.coreTopology.once('error', connectHandlers.error);\n self.s.coreTopology.once('close', connectHandlers.close);\n self.s.coreTopology.once('connect', connectHandler);\n // Reconnect server\n self.s.coreTopology.on('reconnect', reconnectHandler);\n self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler);\n\n // Set up SDAM listeners\n self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged'));\n self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted'));\n self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded'));\n self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed'));\n self.s.coreTopology.on('serverOpening', relay('serverOpening'));\n self.s.coreTopology.on('serverClosed', relay('serverClosed'));\n self.s.coreTopology.on('topologyOpening', relay('topologyOpening'));\n self.s.coreTopology.on('topologyClosed', relay('topologyClosed'));\n self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged'));\n self.s.coreTopology.on('commandStarted', relay('commandStarted'));\n self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded'));\n self.s.coreTopology.on('commandFailed', relay('commandFailed'));\n self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect'));\n self.s.coreTopology.on('monitoring', relay('monitoring'));\n\n // Start connection\n self.s.coreTopology.connect(_options);\n }\n}\n\nObject.defineProperty(Server.prototype, 'poolSize', {\n enumerable: true,\n get: function() {\n return this.s.coreTopology.connections().length;\n }\n});\n\nObject.defineProperty(Server.prototype, 'autoReconnect', {\n enumerable: true,\n get: function() {\n return this.s.reconnect;\n }\n});\n\nObject.defineProperty(Server.prototype, 'host', {\n enumerable: true,\n get: function() {\n return this.s.host;\n }\n});\n\nObject.defineProperty(Server.prototype, 'port', {\n enumerable: true,\n get: function() {\n return this.s.port;\n }\n});\n\n/**\n * Server connect event\n *\n * @event Server#connect\n * @type {object}\n */\n\n/**\n * Server close event\n *\n * @event Server#close\n * @type {object}\n */\n\n/**\n * Server reconnect event\n *\n * @event Server#reconnect\n * @type {object}\n */\n\n/**\n * Server error event\n *\n * @event Server#error\n * @type {MongoError}\n */\n\n/**\n * Server timeout event\n *\n * @event Server#timeout\n * @type {object}\n */\n\n/**\n * Server parseError event\n *\n * @event Server#parseError\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command was started, if command monitoring is enabled\n *\n * @event Server#commandStarted\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command succeeded, if command monitoring is enabled\n *\n * @event Server#commandSucceeded\n * @type {object}\n */\n\n/**\n * An event emitted indicating a command failed, if command monitoring is enabled\n *\n * @event Server#commandFailed\n * @type {object}\n */\n\nmodule.exports = Server;\n","'use strict';\n\nconst EventEmitter = require('events'),\n MongoError = require('../core').MongoError,\n f = require('util').format,\n ReadPreference = require('../core').ReadPreference,\n ClientSession = require('../core').Sessions.ClientSession;\n\n// The store of ops\nvar Store = function(topology, storeOptions) {\n var self = this;\n var storedOps = [];\n storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 };\n\n // Internal state\n this.s = {\n storedOps: storedOps,\n storeOptions: storeOptions,\n topology: topology\n };\n\n Object.defineProperty(this, 'length', {\n enumerable: true,\n get: function() {\n return self.s.storedOps.length;\n }\n });\n};\n\nStore.prototype.add = function(opType, ns, ops, options, callback) {\n if (this.s.storeOptions.force) {\n return callback(MongoError.create({ message: 'db closed by application', driver: true }));\n }\n\n if (this.s.storeOptions.bufferMaxEntries === 0) {\n return callback(\n MongoError.create({\n message: f(\n 'no connection available for operation and number of stored operation > %s',\n this.s.storeOptions.bufferMaxEntries\n ),\n driver: true\n })\n );\n }\n\n if (\n this.s.storeOptions.bufferMaxEntries > 0 &&\n this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries\n ) {\n while (this.s.storedOps.length > 0) {\n var op = this.s.storedOps.shift();\n op.c(\n MongoError.create({\n message: f(\n 'no connection available for operation and number of stored operation > %s',\n this.s.storeOptions.bufferMaxEntries\n ),\n driver: true\n })\n );\n }\n\n return;\n }\n\n this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback });\n};\n\nStore.prototype.addObjectAndMethod = function(opType, object, method, params, callback) {\n if (this.s.storeOptions.force) {\n return callback(MongoError.create({ message: 'db closed by application', driver: true }));\n }\n\n if (this.s.storeOptions.bufferMaxEntries === 0) {\n return callback(\n MongoError.create({\n message: f(\n 'no connection available for operation and number of stored operation > %s',\n this.s.storeOptions.bufferMaxEntries\n ),\n driver: true\n })\n );\n }\n\n if (\n this.s.storeOptions.bufferMaxEntries > 0 &&\n this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries\n ) {\n while (this.s.storedOps.length > 0) {\n var op = this.s.storedOps.shift();\n op.c(\n MongoError.create({\n message: f(\n 'no connection available for operation and number of stored operation > %s',\n this.s.storeOptions.bufferMaxEntries\n ),\n driver: true\n })\n );\n }\n\n return;\n }\n\n this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback });\n};\n\nStore.prototype.flush = function(err) {\n while (this.s.storedOps.length > 0) {\n this.s.storedOps\n .shift()\n .c(\n err ||\n MongoError.create({ message: f('no connection available for operation'), driver: true })\n );\n }\n};\n\nvar primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred'];\nvar secondaryOptions = ['secondary', 'secondaryPreferred'];\n\nStore.prototype.execute = function(options) {\n options = options || {};\n // Get current ops\n var ops = this.s.storedOps;\n // Reset the ops\n this.s.storedOps = [];\n\n // Unpack options\n var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true;\n var executeSecondary =\n typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true;\n\n // Execute all the stored ops\n while (ops.length > 0) {\n var op = ops.shift();\n\n if (op.t === 'cursor') {\n if (executePrimary && executeSecondary) {\n op.o[op.m].apply(op.o, op.p);\n } else if (\n executePrimary &&\n op.o.options &&\n op.o.options.readPreference &&\n primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1\n ) {\n op.o[op.m].apply(op.o, op.p);\n } else if (\n !executePrimary &&\n executeSecondary &&\n op.o.options &&\n op.o.options.readPreference &&\n secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1\n ) {\n op.o[op.m].apply(op.o, op.p);\n }\n } else if (op.t === 'auth') {\n this.s.topology[op.t].apply(this.s.topology, op.o);\n } else {\n if (executePrimary && executeSecondary) {\n this.s.topology[op.t](op.n, op.o, op.op, op.c);\n } else if (\n executePrimary &&\n op.op &&\n op.op.readPreference &&\n primaryOptions.indexOf(op.op.readPreference.mode) !== -1\n ) {\n this.s.topology[op.t](op.n, op.o, op.op, op.c);\n } else if (\n !executePrimary &&\n executeSecondary &&\n op.op &&\n op.op.readPreference &&\n secondaryOptions.indexOf(op.op.readPreference.mode) !== -1\n ) {\n this.s.topology[op.t](op.n, op.o, op.op, op.c);\n }\n }\n }\n};\n\nStore.prototype.all = function() {\n return this.s.storedOps;\n};\n\n// Server capabilities\nvar ServerCapabilities = function(ismaster) {\n var setup_get_property = function(object, name, value) {\n Object.defineProperty(object, name, {\n enumerable: true,\n get: function() {\n return value;\n }\n });\n };\n\n // Capabilities\n var aggregationCursor = false;\n var writeCommands = false;\n var textSearch = false;\n var authCommands = false;\n var listCollections = false;\n var listIndexes = false;\n var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000;\n var commandsTakeWriteConcern = false;\n var commandsTakeCollation = false;\n\n if (ismaster.minWireVersion >= 0) {\n textSearch = true;\n }\n\n if (ismaster.maxWireVersion >= 1) {\n aggregationCursor = true;\n authCommands = true;\n }\n\n if (ismaster.maxWireVersion >= 2) {\n writeCommands = true;\n }\n\n if (ismaster.maxWireVersion >= 3) {\n listCollections = true;\n listIndexes = true;\n }\n\n if (ismaster.maxWireVersion >= 5) {\n commandsTakeWriteConcern = true;\n commandsTakeCollation = true;\n }\n\n // If no min or max wire version set to 0\n if (ismaster.minWireVersion == null) {\n ismaster.minWireVersion = 0;\n }\n\n if (ismaster.maxWireVersion == null) {\n ismaster.maxWireVersion = 0;\n }\n\n // Map up read only parameters\n setup_get_property(this, 'hasAggregationCursor', aggregationCursor);\n setup_get_property(this, 'hasWriteCommands', writeCommands);\n setup_get_property(this, 'hasTextSearch', textSearch);\n setup_get_property(this, 'hasAuthCommands', authCommands);\n setup_get_property(this, 'hasListCollectionsCommand', listCollections);\n setup_get_property(this, 'hasListIndexesCommand', listIndexes);\n setup_get_property(this, 'minWireVersion', ismaster.minWireVersion);\n setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion);\n setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch);\n setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern);\n setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation);\n};\n\nclass TopologyBase extends EventEmitter {\n constructor() {\n super();\n this.setMaxListeners(Infinity);\n }\n\n // Sessions related methods\n hasSessionSupport() {\n return this.logicalSessionTimeoutMinutes != null;\n }\n\n startSession(options, clientOptions) {\n const session = new ClientSession(this, this.s.sessionPool, options, clientOptions);\n\n session.once('ended', () => {\n this.s.sessions.delete(session);\n });\n\n this.s.sessions.add(session);\n return session;\n }\n\n endSessions(sessions, callback) {\n return this.s.coreTopology.endSessions(sessions, callback);\n }\n\n get clientMetadata() {\n return this.s.coreTopology.s.options.metadata;\n }\n\n // Server capabilities\n capabilities() {\n if (this.s.sCapabilities) return this.s.sCapabilities;\n if (this.s.coreTopology.lastIsMaster() == null) return null;\n this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster());\n return this.s.sCapabilities;\n }\n\n // Command\n command(ns, cmd, options, callback) {\n this.s.coreTopology.command(ns.toString(), cmd, ReadPreference.translate(options), callback);\n }\n\n // Insert\n insert(ns, ops, options, callback) {\n this.s.coreTopology.insert(ns.toString(), ops, options, callback);\n }\n\n // Update\n update(ns, ops, options, callback) {\n this.s.coreTopology.update(ns.toString(), ops, options, callback);\n }\n\n // Remove\n remove(ns, ops, options, callback) {\n this.s.coreTopology.remove(ns.toString(), ops, options, callback);\n }\n\n // IsConnected\n isConnected(options) {\n options = options || {};\n options = ReadPreference.translate(options);\n\n return this.s.coreTopology.isConnected(options);\n }\n\n // IsDestroyed\n isDestroyed() {\n return this.s.coreTopology.isDestroyed();\n }\n\n // Cursor\n cursor(ns, cmd, options) {\n options = options || {};\n options = ReadPreference.translate(options);\n options.disconnectHandler = this.s.store;\n options.topology = this;\n\n return this.s.coreTopology.cursor(ns, cmd, options);\n }\n\n lastIsMaster() {\n return this.s.coreTopology.lastIsMaster();\n }\n\n selectServer(selector, options, callback) {\n return this.s.coreTopology.selectServer(selector, options, callback);\n }\n\n /**\n * Unref all sockets\n * @method\n */\n unref() {\n return this.s.coreTopology.unref();\n }\n\n /**\n * All raw connections\n * @method\n * @return {array}\n */\n connections() {\n return this.s.coreTopology.connections();\n }\n\n close(forceClosed, callback) {\n // If we have sessions, we want to individually move them to the session pool,\n // and then send a single endSessions call.\n this.s.sessions.forEach(session => session.endSession());\n\n if (this.s.sessionPool) {\n this.s.sessionPool.endAllPooledSessions();\n }\n\n // We need to wash out all stored processes\n if (forceClosed === true) {\n this.s.storeOptions.force = forceClosed;\n this.s.store.flush();\n }\n\n this.s.coreTopology.destroy(\n {\n force: typeof forceClosed === 'boolean' ? forceClosed : false\n },\n callback\n );\n }\n}\n\n// Properties\nObject.defineProperty(TopologyBase.prototype, 'bson', {\n enumerable: true,\n get: function() {\n return this.s.coreTopology.s.bson;\n }\n});\n\nObject.defineProperty(TopologyBase.prototype, 'parserType', {\n enumerable: true,\n get: function() {\n return this.s.coreTopology.parserType;\n }\n});\n\nObject.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', {\n enumerable: true,\n get: function() {\n return this.s.coreTopology.logicalSessionTimeoutMinutes;\n }\n});\n\nObject.defineProperty(TopologyBase.prototype, 'type', {\n enumerable: true,\n get: function() {\n return this.s.coreTopology.type;\n }\n});\n\nexports.Store = Store;\nexports.ServerCapabilities = ServerCapabilities;\nexports.TopologyBase = TopologyBase;\n","'use strict';\n\nconst ReadPreference = require('./core').ReadPreference,\n parser = require('url'),\n f = require('util').format,\n Logger = require('./core').Logger,\n dns = require('dns');\nconst ReadConcern = require('./read_concern');\n\nmodule.exports = function(url, options, callback) {\n if (typeof options === 'function') (callback = options), (options = {});\n options = options || {};\n\n let result;\n try {\n result = parser.parse(url, true);\n } catch (e) {\n return callback(new Error('URL malformed, cannot be parsed'));\n }\n\n if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') {\n return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`'));\n }\n\n if (result.protocol === 'mongodb:') {\n return parseHandler(url, options, callback);\n }\n\n // Otherwise parse this as an SRV record\n if (result.hostname.split('.').length < 3) {\n return callback(new Error('URI does not have hostname, domain name and tld'));\n }\n\n result.domainLength = result.hostname.split('.').length;\n\n if (result.pathname && result.pathname.match(',')) {\n return callback(new Error('Invalid URI, cannot contain multiple hostnames'));\n }\n\n if (result.port) {\n return callback(new Error('Ports not accepted with `mongodb+srv` URIs'));\n }\n\n let srvAddress = `_mongodb._tcp.${result.host}`;\n dns.resolveSrv(srvAddress, function(err, addresses) {\n if (err) return callback(err);\n\n if (addresses.length === 0) {\n return callback(new Error('No addresses found at host'));\n }\n\n for (let i = 0; i < addresses.length; i++) {\n if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) {\n return callback(new Error('Server record does not share hostname with parent URI'));\n }\n }\n\n let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`;\n let connectionStrings = addresses.map(function(address, i) {\n if (i === 0) return `${base}${address.name}:${address.port}`;\n else return `${address.name}:${address.port}`;\n });\n\n let connectionString = connectionStrings.join(',') + '/';\n let connectionStringOptions = [];\n\n // Add the default database if needed\n if (result.path) {\n let defaultDb = result.path.slice(1);\n if (defaultDb.indexOf('?') !== -1) {\n defaultDb = defaultDb.slice(0, defaultDb.indexOf('?'));\n }\n\n connectionString += defaultDb;\n }\n\n // Default to SSL true\n if (!options.ssl && !result.search) {\n connectionStringOptions.push('ssl=true');\n } else if (!options.ssl && result.search && !result.search.match('ssl')) {\n connectionStringOptions.push('ssl=true');\n }\n\n // Keep original uri options\n if (result.search) {\n connectionStringOptions.push(result.search.replace('?', ''));\n }\n\n dns.resolveTxt(result.host, function(err, record) {\n if (err && err.code !== 'ENODATA') return callback(err);\n if (err && err.code === 'ENODATA') record = null;\n\n if (record) {\n if (record.length > 1) {\n return callback(new Error('Multiple text records not allowed'));\n }\n\n record = record[0];\n if (record.length > 1) record = record.join('');\n else record = record[0];\n\n if (!record.includes('authSource') && !record.includes('replicaSet')) {\n return callback(new Error('Text record must only set `authSource` or `replicaSet`'));\n }\n\n connectionStringOptions.push(record);\n }\n\n // Add any options to the connection string\n if (connectionStringOptions.length) {\n connectionString += `?${connectionStringOptions.join('&')}`;\n }\n\n parseHandler(connectionString, options, callback);\n });\n });\n};\n\nfunction matchesParentDomain(srvAddress, parentDomain) {\n let regex = /^.*?\\./;\n let srv = `.${srvAddress.replace(regex, '')}`;\n let parent = `.${parentDomain.replace(regex, '')}`;\n if (srv.endsWith(parent)) return true;\n else return false;\n}\n\nfunction parseHandler(address, options, callback) {\n let result, err;\n try {\n result = parseConnectionString(address, options);\n } catch (e) {\n err = e;\n }\n\n return err ? callback(err, null) : callback(null, result);\n}\n\nfunction parseConnectionString(url, options) {\n // Variables\n let connection_part = '';\n let auth_part = '';\n let query_string_part = '';\n let dbName = 'admin';\n\n // Url parser result\n let result = parser.parse(url, true);\n if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) {\n throw new Error('No hostname or hostnames provided in connection string');\n }\n\n if (result.port === '0') {\n throw new Error('Invalid port (zero) with hostname');\n }\n\n if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) {\n throw new Error('Invalid port (larger than 65535) with hostname');\n }\n\n if (\n result.path &&\n result.path.length > 0 &&\n result.path[0] !== '/' &&\n url.indexOf('.sock') === -1\n ) {\n throw new Error('Missing delimiting slash between hosts and options');\n }\n\n if (result.query) {\n for (let name in result.query) {\n if (name.indexOf('::') !== -1) {\n throw new Error('Double colon in host identifier');\n }\n\n if (result.query[name] === '') {\n throw new Error('Query parameter ' + name + ' is an incomplete value pair');\n }\n }\n }\n\n if (result.auth) {\n let parts = result.auth.split(':');\n if (url.indexOf(result.auth) !== -1 && parts.length > 2) {\n throw new Error('Username with password containing an unescaped colon');\n }\n\n if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) {\n throw new Error('Username containing an unescaped at-sign');\n }\n }\n\n // Remove query\n let clean = url.split('?').shift();\n\n // Extract the list of hosts\n let strings = clean.split(',');\n let hosts = [];\n\n for (let i = 0; i < strings.length; i++) {\n let hostString = strings[i];\n\n if (hostString.indexOf('mongodb') !== -1) {\n if (hostString.indexOf('@') !== -1) {\n hosts.push(hostString.split('@').pop());\n } else {\n hosts.push(hostString.substr('mongodb://'.length));\n }\n } else if (hostString.indexOf('/') !== -1) {\n hosts.push(hostString.split('/').shift());\n } else if (hostString.indexOf('/') === -1) {\n hosts.push(hostString.trim());\n }\n }\n\n for (let i = 0; i < hosts.length; i++) {\n let r = parser.parse(f('mongodb://%s', hosts[i].trim()));\n if (r.path && r.path.indexOf('.sock') !== -1) continue;\n if (r.path && r.path.indexOf(':') !== -1) {\n // Not connecting to a socket so check for an extra slash in the hostname.\n // Using String#split as perf is better than match.\n if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) {\n throw new Error('Slash in host identifier');\n } else {\n throw new Error('Double colon in host identifier');\n }\n }\n }\n\n // If we have a ? mark cut the query elements off\n if (url.indexOf('?') !== -1) {\n query_string_part = url.substr(url.indexOf('?') + 1);\n connection_part = url.substring('mongodb://'.length, url.indexOf('?'));\n } else {\n connection_part = url.substring('mongodb://'.length);\n }\n\n // Check if we have auth params\n if (connection_part.indexOf('@') !== -1) {\n auth_part = connection_part.split('@')[0];\n connection_part = connection_part.split('@')[1];\n }\n\n // Check there is not more than one unescaped slash\n if (connection_part.split('/').length > 2) {\n throw new Error(\n \"Unsupported host '\" +\n connection_part.split('?')[0] +\n \"', hosts must be URL encoded and contain at most one unencoded slash\"\n );\n }\n\n // Check if the connection string has a db\n if (connection_part.indexOf('.sock') !== -1) {\n if (connection_part.indexOf('.sock/') !== -1) {\n dbName = connection_part.split('.sock/')[1];\n // Check if multiple database names provided, or just an illegal trailing backslash\n if (dbName.indexOf('/') !== -1) {\n if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) {\n throw new Error('Illegal trailing backslash after database name');\n }\n throw new Error('More than 1 database name in URL');\n }\n connection_part = connection_part.split(\n '/',\n connection_part.indexOf('.sock') + '.sock'.length\n );\n }\n } else if (connection_part.indexOf('/') !== -1) {\n // Check if multiple database names provided, or just an illegal trailing backslash\n if (connection_part.split('/').length > 2) {\n if (connection_part.split('/')[2].length === 0) {\n throw new Error('Illegal trailing backslash after database name');\n }\n throw new Error('More than 1 database name in URL');\n }\n dbName = connection_part.split('/')[1];\n connection_part = connection_part.split('/')[0];\n }\n\n // URI decode the host information\n connection_part = decodeURIComponent(connection_part);\n\n // Result object\n let object = {};\n\n // Pick apart the authentication part of the string\n let authPart = auth_part || '';\n let auth = authPart.split(':', 2);\n\n // Decode the authentication URI components and verify integrity\n let user = decodeURIComponent(auth[0]);\n if (auth[0] !== encodeURIComponent(user)) {\n throw new Error('Username contains an illegal unescaped character');\n }\n auth[0] = user;\n\n if (auth[1]) {\n let pass = decodeURIComponent(auth[1]);\n if (auth[1] !== encodeURIComponent(pass)) {\n throw new Error('Password contains an illegal unescaped character');\n }\n auth[1] = pass;\n }\n\n // Add auth to final object if we have 2 elements\n if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] };\n // if user provided auth options, use that\n if (options && options.auth != null) object.auth = options.auth;\n\n // Variables used for temporary storage\n let hostPart;\n let urlOptions;\n let servers;\n let compression;\n let serverOptions = { socketOptions: {} };\n let dbOptions = { read_preference_tags: [] };\n let replSetServersOptions = { socketOptions: {} };\n let mongosOptions = { socketOptions: {} };\n // Add server options to final object\n object.server_options = serverOptions;\n object.db_options = dbOptions;\n object.rs_options = replSetServersOptions;\n object.mongos_options = mongosOptions;\n\n // Let's check if we are using a domain socket\n if (url.match(/\\.sock/)) {\n // Split out the socket part\n let domainSocket = url.substring(\n url.indexOf('mongodb://') + 'mongodb://'.length,\n url.lastIndexOf('.sock') + '.sock'.length\n );\n // Clean out any auth stuff if any\n if (domainSocket.indexOf('@') !== -1) domainSocket = domainSocket.split('@')[1];\n domainSocket = decodeURIComponent(domainSocket);\n servers = [{ domain_socket: domainSocket }];\n } else {\n // Split up the db\n hostPart = connection_part;\n // Deduplicate servers\n let deduplicatedServers = {};\n\n // Parse all server results\n servers = hostPart\n .split(',')\n .map(function(h) {\n let _host, _port, ipv6match;\n //check if it matches [IPv6]:port, where the port number is optional\n if ((ipv6match = /\\[([^\\]]+)\\](?::(.+))?/.exec(h))) {\n _host = ipv6match[1];\n _port = parseInt(ipv6match[2], 10) || 27017;\n } else {\n //otherwise assume it's IPv4, or plain hostname\n let hostPort = h.split(':', 2);\n _host = hostPort[0] || 'localhost';\n _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017;\n // Check for localhost?safe=true style case\n if (_host.indexOf('?') !== -1) _host = _host.split(/\\?/)[0];\n }\n\n // No entry returned for duplicate server\n if (deduplicatedServers[_host + '_' + _port]) return null;\n deduplicatedServers[_host + '_' + _port] = 1;\n\n // Return the mapped object\n return { host: _host, port: _port };\n })\n .filter(function(x) {\n return x != null;\n });\n }\n\n // Get the db name\n object.dbName = dbName || 'admin';\n // Split up all the options\n urlOptions = (query_string_part || '').split(/[&;]/);\n // Ugh, we have to figure out which options go to which constructor manually.\n urlOptions.forEach(function(opt) {\n if (!opt) return;\n var splitOpt = opt.split('='),\n name = splitOpt[0],\n value = splitOpt[1];\n\n // Options implementations\n switch (name) {\n case 'slaveOk':\n case 'slave_ok':\n serverOptions.slave_ok = value === 'true';\n dbOptions.slaveOk = value === 'true';\n break;\n case 'maxPoolSize':\n case 'poolSize':\n serverOptions.poolSize = parseInt(value, 10);\n replSetServersOptions.poolSize = parseInt(value, 10);\n break;\n case 'appname':\n object.appname = decodeURIComponent(value);\n break;\n case 'autoReconnect':\n case 'auto_reconnect':\n serverOptions.auto_reconnect = value === 'true';\n break;\n case 'ssl':\n if (value === 'prefer') {\n serverOptions.ssl = value;\n replSetServersOptions.ssl = value;\n mongosOptions.ssl = value;\n break;\n }\n serverOptions.ssl = value === 'true';\n replSetServersOptions.ssl = value === 'true';\n mongosOptions.ssl = value === 'true';\n break;\n case 'sslValidate':\n serverOptions.sslValidate = value === 'true';\n replSetServersOptions.sslValidate = value === 'true';\n mongosOptions.sslValidate = value === 'true';\n break;\n case 'replicaSet':\n case 'rs_name':\n replSetServersOptions.rs_name = value;\n break;\n case 'reconnectWait':\n replSetServersOptions.reconnectWait = parseInt(value, 10);\n break;\n case 'retries':\n replSetServersOptions.retries = parseInt(value, 10);\n break;\n case 'readSecondary':\n case 'read_secondary':\n replSetServersOptions.read_secondary = value === 'true';\n break;\n case 'fsync':\n dbOptions.fsync = value === 'true';\n break;\n case 'journal':\n dbOptions.j = value === 'true';\n break;\n case 'safe':\n dbOptions.safe = value === 'true';\n break;\n case 'nativeParser':\n case 'native_parser':\n dbOptions.native_parser = value === 'true';\n break;\n case 'readConcernLevel':\n dbOptions.readConcern = new ReadConcern(value);\n break;\n case 'connectTimeoutMS':\n serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10);\n replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10);\n mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10);\n break;\n case 'socketTimeoutMS':\n serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10);\n replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10);\n mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10);\n break;\n case 'w':\n dbOptions.w = parseInt(value, 10);\n if (isNaN(dbOptions.w)) dbOptions.w = value;\n break;\n case 'authSource':\n dbOptions.authSource = value;\n break;\n case 'gssapiServiceName':\n dbOptions.gssapiServiceName = value;\n break;\n case 'authMechanism':\n if (value === 'GSSAPI') {\n // If no password provided decode only the principal\n if (object.auth == null) {\n let urlDecodeAuthPart = decodeURIComponent(authPart);\n if (urlDecodeAuthPart.indexOf('@') === -1)\n throw new Error('GSSAPI requires a provided principal');\n object.auth = { user: urlDecodeAuthPart, password: null };\n } else {\n object.auth.user = decodeURIComponent(object.auth.user);\n }\n } else if (value === 'MONGODB-X509') {\n object.auth = { user: decodeURIComponent(authPart) };\n }\n\n // Only support GSSAPI or MONGODB-CR for now\n if (\n value !== 'GSSAPI' &&\n value !== 'MONGODB-X509' &&\n value !== 'MONGODB-CR' &&\n value !== 'DEFAULT' &&\n value !== 'SCRAM-SHA-1' &&\n value !== 'SCRAM-SHA-256' &&\n value !== 'PLAIN'\n )\n throw new Error(\n 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism'\n );\n\n // Authentication mechanism\n dbOptions.authMechanism = value;\n break;\n case 'authMechanismProperties':\n {\n // Split up into key, value pairs\n let values = value.split(',');\n let o = {};\n // For each value split into key, value\n values.forEach(function(x) {\n let v = x.split(':');\n o[v[0]] = v[1];\n });\n\n // Set all authMechanismProperties\n dbOptions.authMechanismProperties = o;\n // Set the service name value\n if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME;\n if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM;\n if (typeof o.CANONICALIZE_HOST_NAME === 'string')\n dbOptions.gssapiCanonicalizeHostName =\n o.CANONICALIZE_HOST_NAME === 'true' ? true : false;\n }\n break;\n case 'wtimeoutMS':\n dbOptions.wtimeout = parseInt(value, 10);\n break;\n case 'readPreference':\n if (!ReadPreference.isValid(value))\n throw new Error(\n 'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest'\n );\n dbOptions.readPreference = value;\n break;\n case 'maxStalenessSeconds':\n dbOptions.maxStalenessSeconds = parseInt(value, 10);\n break;\n case 'readPreferenceTags':\n {\n // Decode the value\n value = decodeURIComponent(value);\n // Contains the tag object\n let tagObject = {};\n if (value == null || value === '') {\n dbOptions.read_preference_tags.push(tagObject);\n break;\n }\n\n // Split up the tags\n let tags = value.split(/,/);\n for (let i = 0; i < tags.length; i++) {\n let parts = tags[i].trim().split(/:/);\n tagObject[parts[0]] = parts[1];\n }\n\n // Set the preferences tags\n dbOptions.read_preference_tags.push(tagObject);\n }\n break;\n case 'compressors':\n {\n compression = serverOptions.compression || {};\n let compressors = value.split(',');\n if (\n !compressors.every(function(compressor) {\n return compressor === 'snappy' || compressor === 'zlib';\n })\n ) {\n throw new Error('Compressors must be at least one of snappy or zlib');\n }\n\n compression.compressors = compressors;\n serverOptions.compression = compression;\n }\n break;\n case 'zlibCompressionLevel':\n {\n compression = serverOptions.compression || {};\n let zlibCompressionLevel = parseInt(value, 10);\n if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) {\n throw new Error('zlibCompressionLevel must be an integer between -1 and 9');\n }\n\n compression.zlibCompressionLevel = zlibCompressionLevel;\n serverOptions.compression = compression;\n }\n break;\n case 'retryWrites':\n dbOptions.retryWrites = value === 'true';\n break;\n case 'minSize':\n dbOptions.minSize = parseInt(value, 10);\n break;\n default:\n {\n let logger = Logger('URL Parser');\n logger.warn(`${name} is not supported as a connection string option`);\n }\n break;\n }\n });\n\n // No tags: should be null (not [])\n if (dbOptions.read_preference_tags.length === 0) {\n dbOptions.read_preference_tags = null;\n }\n\n // Validate if there are an invalid write concern combinations\n if (\n (dbOptions.w === -1 || dbOptions.w === 0) &&\n (dbOptions.journal === true || dbOptions.fsync === true || dbOptions.safe === true)\n )\n throw new Error('w set to -1 or 0 cannot be combined with safe/w/journal/fsync');\n\n // If no read preference set it to primary\n if (!dbOptions.readPreference) {\n dbOptions.readPreference = 'primary';\n }\n\n // make sure that user-provided options are applied with priority\n dbOptions = Object.assign(dbOptions, options);\n\n // Add servers to result\n object.servers = servers;\n\n // Returned parsed object\n return object;\n}\n","'use strict';\nconst MongoError = require('./core/error').MongoError;\nconst WriteConcern = require('./write_concern');\n\nvar shallowClone = function(obj) {\n var copy = {};\n for (var name in obj) copy[name] = obj[name];\n return copy;\n};\n\n// Set simple property\nvar getSingleProperty = function(obj, name, value) {\n Object.defineProperty(obj, name, {\n enumerable: true,\n get: function() {\n return value;\n }\n });\n};\n\nvar formatSortValue = (exports.formatSortValue = function(sortDirection) {\n var value = ('' + sortDirection).toLowerCase();\n\n switch (value) {\n case 'ascending':\n case 'asc':\n case '1':\n return 1;\n case 'descending':\n case 'desc':\n case '-1':\n return -1;\n default:\n throw new Error(\n 'Illegal sort clause, must be of the form ' +\n \"[['field1', '(ascending|descending)'], \" +\n \"['field2', '(ascending|descending)']]\"\n );\n }\n});\n\nvar formattedOrderClause = (exports.formattedOrderClause = function(sortValue) {\n var orderBy = {};\n if (sortValue == null) return null;\n if (Array.isArray(sortValue)) {\n if (sortValue.length === 0) {\n return null;\n }\n\n for (var i = 0; i < sortValue.length; i++) {\n if (sortValue[i].constructor === String) {\n orderBy[sortValue[i]] = 1;\n } else {\n orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]);\n }\n }\n } else if (sortValue != null && typeof sortValue === 'object') {\n orderBy = sortValue;\n } else if (typeof sortValue === 'string') {\n orderBy[sortValue] = 1;\n } else {\n throw new Error(\n 'Illegal sort clause, must be of the form ' +\n \"[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]\"\n );\n }\n\n return orderBy;\n});\n\nvar checkCollectionName = function checkCollectionName(collectionName) {\n if ('string' !== typeof collectionName) {\n throw new MongoError('collection name must be a String');\n }\n\n if (!collectionName || collectionName.indexOf('..') !== -1) {\n throw new MongoError('collection names cannot be empty');\n }\n\n if (\n collectionName.indexOf('$') !== -1 &&\n collectionName.match(/((^\\$cmd)|(oplog\\.\\$main))/) == null\n ) {\n throw new MongoError(\"collection names must not contain '$'\");\n }\n\n if (collectionName.match(/^\\.|\\.$/) != null) {\n throw new MongoError(\"collection names must not start or end with '.'\");\n }\n\n // Validate that we are not passing 0x00 in the collection name\n if (collectionName.indexOf('\\x00') !== -1) {\n throw new MongoError('collection names cannot contain a null character');\n }\n};\n\nvar handleCallback = function(callback, err, value1, value2) {\n try {\n if (callback == null) return;\n\n if (callback) {\n return value2 ? callback(err, value1, value2) : callback(err, value1);\n }\n } catch (err) {\n process.nextTick(function() {\n throw err;\n });\n return false;\n }\n\n return true;\n};\n\n/**\n * Wrap a Mongo error document in an Error instance\n * @ignore\n * @api private\n */\nvar toError = function(error) {\n if (error instanceof Error) return error;\n\n var msg = error.err || error.errmsg || error.errMessage || error;\n var e = MongoError.create({ message: msg, driver: true });\n\n // Get all object keys\n var keys = typeof error === 'object' ? Object.keys(error) : [];\n\n for (var i = 0; i < keys.length; i++) {\n try {\n e[keys[i]] = error[keys[i]];\n } catch (err) {\n // continue\n }\n }\n\n return e;\n};\n\n/**\n * @ignore\n */\nvar normalizeHintField = function normalizeHintField(hint) {\n var finalHint = null;\n\n if (typeof hint === 'string') {\n finalHint = hint;\n } else if (Array.isArray(hint)) {\n finalHint = {};\n\n hint.forEach(function(param) {\n finalHint[param] = 1;\n });\n } else if (hint != null && typeof hint === 'object') {\n finalHint = {};\n for (var name in hint) {\n finalHint[name] = hint[name];\n }\n }\n\n return finalHint;\n};\n\n/**\n * Create index name based on field spec\n *\n * @ignore\n * @api private\n */\nvar parseIndexOptions = function(fieldOrSpec) {\n var fieldHash = {};\n var indexes = [];\n var keys;\n\n // Get all the fields accordingly\n if ('string' === typeof fieldOrSpec) {\n // 'type'\n indexes.push(fieldOrSpec + '_' + 1);\n fieldHash[fieldOrSpec] = 1;\n } else if (Array.isArray(fieldOrSpec)) {\n fieldOrSpec.forEach(function(f) {\n if ('string' === typeof f) {\n // [{location:'2d'}, 'type']\n indexes.push(f + '_' + 1);\n fieldHash[f] = 1;\n } else if (Array.isArray(f)) {\n // [['location', '2d'],['type', 1]]\n indexes.push(f[0] + '_' + (f[1] || 1));\n fieldHash[f[0]] = f[1] || 1;\n } else if (isObject(f)) {\n // [{location:'2d'}, {type:1}]\n keys = Object.keys(f);\n keys.forEach(function(k) {\n indexes.push(k + '_' + f[k]);\n fieldHash[k] = f[k];\n });\n } else {\n // undefined (ignore)\n }\n });\n } else if (isObject(fieldOrSpec)) {\n // {location:'2d', type:1}\n keys = Object.keys(fieldOrSpec);\n keys.forEach(function(key) {\n indexes.push(key + '_' + fieldOrSpec[key]);\n fieldHash[key] = fieldOrSpec[key];\n });\n }\n\n return {\n name: indexes.join('_'),\n keys: keys,\n fieldHash: fieldHash\n };\n};\n\nvar isObject = (exports.isObject = function(arg) {\n return '[object Object]' === Object.prototype.toString.call(arg);\n});\n\nvar debugOptions = function(debugFields, options) {\n var finaloptions = {};\n debugFields.forEach(function(n) {\n finaloptions[n] = options[n];\n });\n\n return finaloptions;\n};\n\nvar decorateCommand = function(command, options, exclude) {\n for (var name in options) {\n if (exclude.indexOf(name) === -1) command[name] = options[name];\n }\n\n return command;\n};\n\nvar mergeOptions = function(target, source) {\n for (var name in source) {\n target[name] = source[name];\n }\n\n return target;\n};\n\n// Merge options with translation\nvar translateOptions = function(target, source) {\n var translations = {\n // SSL translation options\n sslCA: 'ca',\n sslCRL: 'crl',\n sslValidate: 'rejectUnauthorized',\n sslKey: 'key',\n sslCert: 'cert',\n sslPass: 'passphrase',\n // SocketTimeout translation options\n socketTimeoutMS: 'socketTimeout',\n connectTimeoutMS: 'connectionTimeout',\n // Replicaset options\n replicaSet: 'setName',\n rs_name: 'setName',\n secondaryAcceptableLatencyMS: 'acceptableLatency',\n connectWithNoPrimary: 'secondaryOnlyConnectionAllowed',\n // Mongos options\n acceptableLatencyMS: 'localThresholdMS'\n };\n\n for (var name in source) {\n if (translations[name]) {\n target[translations[name]] = source[name];\n } else {\n target[name] = source[name];\n }\n }\n\n return target;\n};\n\nvar filterOptions = function(options, names) {\n var filterOptions = {};\n\n for (var name in options) {\n if (names.indexOf(name) !== -1) filterOptions[name] = options[name];\n }\n\n // Filtered options\n return filterOptions;\n};\n\n// Write concern keys\nvar writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync'];\n\n// Merge the write concern options\nvar mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) {\n // Mix in any allowed options\n for (var i = 0; i < keys.length; i++) {\n if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) {\n targetOptions[keys[i]] = sourceOptions[keys[i]];\n }\n }\n\n // No merging of write concern\n if (!mergeWriteConcern) return targetOptions;\n\n // Found no write Concern options\n var found = false;\n for (i = 0; i < writeConcernKeys.length; i++) {\n if (targetOptions[writeConcernKeys[i]]) {\n found = true;\n break;\n }\n }\n\n if (!found) {\n for (i = 0; i < writeConcernKeys.length; i++) {\n if (sourceOptions[writeConcernKeys[i]]) {\n targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]];\n }\n }\n }\n\n return targetOptions;\n};\n\n/**\n * Executes the given operation with provided arguments.\n *\n * This method reduces large amounts of duplication in the entire codebase by providing\n * a single point for determining whether callbacks or promises should be used. Additionally\n * it allows for a single point of entry to provide features such as implicit sessions, which\n * are required by the Driver Sessions specification in the event that a ClientSession is\n * not provided\n *\n * @param {object} topology The topology to execute this operation on\n * @param {function} operation The operation to execute\n * @param {array} args Arguments to apply the provided operation\n * @param {object} [options] Options that modify the behavior of the method\n */\nconst executeLegacyOperation = (topology, operation, args, options) => {\n if (topology == null) {\n throw new TypeError('This method requires a valid topology instance');\n }\n\n if (!Array.isArray(args)) {\n throw new TypeError('This method requires an array of arguments to apply');\n }\n\n options = options || {};\n const Promise = topology.s.promiseLibrary;\n let callback = args[args.length - 1];\n\n // The driver sessions spec mandates that we implicitly create sessions for operations\n // that are not explicitly provided with a session.\n let session, opOptions, owner;\n if (!options.skipSessions && topology.hasSessionSupport()) {\n opOptions = args[args.length - 2];\n if (opOptions == null || opOptions.session == null) {\n owner = Symbol();\n session = topology.startSession({ owner });\n const optionsIndex = args.length - 2;\n args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session });\n } else if (opOptions.session && opOptions.session.hasEnded) {\n throw new MongoError('Use of expired sessions is not permitted');\n }\n }\n\n const makeExecuteCallback = (resolve, reject) =>\n function executeCallback(err, result) {\n if (session && session.owner === owner && !options.returnsCursor) {\n session.endSession(() => {\n delete opOptions.session;\n if (err) return reject(err);\n resolve(result);\n });\n } else {\n if (err) return reject(err);\n resolve(result);\n }\n };\n\n // Execute using callback\n if (typeof callback === 'function') {\n callback = args.pop();\n const handler = makeExecuteCallback(\n result => callback(null, result),\n err => callback(err, null)\n );\n args.push(handler);\n\n try {\n return operation.apply(null, args);\n } catch (e) {\n handler(e);\n throw e;\n }\n }\n\n // Return a Promise\n if (args[args.length - 1] != null) {\n throw new TypeError('final argument to `executeLegacyOperation` must be a callback');\n }\n\n return new Promise(function(resolve, reject) {\n const handler = makeExecuteCallback(resolve, reject);\n args[args.length - 1] = handler;\n\n try {\n return operation.apply(null, args);\n } catch (e) {\n handler(e);\n }\n });\n};\n\n/**\n * Applies retryWrites: true to a command if retryWrites is set on the command's database.\n *\n * @param {object} target The target command to which we will apply retryWrites.\n * @param {object} db The database from which we can inherit a retryWrites value.\n */\nfunction applyRetryableWrites(target, db) {\n if (db && db.s.options.retryWrites) {\n target.retryWrites = true;\n }\n\n return target;\n}\n\n/**\n * Applies a write concern to a command based on well defined inheritance rules, optionally\n * detecting support for the write concern in the first place.\n *\n * @param {Object} target the target command we will be applying the write concern to\n * @param {Object} sources sources where we can inherit default write concerns from\n * @param {Object} [options] optional settings passed into a command for write concern overrides\n * @returns {Object} the (now) decorated target\n */\nfunction applyWriteConcern(target, sources, options) {\n options = options || {};\n const db = sources.db;\n const coll = sources.collection;\n\n if (options.session && options.session.inTransaction()) {\n // writeConcern is not allowed within a multi-statement transaction\n if (target.writeConcern) {\n delete target.writeConcern;\n }\n\n return target;\n }\n\n const writeConcern = WriteConcern.fromOptions(options);\n if (writeConcern) {\n return Object.assign(target, { writeConcern });\n }\n\n if (coll && coll.writeConcern) {\n return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) });\n }\n\n if (db && db.writeConcern) {\n return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) });\n }\n\n return target;\n}\n\n/**\n * Checks if a given value is a Promise\n *\n * @param {*} maybePromise\n * @return true if the provided value is a Promise\n */\nfunction isPromiseLike(maybePromise) {\n return maybePromise && typeof maybePromise.then === 'function';\n}\n\n/**\n * Applies collation to a given command.\n *\n * @param {object} [command] the command on which to apply collation\n * @param {(Cursor|Collection)} [target] target of command\n * @param {object} [options] options containing collation settings\n */\nfunction decorateWithCollation(command, target, options) {\n const topology = (target.s && target.s.topology) || target.topology;\n\n if (!topology) {\n throw new TypeError('parameter \"target\" is missing a topology');\n }\n\n const capabilities = topology.capabilities();\n if (options.collation && typeof options.collation === 'object') {\n if (capabilities && capabilities.commandsTakeCollation) {\n command.collation = options.collation;\n } else {\n throw new MongoError(`Current topology does not support collation`);\n }\n }\n}\n\n/**\n * Applies a read concern to a given command.\n *\n * @param {object} command the command on which to apply the read concern\n * @param {Collection} coll the parent collection of the operation calling this method\n */\nfunction decorateWithReadConcern(command, coll, options) {\n if (options && options.session && options.session.inTransaction()) {\n return;\n }\n let readConcern = Object.assign({}, command.readConcern || {});\n if (coll.s.readConcern) {\n Object.assign(readConcern, coll.s.readConcern);\n }\n\n if (Object.keys(readConcern).length > 0) {\n Object.assign(command, { readConcern: readConcern });\n }\n}\n\nconst emitProcessWarning = msg => process.emitWarning(msg, 'DeprecationWarning');\nconst emitConsoleWarning = msg => console.error(msg);\nconst emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning;\n\n/**\n * Default message handler for generating deprecation warnings.\n *\n * @param {string} name function name\n * @param {string} option option name\n * @return {string} warning message\n * @ignore\n * @api private\n */\nfunction defaultMsgHandler(name, option) {\n return `${name} option [${option}] is deprecated and will be removed in a later version.`;\n}\n\n/**\n * Deprecates a given function's options.\n *\n * @param {object} config configuration for deprecation\n * @param {string} config.name function name\n * @param {Array} config.deprecatedOptions options to deprecate\n * @param {number} config.optionsIndex index of options object in function arguments array\n * @param {function} [config.msgHandler] optional custom message handler to generate warnings\n * @param {function} fn the target function of deprecation\n * @return {function} modified function that warns once per deprecated option, and executes original function\n * @ignore\n * @api private\n */\nfunction deprecateOptions(config, fn) {\n if (process.noDeprecation === true) {\n return fn;\n }\n\n const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler;\n\n const optionsWarned = new Set();\n function deprecated() {\n const options = arguments[config.optionsIndex];\n\n // ensure options is a valid, non-empty object, otherwise short-circuit\n if (!isObject(options) || Object.keys(options).length === 0) {\n return fn.apply(this, arguments);\n }\n\n config.deprecatedOptions.forEach(deprecatedOption => {\n if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) {\n optionsWarned.add(deprecatedOption);\n const msg = msgHandler(config.name, deprecatedOption);\n emitDeprecationWarning(msg);\n if (this && this.getLogger) {\n const logger = this.getLogger();\n if (logger) {\n logger.warn(msg);\n }\n }\n }\n });\n\n return fn.apply(this, arguments);\n }\n\n // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80\n // The wrapper will keep the same prototype as fn to maintain prototype chain\n Object.setPrototypeOf(deprecated, fn);\n if (fn.prototype) {\n // Setting this (rather than using Object.setPrototype, as above) ensures\n // that calling the unwrapped constructor gives an instanceof the wrapped\n // constructor.\n deprecated.prototype = fn.prototype;\n }\n\n return deprecated;\n}\n\nconst SUPPORTS = {};\n// Test asyncIterator support\ntry {\n require('./async/async_iterator');\n SUPPORTS.ASYNC_ITERATOR = true;\n} catch (e) {\n SUPPORTS.ASYNC_ITERATOR = false;\n}\n\nclass MongoDBNamespace {\n constructor(db, collection) {\n this.db = db;\n this.collection = collection;\n }\n\n toString() {\n return this.collection ? `${this.db}.${this.collection}` : this.db;\n }\n\n withCollection(collection) {\n return new MongoDBNamespace(this.db, collection);\n }\n\n static fromString(namespace) {\n if (!namespace) {\n throw new Error(`Cannot parse namespace from \"${namespace}\"`);\n }\n\n const index = namespace.indexOf('.');\n return new MongoDBNamespace(namespace.substring(0, index), namespace.substring(index + 1));\n }\n}\n\nfunction* makeCounter(seed) {\n let count = seed || 0;\n while (true) {\n const newCount = count;\n count += 1;\n yield newCount;\n }\n}\n\n/**\n * Helper function for either accepting a callback, or returning a promise\n *\n * @param {Object} parent an instance of parent with promiseLibrary.\n * @param {object} parent.s an object containing promiseLibrary.\n * @param {function} parent.s.promiseLibrary an object containing promiseLibrary.\n * @param {[Function]} callback an optional callback.\n * @param {Function} fn A function that takes a callback\n * @returns {Promise|void} Returns nothing if a callback is supplied, else returns a Promise.\n */\nfunction maybePromise(parent, callback, fn) {\n const PromiseLibrary = (parent && parent.s && parent.s.promiseLibrary) || Promise;\n\n let result;\n if (typeof callback !== 'function') {\n result = new PromiseLibrary((resolve, reject) => {\n callback = (err, res) => {\n if (err) return reject(err);\n resolve(res);\n };\n });\n }\n\n fn(function(err, res) {\n if (err != null) {\n try {\n callback(err);\n } catch (error) {\n return process.nextTick(() => {\n throw error;\n });\n }\n return;\n }\n\n callback(err, res);\n });\n\n return result;\n}\n\nfunction now() {\n const hrtime = process.hrtime();\n return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1000000);\n}\n\nfunction calculateDurationInMs(started) {\n if (typeof started !== 'number') {\n throw TypeError('numeric value required to calculate duration');\n }\n\n const elapsed = now() - started;\n return elapsed < 0 ? 0 : elapsed;\n}\n\n/**\n * Creates an interval timer which is able to be woken up sooner than\n * the interval. The timer will also debounce multiple calls to wake\n * ensuring that the function is only ever called once within a minimum\n * interval window.\n *\n * @param {function} fn An async function to run on an interval, must accept a `callback` as its only parameter\n * @param {object} [options] Optional settings\n * @param {number} [options.interval] The interval at which to run the provided function\n * @param {number} [options.minInterval] The minimum time which must pass between invocations of the provided function\n * @param {boolean} [options.immediate] Execute the function immediately when the interval is started\n */\nfunction makeInterruptableAsyncInterval(fn, options) {\n let timerId;\n let lastCallTime;\n let lastWakeTime;\n let stopped = false;\n\n options = options || {};\n const interval = options.interval || 1000;\n const minInterval = options.minInterval || 500;\n const immediate = typeof options.immediate === 'boolean' ? options.immediate : false;\n\n function wake() {\n const currentTime = now();\n const timeSinceLastWake = currentTime - lastWakeTime;\n const timeSinceLastCall = currentTime - lastCallTime;\n const timeUntilNextCall = Math.max(interval - timeSinceLastCall, 0);\n lastWakeTime = currentTime;\n\n // For the streaming protocol: there is nothing obviously stopping this\n // interval from being woken up again while we are waiting \"infinitely\"\n // for `fn` to be called again`. Since the function effectively\n // never completes, the `timeUntilNextCall` will continue to grow\n // negatively unbounded, so it will never trigger a reschedule here.\n\n // debounce multiple calls to wake within the `minInterval`\n if (timeSinceLastWake < minInterval) {\n return;\n }\n\n // reschedule a call as soon as possible, ensuring the call never happens\n // faster than the `minInterval`\n if (timeUntilNextCall > minInterval) {\n reschedule(minInterval);\n }\n }\n\n function stop() {\n stopped = true;\n if (timerId) {\n clearTimeout(timerId);\n timerId = null;\n }\n\n lastCallTime = 0;\n lastWakeTime = 0;\n }\n\n function reschedule(ms) {\n if (stopped) return;\n clearTimeout(timerId);\n timerId = setTimeout(executeAndReschedule, ms || interval);\n }\n\n function executeAndReschedule() {\n lastWakeTime = 0;\n lastCallTime = now();\n\n fn(err => {\n if (err) throw err;\n reschedule(interval);\n });\n }\n\n if (immediate) {\n executeAndReschedule();\n } else {\n lastCallTime = now();\n reschedule();\n }\n\n return { wake, stop };\n}\n\nfunction hasAtomicOperators(doc) {\n if (Array.isArray(doc)) {\n return doc.reduce((err, u) => err || hasAtomicOperators(u), null);\n }\n\n const keys = Object.keys(doc);\n return keys.length > 0 && keys[0][0] === '$';\n}\n\nmodule.exports = {\n filterOptions,\n mergeOptions,\n translateOptions,\n shallowClone,\n getSingleProperty,\n checkCollectionName,\n toError,\n formattedOrderClause,\n parseIndexOptions,\n normalizeHintField,\n handleCallback,\n decorateCommand,\n isObject,\n debugOptions,\n MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1,\n mergeOptionsAndWriteConcern,\n executeLegacyOperation,\n applyRetryableWrites,\n applyWriteConcern,\n isPromiseLike,\n decorateWithCollation,\n decorateWithReadConcern,\n deprecateOptions,\n SUPPORTS,\n MongoDBNamespace,\n emitDeprecationWarning,\n makeCounter,\n maybePromise,\n now,\n calculateDurationInMs,\n makeInterruptableAsyncInterval,\n hasAtomicOperators\n};\n","'use strict';\n\nconst kWriteConcernKeys = new Set(['w', 'wtimeout', 'j', 'fsync']);\n\n/**\n * The **WriteConcern** class is a class that represents a MongoDB WriteConcern.\n * @class\n * @property {(number|string)} w The write concern\n * @property {number} wtimeout The write concern timeout\n * @property {boolean} j The journal write concern\n * @property {boolean} fsync The file sync write concern\n * @see https://docs.mongodb.com/manual/reference/write-concern/index.html\n */\nclass WriteConcern {\n /**\n * Constructs a WriteConcern from the write concern properties.\n * @param {(number|string)} [w] The write concern\n * @param {number} [wtimeout] The write concern timeout\n * @param {boolean} [j] The journal write concern\n * @param {boolean} [fsync] The file sync write concern\n */\n constructor(w, wtimeout, j, fsync) {\n if (w != null) {\n this.w = w;\n }\n if (wtimeout != null) {\n this.wtimeout = wtimeout;\n }\n if (j != null) {\n this.j = j;\n }\n if (fsync != null) {\n this.fsync = fsync;\n }\n }\n\n /**\n * Construct a WriteConcern given an options object.\n *\n * @param {object} options The options object from which to extract the write concern.\n * @return {WriteConcern}\n */\n static fromOptions(options) {\n if (\n options == null ||\n (options.writeConcern == null &&\n options.w == null &&\n options.wtimeout == null &&\n options.j == null &&\n options.fsync == null)\n ) {\n return;\n }\n\n if (options.writeConcern) {\n if (typeof options.writeConcern === 'string') {\n return new WriteConcern(options.writeConcern);\n }\n\n if (!Object.keys(options.writeConcern).some(key => kWriteConcernKeys.has(key))) {\n return;\n }\n\n return new WriteConcern(\n options.writeConcern.w,\n options.writeConcern.wtimeout,\n options.writeConcern.j,\n options.writeConcern.fsync\n );\n }\n\n return new WriteConcern(options.w, options.wtimeout, options.j, options.fsync);\n }\n}\n\nmodule.exports = WriteConcern;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar Stream = _interopDefault(require('stream'));\nvar http = _interopDefault(require('http'));\nvar Url = _interopDefault(require('url'));\nvar https = _interopDefault(require('https'));\nvar zlib = _interopDefault(require('zlib'));\n\n// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js\n\n// fix for \"Readable\" isn't a named export issue\nconst Readable = Stream.Readable;\n\nconst BUFFER = Symbol('buffer');\nconst TYPE = Symbol('type');\n\nclass Blob {\n\tconstructor() {\n\t\tthis[TYPE] = '';\n\n\t\tconst blobParts = arguments[0];\n\t\tconst options = arguments[1];\n\n\t\tconst buffers = [];\n\t\tlet size = 0;\n\n\t\tif (blobParts) {\n\t\t\tconst a = blobParts;\n\t\t\tconst length = Number(a.length);\n\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\tconst element = a[i];\n\t\t\t\tlet buffer;\n\t\t\t\tif (element instanceof Buffer) {\n\t\t\t\t\tbuffer = element;\n\t\t\t\t} else if (ArrayBuffer.isView(element)) {\n\t\t\t\t\tbuffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);\n\t\t\t\t} else if (element instanceof ArrayBuffer) {\n\t\t\t\t\tbuffer = Buffer.from(element);\n\t\t\t\t} else if (element instanceof Blob) {\n\t\t\t\t\tbuffer = element[BUFFER];\n\t\t\t\t} else {\n\t\t\t\t\tbuffer = Buffer.from(typeof element === 'string' ? element : String(element));\n\t\t\t\t}\n\t\t\t\tsize += buffer.length;\n\t\t\t\tbuffers.push(buffer);\n\t\t\t}\n\t\t}\n\n\t\tthis[BUFFER] = Buffer.concat(buffers);\n\n\t\tlet type = options && options.type !== undefined && String(options.type).toLowerCase();\n\t\tif (type && !/[^\\u0020-\\u007E]/.test(type)) {\n\t\t\tthis[TYPE] = type;\n\t\t}\n\t}\n\tget size() {\n\t\treturn this[BUFFER].length;\n\t}\n\tget type() {\n\t\treturn this[TYPE];\n\t}\n\ttext() {\n\t\treturn Promise.resolve(this[BUFFER].toString());\n\t}\n\tarrayBuffer() {\n\t\tconst buf = this[BUFFER];\n\t\tconst ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n\t\treturn Promise.resolve(ab);\n\t}\n\tstream() {\n\t\tconst readable = new Readable();\n\t\treadable._read = function () {};\n\t\treadable.push(this[BUFFER]);\n\t\treadable.push(null);\n\t\treturn readable;\n\t}\n\ttoString() {\n\t\treturn '[object Blob]';\n\t}\n\tslice() {\n\t\tconst size = this.size;\n\n\t\tconst start = arguments[0];\n\t\tconst end = arguments[1];\n\t\tlet relativeStart, relativeEnd;\n\t\tif (start === undefined) {\n\t\t\trelativeStart = 0;\n\t\t} else if (start < 0) {\n\t\t\trelativeStart = Math.max(size + start, 0);\n\t\t} else {\n\t\t\trelativeStart = Math.min(start, size);\n\t\t}\n\t\tif (end === undefined) {\n\t\t\trelativeEnd = size;\n\t\t} else if (end < 0) {\n\t\t\trelativeEnd = Math.max(size + end, 0);\n\t\t} else {\n\t\t\trelativeEnd = Math.min(end, size);\n\t\t}\n\t\tconst span = Math.max(relativeEnd - relativeStart, 0);\n\n\t\tconst buffer = this[BUFFER];\n\t\tconst slicedBuffer = buffer.slice(relativeStart, relativeStart + span);\n\t\tconst blob = new Blob([], { type: arguments[2] });\n\t\tblob[BUFFER] = slicedBuffer;\n\t\treturn blob;\n\t}\n}\n\nObject.defineProperties(Blob.prototype, {\n\tsize: { enumerable: true },\n\ttype: { enumerable: true },\n\tslice: { enumerable: true }\n});\n\nObject.defineProperty(Blob.prototype, Symbol.toStringTag, {\n\tvalue: 'Blob',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\n/**\n * fetch-error.js\n *\n * FetchError interface for operational errors\n */\n\n/**\n * Create FetchError instance\n *\n * @param String message Error message for human\n * @param String type Error type for machine\n * @param String systemError For Node.js system error\n * @return FetchError\n */\nfunction FetchError(message, type, systemError) {\n Error.call(this, message);\n\n this.message = message;\n this.type = type;\n\n // when err.type is `system`, err.code contains system error code\n if (systemError) {\n this.code = this.errno = systemError.code;\n }\n\n // hide custom error implementation details from end-users\n Error.captureStackTrace(this, this.constructor);\n}\n\nFetchError.prototype = Object.create(Error.prototype);\nFetchError.prototype.constructor = FetchError;\nFetchError.prototype.name = 'FetchError';\n\nlet convert;\ntry {\n\tconvert = require('encoding').convert;\n} catch (e) {}\n\nconst INTERNALS = Symbol('Body internals');\n\n// fix an issue where \"PassThrough\" isn't a named export for node <10\nconst PassThrough = Stream.PassThrough;\n\n/**\n * Body mixin\n *\n * Ref: https://fetch.spec.whatwg.org/#body\n *\n * @param Stream body Readable stream\n * @param Object opts Response options\n * @return Void\n */\nfunction Body(body) {\n\tvar _this = this;\n\n\tvar _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n\t _ref$size = _ref.size;\n\n\tlet size = _ref$size === undefined ? 0 : _ref$size;\n\tvar _ref$timeout = _ref.timeout;\n\tlet timeout = _ref$timeout === undefined ? 0 : _ref$timeout;\n\n\tif (body == null) {\n\t\t// body is undefined or null\n\t\tbody = null;\n\t} else if (isURLSearchParams(body)) {\n\t\t// body is a URLSearchParams\n\t\tbody = Buffer.from(body.toString());\n\t} else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {\n\t\t// body is ArrayBuffer\n\t\tbody = Buffer.from(body);\n\t} else if (ArrayBuffer.isView(body)) {\n\t\t// body is ArrayBufferView\n\t\tbody = Buffer.from(body.buffer, body.byteOffset, body.byteLength);\n\t} else if (body instanceof Stream) ; else {\n\t\t// none of the above\n\t\t// coerce to string then buffer\n\t\tbody = Buffer.from(String(body));\n\t}\n\tthis[INTERNALS] = {\n\t\tbody,\n\t\tdisturbed: false,\n\t\terror: null\n\t};\n\tthis.size = size;\n\tthis.timeout = timeout;\n\n\tif (body instanceof Stream) {\n\t\tbody.on('error', function (err) {\n\t\t\tconst error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);\n\t\t\t_this[INTERNALS].error = error;\n\t\t});\n\t}\n}\n\nBody.prototype = {\n\tget body() {\n\t\treturn this[INTERNALS].body;\n\t},\n\n\tget bodyUsed() {\n\t\treturn this[INTERNALS].disturbed;\n\t},\n\n\t/**\n * Decode response as ArrayBuffer\n *\n * @return Promise\n */\n\tarrayBuffer() {\n\t\treturn consumeBody.call(this).then(function (buf) {\n\t\t\treturn buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n\t\t});\n\t},\n\n\t/**\n * Return raw response as Blob\n *\n * @return Promise\n */\n\tblob() {\n\t\tlet ct = this.headers && this.headers.get('content-type') || '';\n\t\treturn consumeBody.call(this).then(function (buf) {\n\t\t\treturn Object.assign(\n\t\t\t// Prevent copying\n\t\t\tnew Blob([], {\n\t\t\t\ttype: ct.toLowerCase()\n\t\t\t}), {\n\t\t\t\t[BUFFER]: buf\n\t\t\t});\n\t\t});\n\t},\n\n\t/**\n * Decode response as json\n *\n * @return Promise\n */\n\tjson() {\n\t\tvar _this2 = this;\n\n\t\treturn consumeBody.call(this).then(function (buffer) {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(buffer.toString());\n\t\t\t} catch (err) {\n\t\t\t\treturn Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));\n\t\t\t}\n\t\t});\n\t},\n\n\t/**\n * Decode response as text\n *\n * @return Promise\n */\n\ttext() {\n\t\treturn consumeBody.call(this).then(function (buffer) {\n\t\t\treturn buffer.toString();\n\t\t});\n\t},\n\n\t/**\n * Decode response as buffer (non-spec api)\n *\n * @return Promise\n */\n\tbuffer() {\n\t\treturn consumeBody.call(this);\n\t},\n\n\t/**\n * Decode response as text, while automatically detecting the encoding and\n * trying to decode to UTF-8 (non-spec api)\n *\n * @return Promise\n */\n\ttextConverted() {\n\t\tvar _this3 = this;\n\n\t\treturn consumeBody.call(this).then(function (buffer) {\n\t\t\treturn convertBody(buffer, _this3.headers);\n\t\t});\n\t}\n};\n\n// In browsers, all properties are enumerable.\nObject.defineProperties(Body.prototype, {\n\tbody: { enumerable: true },\n\tbodyUsed: { enumerable: true },\n\tarrayBuffer: { enumerable: true },\n\tblob: { enumerable: true },\n\tjson: { enumerable: true },\n\ttext: { enumerable: true }\n});\n\nBody.mixIn = function (proto) {\n\tfor (const name of Object.getOwnPropertyNames(Body.prototype)) {\n\t\t// istanbul ignore else: future proof\n\t\tif (!(name in proto)) {\n\t\t\tconst desc = Object.getOwnPropertyDescriptor(Body.prototype, name);\n\t\t\tObject.defineProperty(proto, name, desc);\n\t\t}\n\t}\n};\n\n/**\n * Consume and convert an entire Body to a Buffer.\n *\n * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body\n *\n * @return Promise\n */\nfunction consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}\n\n/**\n * Detect buffer encoding and convert to target encoding\n * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding\n *\n * @param Buffer buffer Incoming buffer\n * @param String encoding Target encoding\n * @return String\n */\nfunction convertBody(buffer, headers) {\n\tif (typeof convert !== 'function') {\n\t\tthrow new Error('The package `encoding` must be installed to use the textConverted() function');\n\t}\n\n\tconst ct = headers.get('content-type');\n\tlet charset = 'utf-8';\n\tlet res, str;\n\n\t// header\n\tif (ct) {\n\t\tres = /charset=([^;]*)/i.exec(ct);\n\t}\n\n\t// no charset in content type, peek at response body for at most 1024 bytes\n\tstr = buffer.slice(0, 1024).toString();\n\n\t// html5\n\tif (!res && str) {\n\t\tres = / 0 && arguments[0] !== undefined ? arguments[0] : undefined;\n\n\t\tthis[MAP] = Object.create(null);\n\n\t\tif (init instanceof Headers) {\n\t\t\tconst rawHeaders = init.raw();\n\t\t\tconst headerNames = Object.keys(rawHeaders);\n\n\t\t\tfor (const headerName of headerNames) {\n\t\t\t\tfor (const value of rawHeaders[headerName]) {\n\t\t\t\t\tthis.append(headerName, value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\t// We don't worry about converting prop to ByteString here as append()\n\t\t// will handle it.\n\t\tif (init == null) ; else if (typeof init === 'object') {\n\t\t\tconst method = init[Symbol.iterator];\n\t\t\tif (method != null) {\n\t\t\t\tif (typeof method !== 'function') {\n\t\t\t\t\tthrow new TypeError('Header pairs must be iterable');\n\t\t\t\t}\n\n\t\t\t\t// sequence>\n\t\t\t\t// Note: per spec we have to first exhaust the lists then process them\n\t\t\t\tconst pairs = [];\n\t\t\t\tfor (const pair of init) {\n\t\t\t\t\tif (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {\n\t\t\t\t\t\tthrow new TypeError('Each header pair must be iterable');\n\t\t\t\t\t}\n\t\t\t\t\tpairs.push(Array.from(pair));\n\t\t\t\t}\n\n\t\t\t\tfor (const pair of pairs) {\n\t\t\t\t\tif (pair.length !== 2) {\n\t\t\t\t\t\tthrow new TypeError('Each header pair must be a name/value tuple');\n\t\t\t\t\t}\n\t\t\t\t\tthis.append(pair[0], pair[1]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// record\n\t\t\t\tfor (const key of Object.keys(init)) {\n\t\t\t\t\tconst value = init[key];\n\t\t\t\t\tthis.append(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new TypeError('Provided initializer must be an object');\n\t\t}\n\t}\n\n\t/**\n * Return combined header value given name\n *\n * @param String name Header name\n * @return Mixed\n */\n\tget(name) {\n\t\tname = `${name}`;\n\t\tvalidateName(name);\n\t\tconst key = find(this[MAP], name);\n\t\tif (key === undefined) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn this[MAP][key].join(', ');\n\t}\n\n\t/**\n * Iterate over all headers\n *\n * @param Function callback Executed for each item with parameters (value, name, thisArg)\n * @param Boolean thisArg `this` context for callback function\n * @return Void\n */\n\tforEach(callback) {\n\t\tlet thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;\n\n\t\tlet pairs = getHeaders(this);\n\t\tlet i = 0;\n\t\twhile (i < pairs.length) {\n\t\t\tvar _pairs$i = pairs[i];\n\t\t\tconst name = _pairs$i[0],\n\t\t\t value = _pairs$i[1];\n\n\t\t\tcallback.call(thisArg, value, name, this);\n\t\t\tpairs = getHeaders(this);\n\t\t\ti++;\n\t\t}\n\t}\n\n\t/**\n * Overwrite header values given name\n *\n * @param String name Header name\n * @param String value Header value\n * @return Void\n */\n\tset(name, value) {\n\t\tname = `${name}`;\n\t\tvalue = `${value}`;\n\t\tvalidateName(name);\n\t\tvalidateValue(value);\n\t\tconst key = find(this[MAP], name);\n\t\tthis[MAP][key !== undefined ? key : name] = [value];\n\t}\n\n\t/**\n * Append a value onto existing header\n *\n * @param String name Header name\n * @param String value Header value\n * @return Void\n */\n\tappend(name, value) {\n\t\tname = `${name}`;\n\t\tvalue = `${value}`;\n\t\tvalidateName(name);\n\t\tvalidateValue(value);\n\t\tconst key = find(this[MAP], name);\n\t\tif (key !== undefined) {\n\t\t\tthis[MAP][key].push(value);\n\t\t} else {\n\t\t\tthis[MAP][name] = [value];\n\t\t}\n\t}\n\n\t/**\n * Check for header name existence\n *\n * @param String name Header name\n * @return Boolean\n */\n\thas(name) {\n\t\tname = `${name}`;\n\t\tvalidateName(name);\n\t\treturn find(this[MAP], name) !== undefined;\n\t}\n\n\t/**\n * Delete all header values given name\n *\n * @param String name Header name\n * @return Void\n */\n\tdelete(name) {\n\t\tname = `${name}`;\n\t\tvalidateName(name);\n\t\tconst key = find(this[MAP], name);\n\t\tif (key !== undefined) {\n\t\t\tdelete this[MAP][key];\n\t\t}\n\t}\n\n\t/**\n * Return raw headers (non-spec api)\n *\n * @return Object\n */\n\traw() {\n\t\treturn this[MAP];\n\t}\n\n\t/**\n * Get an iterator on keys.\n *\n * @return Iterator\n */\n\tkeys() {\n\t\treturn createHeadersIterator(this, 'key');\n\t}\n\n\t/**\n * Get an iterator on values.\n *\n * @return Iterator\n */\n\tvalues() {\n\t\treturn createHeadersIterator(this, 'value');\n\t}\n\n\t/**\n * Get an iterator on entries.\n *\n * This is the default iterator of the Headers object.\n *\n * @return Iterator\n */\n\t[Symbol.iterator]() {\n\t\treturn createHeadersIterator(this, 'key+value');\n\t}\n}\nHeaders.prototype.entries = Headers.prototype[Symbol.iterator];\n\nObject.defineProperty(Headers.prototype, Symbol.toStringTag, {\n\tvalue: 'Headers',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\nObject.defineProperties(Headers.prototype, {\n\tget: { enumerable: true },\n\tforEach: { enumerable: true },\n\tset: { enumerable: true },\n\tappend: { enumerable: true },\n\thas: { enumerable: true },\n\tdelete: { enumerable: true },\n\tkeys: { enumerable: true },\n\tvalues: { enumerable: true },\n\tentries: { enumerable: true }\n});\n\nfunction getHeaders(headers) {\n\tlet kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';\n\n\tconst keys = Object.keys(headers[MAP]).sort();\n\treturn keys.map(kind === 'key' ? function (k) {\n\t\treturn k.toLowerCase();\n\t} : kind === 'value' ? function (k) {\n\t\treturn headers[MAP][k].join(', ');\n\t} : function (k) {\n\t\treturn [k.toLowerCase(), headers[MAP][k].join(', ')];\n\t});\n}\n\nconst INTERNAL = Symbol('internal');\n\nfunction createHeadersIterator(target, kind) {\n\tconst iterator = Object.create(HeadersIteratorPrototype);\n\titerator[INTERNAL] = {\n\t\ttarget,\n\t\tkind,\n\t\tindex: 0\n\t};\n\treturn iterator;\n}\n\nconst HeadersIteratorPrototype = Object.setPrototypeOf({\n\tnext() {\n\t\t// istanbul ignore if\n\t\tif (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {\n\t\t\tthrow new TypeError('Value of `this` is not a HeadersIterator');\n\t\t}\n\n\t\tvar _INTERNAL = this[INTERNAL];\n\t\tconst target = _INTERNAL.target,\n\t\t kind = _INTERNAL.kind,\n\t\t index = _INTERNAL.index;\n\n\t\tconst values = getHeaders(target, kind);\n\t\tconst len = values.length;\n\t\tif (index >= len) {\n\t\t\treturn {\n\t\t\t\tvalue: undefined,\n\t\t\t\tdone: true\n\t\t\t};\n\t\t}\n\n\t\tthis[INTERNAL].index = index + 1;\n\n\t\treturn {\n\t\t\tvalue: values[index],\n\t\t\tdone: false\n\t\t};\n\t}\n}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));\n\nObject.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {\n\tvalue: 'HeadersIterator',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\n/**\n * Export the Headers object in a form that Node.js can consume.\n *\n * @param Headers headers\n * @return Object\n */\nfunction exportNodeCompatibleHeaders(headers) {\n\tconst obj = Object.assign({ __proto__: null }, headers[MAP]);\n\n\t// http.request() only supports string as Host header. This hack makes\n\t// specifying custom Host header possible.\n\tconst hostHeaderKey = find(headers[MAP], 'Host');\n\tif (hostHeaderKey !== undefined) {\n\t\tobj[hostHeaderKey] = obj[hostHeaderKey][0];\n\t}\n\n\treturn obj;\n}\n\n/**\n * Create a Headers object from an object of headers, ignoring those that do\n * not conform to HTTP grammar productions.\n *\n * @param Object obj Object of headers\n * @return Headers\n */\nfunction createHeadersLenient(obj) {\n\tconst headers = new Headers();\n\tfor (const name of Object.keys(obj)) {\n\t\tif (invalidTokenRegex.test(name)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (Array.isArray(obj[name])) {\n\t\t\tfor (const val of obj[name]) {\n\t\t\t\tif (invalidHeaderCharRegex.test(val)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (headers[MAP][name] === undefined) {\n\t\t\t\t\theaders[MAP][name] = [val];\n\t\t\t\t} else {\n\t\t\t\t\theaders[MAP][name].push(val);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (!invalidHeaderCharRegex.test(obj[name])) {\n\t\t\theaders[MAP][name] = [obj[name]];\n\t\t}\n\t}\n\treturn headers;\n}\n\nconst INTERNALS$1 = Symbol('Response internals');\n\n// fix an issue where \"STATUS_CODES\" aren't a named export for node <10\nconst STATUS_CODES = http.STATUS_CODES;\n\n/**\n * Response class\n *\n * @param Stream body Readable stream\n * @param Object opts Response options\n * @return Void\n */\nclass Response {\n\tconstructor() {\n\t\tlet body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n\t\tlet opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n\t\tBody.call(this, body, opts);\n\n\t\tconst status = opts.status || 200;\n\t\tconst headers = new Headers(opts.headers);\n\n\t\tif (body != null && !headers.has('Content-Type')) {\n\t\t\tconst contentType = extractContentType(body);\n\t\t\tif (contentType) {\n\t\t\t\theaders.append('Content-Type', contentType);\n\t\t\t}\n\t\t}\n\n\t\tthis[INTERNALS$1] = {\n\t\t\turl: opts.url,\n\t\t\tstatus,\n\t\t\tstatusText: opts.statusText || STATUS_CODES[status],\n\t\t\theaders,\n\t\t\tcounter: opts.counter\n\t\t};\n\t}\n\n\tget url() {\n\t\treturn this[INTERNALS$1].url || '';\n\t}\n\n\tget status() {\n\t\treturn this[INTERNALS$1].status;\n\t}\n\n\t/**\n * Convenience property representing if the request ended normally\n */\n\tget ok() {\n\t\treturn this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;\n\t}\n\n\tget redirected() {\n\t\treturn this[INTERNALS$1].counter > 0;\n\t}\n\n\tget statusText() {\n\t\treturn this[INTERNALS$1].statusText;\n\t}\n\n\tget headers() {\n\t\treturn this[INTERNALS$1].headers;\n\t}\n\n\t/**\n * Clone this response\n *\n * @return Response\n */\n\tclone() {\n\t\treturn new Response(clone(this), {\n\t\t\turl: this.url,\n\t\t\tstatus: this.status,\n\t\t\tstatusText: this.statusText,\n\t\t\theaders: this.headers,\n\t\t\tok: this.ok,\n\t\t\tredirected: this.redirected\n\t\t});\n\t}\n}\n\nBody.mixIn(Response.prototype);\n\nObject.defineProperties(Response.prototype, {\n\turl: { enumerable: true },\n\tstatus: { enumerable: true },\n\tok: { enumerable: true },\n\tredirected: { enumerable: true },\n\tstatusText: { enumerable: true },\n\theaders: { enumerable: true },\n\tclone: { enumerable: true }\n});\n\nObject.defineProperty(Response.prototype, Symbol.toStringTag, {\n\tvalue: 'Response',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\nconst INTERNALS$2 = Symbol('Request internals');\n\n// fix an issue where \"format\", \"parse\" aren't a named export for node <10\nconst parse_url = Url.parse;\nconst format_url = Url.format;\n\nconst streamDestructionSupported = 'destroy' in Stream.Readable.prototype;\n\n/**\n * Check if a value is an instance of Request.\n *\n * @param Mixed input\n * @return Boolean\n */\nfunction isRequest(input) {\n\treturn typeof input === 'object' && typeof input[INTERNALS$2] === 'object';\n}\n\nfunction isAbortSignal(signal) {\n\tconst proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);\n\treturn !!(proto && proto.constructor.name === 'AbortSignal');\n}\n\n/**\n * Request class\n *\n * @param Mixed input Url or Request instance\n * @param Object init Custom options\n * @return Void\n */\nclass Request {\n\tconstructor(input) {\n\t\tlet init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n\t\tlet parsedURL;\n\n\t\t// normalize input\n\t\tif (!isRequest(input)) {\n\t\t\tif (input && input.href) {\n\t\t\t\t// in order to support Node.js' Url objects; though WHATWG's URL objects\n\t\t\t\t// will fall into this branch also (since their `toString()` will return\n\t\t\t\t// `href` property anyway)\n\t\t\t\tparsedURL = parse_url(input.href);\n\t\t\t} else {\n\t\t\t\t// coerce input to a string before attempting to parse\n\t\t\t\tparsedURL = parse_url(`${input}`);\n\t\t\t}\n\t\t\tinput = {};\n\t\t} else {\n\t\t\tparsedURL = parse_url(input.url);\n\t\t}\n\n\t\tlet method = init.method || input.method || 'GET';\n\t\tmethod = method.toUpperCase();\n\n\t\tif ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {\n\t\t\tthrow new TypeError('Request with GET/HEAD method cannot have body');\n\t\t}\n\n\t\tlet inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;\n\n\t\tBody.call(this, inputBody, {\n\t\t\ttimeout: init.timeout || input.timeout || 0,\n\t\t\tsize: init.size || input.size || 0\n\t\t});\n\n\t\tconst headers = new Headers(init.headers || input.headers || {});\n\n\t\tif (inputBody != null && !headers.has('Content-Type')) {\n\t\t\tconst contentType = extractContentType(inputBody);\n\t\t\tif (contentType) {\n\t\t\t\theaders.append('Content-Type', contentType);\n\t\t\t}\n\t\t}\n\n\t\tlet signal = isRequest(input) ? input.signal : null;\n\t\tif ('signal' in init) signal = init.signal;\n\n\t\tif (signal != null && !isAbortSignal(signal)) {\n\t\t\tthrow new TypeError('Expected signal to be an instanceof AbortSignal');\n\t\t}\n\n\t\tthis[INTERNALS$2] = {\n\t\t\tmethod,\n\t\t\tredirect: init.redirect || input.redirect || 'follow',\n\t\t\theaders,\n\t\t\tparsedURL,\n\t\t\tsignal\n\t\t};\n\n\t\t// node-fetch-only options\n\t\tthis.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;\n\t\tthis.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;\n\t\tthis.counter = init.counter || input.counter || 0;\n\t\tthis.agent = init.agent || input.agent;\n\t}\n\n\tget method() {\n\t\treturn this[INTERNALS$2].method;\n\t}\n\n\tget url() {\n\t\treturn format_url(this[INTERNALS$2].parsedURL);\n\t}\n\n\tget headers() {\n\t\treturn this[INTERNALS$2].headers;\n\t}\n\n\tget redirect() {\n\t\treturn this[INTERNALS$2].redirect;\n\t}\n\n\tget signal() {\n\t\treturn this[INTERNALS$2].signal;\n\t}\n\n\t/**\n * Clone this request\n *\n * @return Request\n */\n\tclone() {\n\t\treturn new Request(this);\n\t}\n}\n\nBody.mixIn(Request.prototype);\n\nObject.defineProperty(Request.prototype, Symbol.toStringTag, {\n\tvalue: 'Request',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\nObject.defineProperties(Request.prototype, {\n\tmethod: { enumerable: true },\n\turl: { enumerable: true },\n\theaders: { enumerable: true },\n\tredirect: { enumerable: true },\n\tclone: { enumerable: true },\n\tsignal: { enumerable: true }\n});\n\n/**\n * Convert a Request to Node.js http request options.\n *\n * @param Request A Request instance\n * @return Object The options object to be passed to http.request\n */\nfunction getNodeRequestOptions(request) {\n\tconst parsedURL = request[INTERNALS$2].parsedURL;\n\tconst headers = new Headers(request[INTERNALS$2].headers);\n\n\t// fetch step 1.3\n\tif (!headers.has('Accept')) {\n\t\theaders.set('Accept', '*/*');\n\t}\n\n\t// Basic fetch\n\tif (!parsedURL.protocol || !parsedURL.hostname) {\n\t\tthrow new TypeError('Only absolute URLs are supported');\n\t}\n\n\tif (!/^https?:$/.test(parsedURL.protocol)) {\n\t\tthrow new TypeError('Only HTTP(S) protocols are supported');\n\t}\n\n\tif (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {\n\t\tthrow new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');\n\t}\n\n\t// HTTP-network-or-cache fetch steps 2.4-2.7\n\tlet contentLengthValue = null;\n\tif (request.body == null && /^(POST|PUT)$/i.test(request.method)) {\n\t\tcontentLengthValue = '0';\n\t}\n\tif (request.body != null) {\n\t\tconst totalBytes = getTotalBytes(request);\n\t\tif (typeof totalBytes === 'number') {\n\t\t\tcontentLengthValue = String(totalBytes);\n\t\t}\n\t}\n\tif (contentLengthValue) {\n\t\theaders.set('Content-Length', contentLengthValue);\n\t}\n\n\t// HTTP-network-or-cache fetch step 2.11\n\tif (!headers.has('User-Agent')) {\n\t\theaders.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');\n\t}\n\n\t// HTTP-network-or-cache fetch step 2.15\n\tif (request.compress && !headers.has('Accept-Encoding')) {\n\t\theaders.set('Accept-Encoding', 'gzip,deflate');\n\t}\n\n\tlet agent = request.agent;\n\tif (typeof agent === 'function') {\n\t\tagent = agent(parsedURL);\n\t}\n\n\tif (!headers.has('Connection') && !agent) {\n\t\theaders.set('Connection', 'close');\n\t}\n\n\t// HTTP-network fetch step 4.2\n\t// chunked encoding is handled by Node.js\n\n\treturn Object.assign({}, parsedURL, {\n\t\tmethod: request.method,\n\t\theaders: exportNodeCompatibleHeaders(headers),\n\t\tagent\n\t});\n}\n\n/**\n * abort-error.js\n *\n * AbortError interface for cancelled requests\n */\n\n/**\n * Create AbortError instance\n *\n * @param String message Error message for human\n * @return AbortError\n */\nfunction AbortError(message) {\n Error.call(this, message);\n\n this.type = 'aborted';\n this.message = message;\n\n // hide custom error implementation details from end-users\n Error.captureStackTrace(this, this.constructor);\n}\n\nAbortError.prototype = Object.create(Error.prototype);\nAbortError.prototype.constructor = AbortError;\nAbortError.prototype.name = 'AbortError';\n\n// fix an issue where \"PassThrough\", \"resolve\" aren't a named export for node <10\nconst PassThrough$1 = Stream.PassThrough;\nconst resolve_url = Url.resolve;\n\n/**\n * Fetch function\n *\n * @param Mixed url Absolute url or Request instance\n * @param Object opts Fetch options\n * @return Promise\n */\nfunction fetch(url, opts) {\n\n\t// allow custom promise\n\tif (!fetch.Promise) {\n\t\tthrow new Error('native promise missing, set fetch.Promise to your favorite alternative');\n\t}\n\n\tBody.Promise = fetch.Promise;\n\n\t// wrap http.request into fetch\n\treturn new fetch.Promise(function (resolve, reject) {\n\t\t// build request object\n\t\tconst request = new Request(url, opts);\n\t\tconst options = getNodeRequestOptions(request);\n\n\t\tconst send = (options.protocol === 'https:' ? https : http).request;\n\t\tconst signal = request.signal;\n\n\t\tlet response = null;\n\n\t\tconst abort = function abort() {\n\t\t\tlet error = new AbortError('The user aborted a request.');\n\t\t\treject(error);\n\t\t\tif (request.body && request.body instanceof Stream.Readable) {\n\t\t\t\trequest.body.destroy(error);\n\t\t\t}\n\t\t\tif (!response || !response.body) return;\n\t\t\tresponse.body.emit('error', error);\n\t\t};\n\n\t\tif (signal && signal.aborted) {\n\t\t\tabort();\n\t\t\treturn;\n\t\t}\n\n\t\tconst abortAndFinalize = function abortAndFinalize() {\n\t\t\tabort();\n\t\t\tfinalize();\n\t\t};\n\n\t\t// send request\n\t\tconst req = send(options);\n\t\tlet reqTimeout;\n\n\t\tif (signal) {\n\t\t\tsignal.addEventListener('abort', abortAndFinalize);\n\t\t}\n\n\t\tfunction finalize() {\n\t\t\treq.abort();\n\t\t\tif (signal) signal.removeEventListener('abort', abortAndFinalize);\n\t\t\tclearTimeout(reqTimeout);\n\t\t}\n\n\t\tif (request.timeout) {\n\t\t\treq.once('socket', function (socket) {\n\t\t\t\treqTimeout = setTimeout(function () {\n\t\t\t\t\treject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));\n\t\t\t\t\tfinalize();\n\t\t\t\t}, request.timeout);\n\t\t\t});\n\t\t}\n\n\t\treq.on('error', function (err) {\n\t\t\treject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));\n\t\t\tfinalize();\n\t\t});\n\n\t\treq.on('response', function (res) {\n\t\t\tclearTimeout(reqTimeout);\n\n\t\t\tconst headers = createHeadersLenient(res.headers);\n\n\t\t\t// HTTP fetch step 5\n\t\t\tif (fetch.isRedirect(res.statusCode)) {\n\t\t\t\t// HTTP fetch step 5.2\n\t\t\t\tconst location = headers.get('Location');\n\n\t\t\t\t// HTTP fetch step 5.3\n\t\t\t\tconst locationURL = location === null ? null : resolve_url(request.url, location);\n\n\t\t\t\t// HTTP fetch step 5.5\n\t\t\t\tswitch (request.redirect) {\n\t\t\t\t\tcase 'error':\n\t\t\t\t\t\treject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\tcase 'manual':\n\t\t\t\t\t\t// node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.\n\t\t\t\t\t\tif (locationURL !== null) {\n\t\t\t\t\t\t\t// handle corrupted header\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\theaders.set('Location', locationURL);\n\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t// istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request\n\t\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'follow':\n\t\t\t\t\t\t// HTTP-redirect fetch step 2\n\t\t\t\t\t\tif (locationURL === null) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 5\n\t\t\t\t\t\tif (request.counter >= request.follow) {\n\t\t\t\t\t\t\treject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));\n\t\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 6 (counter increment)\n\t\t\t\t\t\t// Create a new Request object.\n\t\t\t\t\t\tconst requestOpts = {\n\t\t\t\t\t\t\theaders: new Headers(request.headers),\n\t\t\t\t\t\t\tfollow: request.follow,\n\t\t\t\t\t\t\tcounter: request.counter + 1,\n\t\t\t\t\t\t\tagent: request.agent,\n\t\t\t\t\t\t\tcompress: request.compress,\n\t\t\t\t\t\t\tmethod: request.method,\n\t\t\t\t\t\t\tbody: request.body,\n\t\t\t\t\t\t\tsignal: request.signal,\n\t\t\t\t\t\t\ttimeout: request.timeout,\n\t\t\t\t\t\t\tsize: request.size\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 9\n\t\t\t\t\t\tif (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {\n\t\t\t\t\t\t\treject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));\n\t\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 11\n\t\t\t\t\t\tif (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {\n\t\t\t\t\t\t\trequestOpts.method = 'GET';\n\t\t\t\t\t\t\trequestOpts.body = undefined;\n\t\t\t\t\t\t\trequestOpts.headers.delete('content-length');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 15\n\t\t\t\t\t\tresolve(fetch(new Request(locationURL, requestOpts)));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// prepare response\n\t\t\tres.once('end', function () {\n\t\t\t\tif (signal) signal.removeEventListener('abort', abortAndFinalize);\n\t\t\t});\n\t\t\tlet body = res.pipe(new PassThrough$1());\n\n\t\t\tconst response_options = {\n\t\t\t\turl: request.url,\n\t\t\t\tstatus: res.statusCode,\n\t\t\t\tstatusText: res.statusMessage,\n\t\t\t\theaders: headers,\n\t\t\t\tsize: request.size,\n\t\t\t\ttimeout: request.timeout,\n\t\t\t\tcounter: request.counter\n\t\t\t};\n\n\t\t\t// HTTP-network fetch step 12.1.1.3\n\t\t\tconst codings = headers.get('Content-Encoding');\n\n\t\t\t// HTTP-network fetch step 12.1.1.4: handle content codings\n\n\t\t\t// in following scenarios we ignore compression support\n\t\t\t// 1. compression support is disabled\n\t\t\t// 2. HEAD request\n\t\t\t// 3. no Content-Encoding header\n\t\t\t// 4. no content response (204)\n\t\t\t// 5. content not modified response (304)\n\t\t\tif (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {\n\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// For Node v6+\n\t\t\t// Be less strict when decoding compressed responses, since sometimes\n\t\t\t// servers send slightly invalid responses that are still accepted\n\t\t\t// by common browsers.\n\t\t\t// Always using Z_SYNC_FLUSH is what cURL does.\n\t\t\tconst zlibOptions = {\n\t\t\t\tflush: zlib.Z_SYNC_FLUSH,\n\t\t\t\tfinishFlush: zlib.Z_SYNC_FLUSH\n\t\t\t};\n\n\t\t\t// for gzip\n\t\t\tif (codings == 'gzip' || codings == 'x-gzip') {\n\t\t\t\tbody = body.pipe(zlib.createGunzip(zlibOptions));\n\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// for deflate\n\t\t\tif (codings == 'deflate' || codings == 'x-deflate') {\n\t\t\t\t// handle the infamous raw deflate response from old servers\n\t\t\t\t// a hack for old IIS and Apache servers\n\t\t\t\tconst raw = res.pipe(new PassThrough$1());\n\t\t\t\traw.once('data', function (chunk) {\n\t\t\t\t\t// see http://stackoverflow.com/questions/37519828\n\t\t\t\t\tif ((chunk[0] & 0x0F) === 0x08) {\n\t\t\t\t\t\tbody = body.pipe(zlib.createInflate());\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbody = body.pipe(zlib.createInflateRaw());\n\t\t\t\t\t}\n\t\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\t\tresolve(response);\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// for br\n\t\t\tif (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {\n\t\t\t\tbody = body.pipe(zlib.createBrotliDecompress());\n\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// otherwise, use response as-is\n\t\t\tresponse = new Response(body, response_options);\n\t\t\tresolve(response);\n\t\t});\n\n\t\twriteToStream(req, request);\n\t});\n}\n/**\n * Redirect code matching\n *\n * @param Number code Status code\n * @return Boolean\n */\nfetch.isRedirect = function (code) {\n\treturn code === 301 || code === 302 || code === 303 || code === 307 || code === 308;\n};\n\n// expose Promise\nfetch.Promise = global.Promise;\n\nmodule.exports = exports = fetch;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = exports;\nexports.Headers = Headers;\nexports.Request = Request;\nexports.Response = Response;\nexports.FetchError = FetchError;\n","var wrappy = require('wrappy')\nmodule.exports = wrappy(once)\nmodule.exports.strict = wrappy(onceStrict)\n\nonce.proto = once(function () {\n Object.defineProperty(Function.prototype, 'once', {\n value: function () {\n return once(this)\n },\n configurable: true\n })\n\n Object.defineProperty(Function.prototype, 'onceStrict', {\n value: function () {\n return onceStrict(this)\n },\n configurable: true\n })\n})\n\nfunction once (fn) {\n var f = function () {\n if (f.called) return f.value\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n f.called = false\n return f\n}\n\nfunction onceStrict (fn) {\n var f = function () {\n if (f.called)\n throw new Error(f.onceError)\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n var name = fn.name || 'Function wrapped with `once`'\n f.onceError = name + \" shouldn't be called more than once\"\n f.called = false\n return f\n}\n","'use strict';\nconst pTry = require('p-try');\n\nconst pLimit = concurrency => {\n\tif (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {\n\t\treturn Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up'));\n\t}\n\n\tconst queue = [];\n\tlet activeCount = 0;\n\n\tconst next = () => {\n\t\tactiveCount--;\n\n\t\tif (queue.length > 0) {\n\t\t\tqueue.shift()();\n\t\t}\n\t};\n\n\tconst run = (fn, resolve, ...args) => {\n\t\tactiveCount++;\n\n\t\tconst result = pTry(fn, ...args);\n\n\t\tresolve(result);\n\n\t\tresult.then(next, next);\n\t};\n\n\tconst enqueue = (fn, resolve, ...args) => {\n\t\tif (activeCount < concurrency) {\n\t\t\trun(fn, resolve, ...args);\n\t\t} else {\n\t\t\tqueue.push(run.bind(null, fn, resolve, ...args));\n\t\t}\n\t};\n\n\tconst generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.length\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue: () => {\n\t\t\t\tqueue.length = 0;\n\t\t\t}\n\t\t}\n\t});\n\n\treturn generator;\n};\n\nmodule.exports = pLimit;\nmodule.exports.default = pLimit;\n","'use strict';\n\nconst pTry = (fn, ...arguments_) => new Promise(resolve => {\n\tresolve(fn(...arguments_));\n});\n\nmodule.exports = pTry;\n// TODO: remove this in the next major version\nmodule.exports.default = pTry;\n","'use strict'\n\nconst chalk = require('chalk')\nconst jmespath = require('jmespath')\nconst colors = require('./lib/colors')\nconst { ERROR_LIKE_KEYS, MESSAGE_KEY, TIMESTAMP_KEY } = require('./lib/constants')\nconst {\n isObject,\n prettifyErrorLog,\n prettifyLevel,\n prettifyMessage,\n prettifyMetadata,\n prettifyObject,\n prettifyTime\n} = require('./lib/utils')\n\nconst bourne = require('@hapi/bourne')\nconst jsonParser = input => {\n try {\n return { value: bourne.parse(input, { protoAction: 'remove' }) }\n } catch (err) {\n return { err }\n }\n}\n\nconst defaultOptions = {\n colorize: chalk.supportsColor,\n crlf: false,\n errorLikeObjectKeys: ERROR_LIKE_KEYS,\n errorProps: '',\n levelFirst: false,\n messageKey: MESSAGE_KEY,\n messageFormat: false,\n timestampKey: TIMESTAMP_KEY,\n translateTime: false,\n useMetadata: false,\n outputStream: process.stdout,\n customPrettifiers: {}\n}\n\nmodule.exports = function prettyFactory (options) {\n const opts = Object.assign({}, defaultOptions, options)\n const EOL = opts.crlf ? '\\r\\n' : '\\n'\n const IDENT = ' '\n const messageKey = opts.messageKey\n const levelKey = opts.levelKey\n const messageFormat = opts.messageFormat\n const timestampKey = opts.timestampKey\n const errorLikeObjectKeys = opts.errorLikeObjectKeys\n const errorProps = opts.errorProps.split(',')\n const customPrettifiers = opts.customPrettifiers\n const ignoreKeys = opts.ignore ? new Set(opts.ignore.split(',')) : undefined\n\n const colorizer = colors(opts.colorize)\n const search = opts.search\n\n return pretty\n\n function pretty (inputData) {\n let log\n if (!isObject(inputData)) {\n const parsed = jsonParser(inputData)\n if (parsed.err || !isObject(parsed.value)) {\n // pass through\n return inputData + EOL\n }\n log = parsed.value\n } else {\n log = inputData\n }\n\n // Short-circuit for spec allowed primitive values.\n if ([null, true, false].includes(log) || Number.isFinite(log)) {\n return `${log}\\n`\n }\n\n if (search && !jmespath.search(log, search)) {\n return\n }\n\n const prettifiedMessage = prettifyMessage({ log, messageKey, colorizer, messageFormat })\n\n if (ignoreKeys) {\n log = Object.keys(log)\n .filter(key => !ignoreKeys.has(key))\n .reduce((res, key) => {\n res[key] = log[key]\n return res\n }, {})\n }\n\n const prettifiedLevel = prettifyLevel({ log, colorizer, levelKey })\n const prettifiedMetadata = prettifyMetadata({ log })\n const prettifiedTime = prettifyTime({ log, translateFormat: opts.translateTime, timestampKey })\n\n let line = ''\n if (opts.levelFirst && prettifiedLevel) {\n line = `${prettifiedLevel}`\n }\n\n if (prettifiedTime && line === '') {\n line = `${prettifiedTime}`\n } else if (prettifiedTime) {\n line = `${line} ${prettifiedTime}`\n }\n\n if (!opts.levelFirst && prettifiedLevel) {\n if (line.length > 0) {\n line = `${line} ${prettifiedLevel}`\n } else {\n line = prettifiedLevel\n }\n }\n\n if (prettifiedMetadata) {\n line = `${line} ${prettifiedMetadata}:`\n }\n\n if (line.endsWith(':') === false && line !== '') {\n line += ':'\n }\n\n if (prettifiedMessage) {\n line = `${line} ${prettifiedMessage}`\n }\n\n if (line.length > 0) {\n line += EOL\n }\n\n if (log.type === 'Error' && log.stack) {\n const prettifiedErrorLog = prettifyErrorLog({\n log,\n errorLikeKeys: errorLikeObjectKeys,\n errorProperties: errorProps,\n ident: IDENT,\n eol: EOL\n })\n line += prettifiedErrorLog\n } else {\n const skipKeys = [messageKey, levelKey].filter(key => typeof log[key] === 'string')\n const prettifiedObject = prettifyObject({\n input: log,\n skipKeys,\n customPrettifiers,\n errorLikeKeys: errorLikeObjectKeys,\n eol: EOL,\n ident: IDENT\n })\n line += prettifiedObject\n }\n\n return line\n }\n}\n","'use strict'\n\nconst { LEVELS, LEVEL_NAMES } = require('./constants')\n\nconst nocolor = input => input\nconst plain = {\n default: nocolor,\n 60: nocolor,\n 50: nocolor,\n 40: nocolor,\n 30: nocolor,\n 20: nocolor,\n 10: nocolor,\n message: nocolor\n}\n\nconst chalk = require('chalk')\nconst ctx = new chalk.constructor({ enabled: true, level: 3 })\nconst colored = {\n default: ctx.white,\n 60: ctx.bgRed,\n 50: ctx.red,\n 40: ctx.yellow,\n 30: ctx.green,\n 20: ctx.blue,\n 10: ctx.grey,\n message: ctx.cyan\n}\n\nfunction colorizeLevel (level, colorizer) {\n if (Number.isInteger(+level)) {\n return Object.prototype.hasOwnProperty.call(LEVELS, level)\n ? colorizer[level](LEVELS[level])\n : colorizer.default(LEVELS.default)\n }\n const levelNum = LEVEL_NAMES[level.toLowerCase()] || 'default'\n return colorizer[levelNum](LEVELS[levelNum])\n}\n\nfunction plainColorizer (level) {\n return colorizeLevel(level, plain)\n}\nplainColorizer.message = plain.message\n\nfunction coloredColorizer (level) {\n return colorizeLevel(level, colored)\n}\ncoloredColorizer.message = colored.message\n\n/**\n * Factory function get a function to colorized levels. The returned function\n * also includes a `.message(str)` method to colorize strings.\n *\n * @param {bool} [useColors=false] When `true` a function that applies standard\n * terminal colors is returned.\n *\n * @returns {function} `function (level) {}` has a `.message(str)` method to\n * apply colorization to a string. The core function accepts either an integer\n * `level` or a `string` level. The integer level will map to a known level\n * string or to `USERLVL` if not known. The string `level` will map to the same\n * colors as the integer `level` and will also default to `USERLVL` if the given\n * string is not a recognized level name.\n */\nmodule.exports = function getColorizer (useColors = false) {\n return useColors ? coloredColorizer : plainColorizer\n}\n","'use strict'\n\nmodule.exports = {\n DATE_FORMAT: 'yyyy-mm-dd HH:MM:ss.l o',\n\n ERROR_LIKE_KEYS: ['err', 'error'],\n\n MESSAGE_KEY: 'msg',\n\n LEVEL_KEY: 'level',\n\n TIMESTAMP_KEY: 'time',\n\n LEVELS: {\n default: 'USERLVL',\n 60: 'FATAL',\n 50: 'ERROR',\n 40: 'WARN ',\n 30: 'INFO ',\n 20: 'DEBUG',\n 10: 'TRACE'\n },\n\n LEVEL_NAMES: {\n fatal: 60,\n error: 50,\n warn: 40,\n info: 30,\n debug: 20,\n trace: 10\n },\n\n // Object keys that probably came from a logger like Pino or Bunyan.\n LOGGER_KEYS: [\n 'pid',\n 'hostname',\n 'name',\n 'level',\n 'time',\n 'timestamp',\n 'v',\n 'caller'\n ]\n}\n","'use strict'\n\nconst dateformat = require('dateformat')\nconst stringifySafe = require('fast-safe-stringify')\nconst defaultColorizer = require('./colors')()\nconst {\n DATE_FORMAT,\n ERROR_LIKE_KEYS,\n MESSAGE_KEY,\n LEVEL_KEY,\n TIMESTAMP_KEY,\n LOGGER_KEYS\n} = require('./constants')\n\nmodule.exports = {\n isObject,\n prettifyErrorLog,\n prettifyLevel,\n prettifyMessage,\n prettifyMetadata,\n prettifyObject,\n prettifyTime\n}\n\nmodule.exports.internals = {\n formatTime,\n joinLinesWithIndentation\n}\n\n/**\n * Converts a given `epoch` to a desired display format.\n *\n * @param {number|string} epoch The time to convert. May be any value that is\n * valid for `new Date()`.\n * @param {bool|string} [translateTime=false] When `false`, the given `epoch`\n * will simply be returned. When `true`, the given `epoch` will be converted\n * to a string at UTC using the `DATE_FORMAT` constant. If `translateTime` is\n * a string, the following rules are available:\n *\n * - ``: The string is a literal format string. This format\n * string will be used to interpret the `epoch` and return a display string\n * at UTC.\n * - `SYS:STANDARD`: The returned display string will follow the `DATE_FORMAT`\n * constant at the system's local timezone.\n * - `SYS:`: The returned display string will follow the given\n * `` at the system's local timezone.\n * - `UTC:`: The returned display string will follow the given\n * `` at UTC.\n *\n * @returns {number|string} The formatted time.\n */\nfunction formatTime (epoch, translateTime = false) {\n if (translateTime === false) {\n return epoch\n }\n\n const instant = new Date(epoch)\n if (translateTime === true) {\n return dateformat(instant, 'UTC:' + DATE_FORMAT)\n }\n\n const upperFormat = translateTime.toUpperCase()\n if (upperFormat === 'SYS:STANDARD') {\n return dateformat(instant, DATE_FORMAT)\n }\n\n const prefix = upperFormat.substr(0, 4)\n if (prefix === 'SYS:' || prefix === 'UTC:') {\n if (prefix === 'UTC:') {\n return dateformat(instant, translateTime)\n }\n return dateformat(instant, translateTime.slice(4))\n }\n\n return dateformat(instant, `UTC:${translateTime}`)\n}\n\nfunction isObject (input) {\n return Object.prototype.toString.apply(input) === '[object Object]'\n}\n\n/**\n * Given a string with line separators, either `\\r\\n` or `\\n`, add indentation\n * to all lines subsequent to the first line and rejoin the lines using an\n * end of line sequence.\n *\n * @param {object} input\n * @param {string} input.input The string to split and reformat.\n * @param {string} [input.ident] The indentation string. Default: ` ` (4 spaces).\n * @param {string} [input.eol] The end of line sequence to use when rejoining\n * the lines. Default: `'\\n'`.\n *\n * @returns {string} A string with lines subsequent to the first indented\n * with the given indentation sequence.\n */\nfunction joinLinesWithIndentation ({ input, ident = ' ', eol = '\\n' }) {\n const lines = input.split(/\\r?\\n/)\n for (var i = 1; i < lines.length; i += 1) {\n lines[i] = ident + lines[i]\n }\n return lines.join(eol)\n}\n\n/**\n * Given a log object that has a `type: 'Error'` key, prettify the object and\n * return the result. In other\n *\n * @param {object} input\n * @param {object} input.log The error log to prettify.\n * @param {string} [input.messageKey] The name of the key that contains a\n * general log message. This is not the error's message property but the logger\n * messsage property. Default: `MESSAGE_KEY` constant.\n * @param {string} [input.ident] The sequence to use for indentation. Default: `' '`.\n * @param {string} [input.eol] The sequence to use for EOL. Default: `'\\n'`.\n * @param {string[]} [input.errorLikeKeys] A set of keys that should be considered\n * to have error objects as values. Default: `ERROR_LIKE_KEYS` constant.\n * @param {string[]} [input.errorProperties] A set of specific error object\n * properties, that are not the value of `messageKey`, `type`, or `stack`, to\n * include in the prettified result. The first entry in the list may be `'*'`\n * to indicate that all sibiling properties should be prettified. Default: `[]`.\n *\n * @returns {string} A sring that represents the prettified error log.\n */\nfunction prettifyErrorLog ({\n log,\n messageKey = MESSAGE_KEY,\n ident = ' ',\n eol = '\\n',\n errorLikeKeys = ERROR_LIKE_KEYS,\n errorProperties = []\n}) {\n const stack = log.stack\n const joinedLines = joinLinesWithIndentation({ input: stack, ident, eol })\n let result = `${ident}${joinedLines}${eol}`\n\n if (errorProperties.length > 0) {\n const excludeProperties = LOGGER_KEYS.concat(messageKey, 'type', 'stack')\n let propertiesToPrint\n if (errorProperties[0] === '*') {\n // Print all sibling properties except for the standard exclusions.\n propertiesToPrint = Object.keys(log).filter(k => excludeProperties.includes(k) === false)\n } else {\n // Print only sepcified properties unless the property is a standard exclusion.\n propertiesToPrint = errorProperties.filter(k => excludeProperties.includes(k) === false)\n }\n\n for (var i = 0; i < propertiesToPrint.length; i += 1) {\n const key = propertiesToPrint[i]\n if (key in log === false) continue\n if (isObject(log[key])) {\n // The nested object may have \"logger\" type keys but since they are not\n // at the root level of the object being processed, we want to print them.\n // Thus, we invoke with `excludeLoggerKeys: false`.\n const prettifiedObject = prettifyObject({ input: log[key], errorLikeKeys, excludeLoggerKeys: false, eol, ident })\n result = `${result}${key}: {${eol}${prettifiedObject}}${eol}`\n continue\n }\n result = `${result}${key}: ${log[key]}${eol}`\n }\n }\n\n return result\n}\n\n/**\n * Checks if the passed in log has a `level` value and returns a prettified\n * string for that level if so.\n *\n * @param {object} input\n * @param {object} input.log The log object.\n * @param {function} [input.colorizer] A colorizer function that accepts a level\n * value and returns a colorized string. Default: a no-op colorizer.\n * @param {string} [levelKey='level'] The key to find the level under.\n *\n * @returns {undefined|string} If `log` does not have a `level` property then\n * `undefined` will be returned. Otherwise, a string from the specified\n * `colorizer` is returned.\n */\nfunction prettifyLevel ({ log, colorizer = defaultColorizer, levelKey = LEVEL_KEY }) {\n if (levelKey in log === false) return undefined\n return colorizer(log[levelKey])\n}\n\n/**\n * Prettifies a message string if the given `log` has a message property.\n *\n * @param {object} input\n * @param {object} input.log The log object with the message to colorize.\n * @param {string} [input.messageKey='msg'] The property of the `log` that is the\n * message to be prettified.\n * @param {string} [input.messageFormat=undefined] A format string that defines how the\n * logged message should be formatted, e.g. `'{level} - {pid}'`.\n * @param {function} [input.colorizer] A colorizer function that has a\n * `.message(str)` method attached to it. This function should return a colorized\n * string which will be the \"prettified\" message. Default: a no-op colorizer.\n *\n * @returns {undefined|string} If the message key is not found, or the message\n * key is not a string, then `undefined` will be returned. Otherwise, a string\n * that is the prettified message.\n */\nfunction prettifyMessage ({ log, messageFormat, messageKey = MESSAGE_KEY, colorizer = defaultColorizer }) {\n if (messageFormat) {\n const message = String(messageFormat).replace(/{([^{}]+)}/g, function (match, p1) {\n if (p1 && log[p1]) {\n return log[p1]\n }\n return ''\n })\n return colorizer.message(message)\n }\n if (messageKey in log === false) return undefined\n if (typeof log[messageKey] !== 'string') return undefined\n return colorizer.message(log[messageKey])\n}\n\n/**\n * Prettifies metadata that is usually present in a Pino log line. It looks for\n * fields `name`, `pid`, `hostname`, and `caller` and returns a formatted string using\n * the fields it finds.\n *\n * @param {object} input\n * @param {object} input.log The log that may or may not contain metadata to\n * be prettified.\n *\n * @returns {undefined|string} If no metadata is found then `undefined` is\n * returned. Otherwise, a string of prettified metadata is returned.\n */\nfunction prettifyMetadata ({ log }) {\n let line = ''\n\n if (log.name || log.pid || log.hostname) {\n line += '('\n\n if (log.name) {\n line += log.name\n }\n\n if (log.name && log.pid) {\n line += '/' + log.pid\n } else if (log.pid) {\n line += log.pid\n }\n\n if (log.hostname) {\n // If `pid` and `name` were in the ignore keys list then we don't need\n // the leading space.\n line += `${line === '(' ? 'on' : ' on'} ${log.hostname}`\n }\n\n line += ')'\n }\n\n if (log.caller) {\n line += `${line === '' ? '' : ' '}<${log.caller}>`\n }\n\n if (line === '') {\n return undefined\n } else {\n return line\n }\n}\n\n/**\n * Prettifies a standard object. Special care is taken when processing the object\n * to handle child objects that are attached to keys known to contain error\n * objects.\n *\n * @param {object} input\n * @param {object} input.input The object to prettify.\n * @param {string} [input.ident] The identation sequence to use. Default: `' '`.\n * @param {string} [input.eol] The EOL sequence to use. Default: `'\\n'`.\n * @param {string[]} [input.skipKeys] A set of object keys to exclude from the\n * prettified result. Default: `[]`.\n * @param {Object} [input.customPrettifiers] Dictionary of\n * custom prettifiers. Default: `{}`.\n * @param {string[]} [input.errorLikeKeys] A set of object keys that contain\n * error objects. Default: `ERROR_LIKE_KEYS` constant.\n * @param {boolean} [input.excludeLoggerKeys] Indicates if known logger specific\n * keys should be excluded from prettification. Default: `true`.\n *\n * @returns {string} The prettified string. This can be as little as `''` if\n * there was nothing to prettify.\n */\nfunction prettifyObject ({\n input,\n ident = ' ',\n eol = '\\n',\n skipKeys = [],\n customPrettifiers = {},\n errorLikeKeys = ERROR_LIKE_KEYS,\n excludeLoggerKeys = true\n}) {\n const objectKeys = Object.keys(input)\n const keysToIgnore = [].concat(skipKeys)\n\n if (excludeLoggerKeys === true) Array.prototype.push.apply(keysToIgnore, LOGGER_KEYS)\n\n let result = ''\n\n const keysToIterate = objectKeys.filter(k => keysToIgnore.includes(k) === false)\n for (var i = 0; i < objectKeys.length; i += 1) {\n const keyName = keysToIterate[i]\n const keyValue = input[keyName]\n\n if (keyValue === undefined) continue\n\n let lines\n if (typeof customPrettifiers[keyName] === 'function') {\n lines = customPrettifiers[keyName](keyValue, keyName, input)\n } else {\n lines = stringifySafe(keyValue, null, 2)\n }\n\n if (lines === undefined) continue\n const joinedLines = joinLinesWithIndentation({ input: lines, ident, eol })\n\n if (errorLikeKeys.includes(keyName) === true) {\n const splitLines = `${ident}${keyName}: ${joinedLines}${eol}`.split(eol)\n for (var j = 0; j < splitLines.length; j += 1) {\n if (j !== 0) result += eol\n\n const line = splitLines[j]\n if (/^\\s*\"stack\"/.test(line)) {\n const matches = /^(\\s*\"stack\":)\\s*(\".*\"),?$/.exec(line)\n if (matches && matches.length === 3) {\n const indentSize = /^\\s*/.exec(line)[0].length + 4\n const indentation = ' '.repeat(indentSize)\n const stackMessage = matches[2]\n result += matches[1] + eol + indentation + JSON.parse(stackMessage).replace(/\\n/g, eol + indentation)\n }\n } else {\n result += line\n }\n }\n } else {\n result += `${ident}${keyName}: ${joinedLines}${eol}`\n }\n }\n\n return result\n}\n\n/**\n * Prettifies a timestamp if the given `log` has either `time`, `timestamp` or custom specified timestamp\n * property.\n *\n * @param {object} input\n * @param {object} input.log The log object with the timestamp to be prettified.\n * @param {string} [input.timestampKey='time'] The log property that should be used to resolve timestamp value\n * @param {bool|string} [input.translateFormat=undefined] When `true` the\n * timestamp will be prettified into a string at UTC using the default\n * `DATE_FORMAT`. If a string, then `translateFormat` will be used as the format\n * string to determine the output; see the `formatTime` function for details.\n *\n * @returns {undefined|string} If a timestamp property cannot be found then\n * `undefined` is returned. Otherwise, the prettified time is returned as a\n * string.\n */\nfunction prettifyTime ({ log, timestampKey = TIMESTAMP_KEY, translateFormat = undefined }) {\n let time = null\n\n if (timestampKey in log) {\n time = log[timestampKey]\n } else if ('timestamp' in log) {\n time = log.timestamp\n }\n\n if (time === null) return undefined\n if (translateFormat) {\n return '[' + formatTime(time, translateFormat) + ']'\n }\n\n return `[${time}]`\n}\n","'use strict';\nconst colorConvert = require('color-convert');\n\nconst wrapAnsi16 = (fn, offset) => function () {\n\tconst code = fn.apply(colorConvert, arguments);\n\treturn `\\u001B[${code + offset}m`;\n};\n\nconst wrapAnsi256 = (fn, offset) => function () {\n\tconst code = fn.apply(colorConvert, arguments);\n\treturn `\\u001B[${38 + offset};5;${code}m`;\n};\n\nconst wrapAnsi16m = (fn, offset) => function () {\n\tconst rgb = fn.apply(colorConvert, arguments);\n\treturn `\\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;\n};\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\tconst styles = {\n\t\tmodifier: {\n\t\t\treset: [0, 0],\n\t\t\t// 21 isn't widely supported and 22 does the same thing\n\t\t\tbold: [1, 22],\n\t\t\tdim: [2, 22],\n\t\t\titalic: [3, 23],\n\t\t\tunderline: [4, 24],\n\t\t\tinverse: [7, 27],\n\t\t\thidden: [8, 28],\n\t\t\tstrikethrough: [9, 29]\n\t\t},\n\t\tcolor: {\n\t\t\tblack: [30, 39],\n\t\t\tred: [31, 39],\n\t\t\tgreen: [32, 39],\n\t\t\tyellow: [33, 39],\n\t\t\tblue: [34, 39],\n\t\t\tmagenta: [35, 39],\n\t\t\tcyan: [36, 39],\n\t\t\twhite: [37, 39],\n\t\t\tgray: [90, 39],\n\n\t\t\t// Bright color\n\t\t\tredBright: [91, 39],\n\t\t\tgreenBright: [92, 39],\n\t\t\tyellowBright: [93, 39],\n\t\t\tblueBright: [94, 39],\n\t\t\tmagentaBright: [95, 39],\n\t\t\tcyanBright: [96, 39],\n\t\t\twhiteBright: [97, 39]\n\t\t},\n\t\tbgColor: {\n\t\t\tbgBlack: [40, 49],\n\t\t\tbgRed: [41, 49],\n\t\t\tbgGreen: [42, 49],\n\t\t\tbgYellow: [43, 49],\n\t\t\tbgBlue: [44, 49],\n\t\t\tbgMagenta: [45, 49],\n\t\t\tbgCyan: [46, 49],\n\t\t\tbgWhite: [47, 49],\n\n\t\t\t// Bright color\n\t\t\tbgBlackBright: [100, 49],\n\t\t\tbgRedBright: [101, 49],\n\t\t\tbgGreenBright: [102, 49],\n\t\t\tbgYellowBright: [103, 49],\n\t\t\tbgBlueBright: [104, 49],\n\t\t\tbgMagentaBright: [105, 49],\n\t\t\tbgCyanBright: [106, 49],\n\t\t\tbgWhiteBright: [107, 49]\n\t\t}\n\t};\n\n\t// Fix humans\n\tstyles.color.grey = styles.color.gray;\n\n\tfor (const groupName of Object.keys(styles)) {\n\t\tconst group = styles[groupName];\n\n\t\tfor (const styleName of Object.keys(group)) {\n\t\t\tconst style = group[styleName];\n\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false\n\t\t});\n\n\t\tObject.defineProperty(styles, 'codes', {\n\t\t\tvalue: codes,\n\t\t\tenumerable: false\n\t\t});\n\t}\n\n\tconst ansi2ansi = n => n;\n\tconst rgb2rgb = (r, g, b) => [r, g, b];\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = {\n\t\tansi: wrapAnsi16(ansi2ansi, 0)\n\t};\n\tstyles.color.ansi256 = {\n\t\tansi256: wrapAnsi256(ansi2ansi, 0)\n\t};\n\tstyles.color.ansi16m = {\n\t\trgb: wrapAnsi16m(rgb2rgb, 0)\n\t};\n\n\tstyles.bgColor.ansi = {\n\t\tansi: wrapAnsi16(ansi2ansi, 10)\n\t};\n\tstyles.bgColor.ansi256 = {\n\t\tansi256: wrapAnsi256(ansi2ansi, 10)\n\t};\n\tstyles.bgColor.ansi16m = {\n\t\trgb: wrapAnsi16m(rgb2rgb, 10)\n\t};\n\n\tfor (let key of Object.keys(colorConvert)) {\n\t\tif (typeof colorConvert[key] !== 'object') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst suite = colorConvert[key];\n\n\t\tif (key === 'ansi16') {\n\t\t\tkey = 'ansi';\n\t\t}\n\n\t\tif ('ansi16' in suite) {\n\t\t\tstyles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);\n\t\t\tstyles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);\n\t\t}\n\n\t\tif ('ansi256' in suite) {\n\t\t\tstyles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);\n\t\t\tstyles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);\n\t\t}\n\n\t\tif ('rgb' in suite) {\n\t\t\tstyles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);\n\t\t\tstyles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);\n\t\t}\n\t}\n\n\treturn styles;\n}\n\n// Make the export immutable\nObject.defineProperty(module, 'exports', {\n\tenumerable: true,\n\tget: assembleStyles\n});\n","'use strict';\nconst escapeStringRegexp = require('escape-string-regexp');\nconst ansiStyles = require('ansi-styles');\nconst stdoutColor = require('supports-color').stdout;\n\nconst template = require('./templates.js');\n\nconst isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');\n\n// `supportsColor.level` → `ansiStyles.color[name]` mapping\nconst levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];\n\n// `color-convert` models to exclude from the Chalk API due to conflicts and such\nconst skipModels = new Set(['gray']);\n\nconst styles = Object.create(null);\n\nfunction applyOptions(obj, options) {\n\toptions = options || {};\n\n\t// Detect level if not set manually\n\tconst scLevel = stdoutColor ? stdoutColor.level : 0;\n\tobj.level = options.level === undefined ? scLevel : options.level;\n\tobj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;\n}\n\nfunction Chalk(options) {\n\t// We check for this.template here since calling `chalk.constructor()`\n\t// by itself will have a `this` of a previously constructed chalk object\n\tif (!this || !(this instanceof Chalk) || this.template) {\n\t\tconst chalk = {};\n\t\tapplyOptions(chalk, options);\n\n\t\tchalk.template = function () {\n\t\t\tconst args = [].slice.call(arguments);\n\t\t\treturn chalkTag.apply(null, [chalk.template].concat(args));\n\t\t};\n\n\t\tObject.setPrototypeOf(chalk, Chalk.prototype);\n\t\tObject.setPrototypeOf(chalk.template, chalk);\n\n\t\tchalk.template.constructor = Chalk;\n\n\t\treturn chalk.template;\n\t}\n\n\tapplyOptions(this, options);\n}\n\n// Use bright blue on Windows as the normal blue color is illegible\nif (isSimpleWindowsTerm) {\n\tansiStyles.blue.open = '\\u001B[94m';\n}\n\nfor (const key of Object.keys(ansiStyles)) {\n\tansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');\n\n\tstyles[key] = {\n\t\tget() {\n\t\t\tconst codes = ansiStyles[key];\n\t\t\treturn build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);\n\t\t}\n\t};\n}\n\nstyles.visible = {\n\tget() {\n\t\treturn build.call(this, this._styles || [], true, 'visible');\n\t}\n};\n\nansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');\nfor (const model of Object.keys(ansiStyles.color.ansi)) {\n\tif (skipModels.has(model)) {\n\t\tcontinue;\n\t}\n\n\tstyles[model] = {\n\t\tget() {\n\t\t\tconst level = this.level;\n\t\t\treturn function () {\n\t\t\t\tconst open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);\n\t\t\t\tconst codes = {\n\t\t\t\t\topen,\n\t\t\t\t\tclose: ansiStyles.color.close,\n\t\t\t\t\tcloseRe: ansiStyles.color.closeRe\n\t\t\t\t};\n\t\t\t\treturn build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);\n\t\t\t};\n\t\t}\n\t};\n}\n\nansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');\nfor (const model of Object.keys(ansiStyles.bgColor.ansi)) {\n\tif (skipModels.has(model)) {\n\t\tcontinue;\n\t}\n\n\tconst bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);\n\tstyles[bgModel] = {\n\t\tget() {\n\t\t\tconst level = this.level;\n\t\t\treturn function () {\n\t\t\t\tconst open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);\n\t\t\t\tconst codes = {\n\t\t\t\t\topen,\n\t\t\t\t\tclose: ansiStyles.bgColor.close,\n\t\t\t\t\tcloseRe: ansiStyles.bgColor.closeRe\n\t\t\t\t};\n\t\t\t\treturn build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);\n\t\t\t};\n\t\t}\n\t};\n}\n\nconst proto = Object.defineProperties(() => {}, styles);\n\nfunction build(_styles, _empty, key) {\n\tconst builder = function () {\n\t\treturn applyStyle.apply(builder, arguments);\n\t};\n\n\tbuilder._styles = _styles;\n\tbuilder._empty = _empty;\n\n\tconst self = this;\n\n\tObject.defineProperty(builder, 'level', {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn self.level;\n\t\t},\n\t\tset(level) {\n\t\t\tself.level = level;\n\t\t}\n\t});\n\n\tObject.defineProperty(builder, 'enabled', {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn self.enabled;\n\t\t},\n\t\tset(enabled) {\n\t\t\tself.enabled = enabled;\n\t\t}\n\t});\n\n\t// See below for fix regarding invisible grey/dim combination on Windows\n\tbuilder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';\n\n\t// `__proto__` is used because we must return a function, but there is\n\t// no way to create a function with a different prototype\n\tbuilder.__proto__ = proto; // eslint-disable-line no-proto\n\n\treturn builder;\n}\n\nfunction applyStyle() {\n\t// Support varags, but simply cast to string in case there's only one arg\n\tconst args = arguments;\n\tconst argsLen = args.length;\n\tlet str = String(arguments[0]);\n\n\tif (argsLen === 0) {\n\t\treturn '';\n\t}\n\n\tif (argsLen > 1) {\n\t\t// Don't slice `arguments`, it prevents V8 optimizations\n\t\tfor (let a = 1; a < argsLen; a++) {\n\t\t\tstr += ' ' + args[a];\n\t\t}\n\t}\n\n\tif (!this.enabled || this.level <= 0 || !str) {\n\t\treturn this._empty ? '' : str;\n\t}\n\n\t// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,\n\t// see https://github.com/chalk/chalk/issues/58\n\t// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.\n\tconst originalDim = ansiStyles.dim.open;\n\tif (isSimpleWindowsTerm && this.hasGrey) {\n\t\tansiStyles.dim.open = '';\n\t}\n\n\tfor (const code of this._styles.slice().reverse()) {\n\t\t// Replace any instances already present with a re-opening code\n\t\t// otherwise only the part of the string until said closing code\n\t\t// will be colored, and the rest will simply be 'plain'.\n\t\tstr = code.open + str.replace(code.closeRe, code.open) + code.close;\n\n\t\t// Close the styling before a linebreak and reopen\n\t\t// after next line to fix a bleed issue on macOS\n\t\t// https://github.com/chalk/chalk/pull/92\n\t\tstr = str.replace(/\\r?\\n/g, `${code.close}$&${code.open}`);\n\t}\n\n\t// Reset the original `dim` if we changed it to work around the Windows dimmed gray issue\n\tansiStyles.dim.open = originalDim;\n\n\treturn str;\n}\n\nfunction chalkTag(chalk, strings) {\n\tif (!Array.isArray(strings)) {\n\t\t// If chalk() was called by itself or with a string,\n\t\t// return the string itself as a string.\n\t\treturn [].slice.call(arguments, 1).join(' ');\n\t}\n\n\tconst args = [].slice.call(arguments, 2);\n\tconst parts = [strings.raw[0]];\n\n\tfor (let i = 1; i < strings.length; i++) {\n\t\tparts.push(String(args[i - 1]).replace(/[{}\\\\]/g, '\\\\$&'));\n\t\tparts.push(String(strings.raw[i]));\n\t}\n\n\treturn template(chalk, parts.join(''));\n}\n\nObject.defineProperties(Chalk.prototype, styles);\n\nmodule.exports = Chalk(); // eslint-disable-line new-cap\nmodule.exports.supportsColor = stdoutColor;\nmodule.exports.default = module.exports; // For TypeScript\n","'use strict';\nconst TEMPLATE_REGEX = /(?:\\\\(u[a-f\\d]{4}|x[a-f\\d]{2}|.))|(?:\\{(~)?(\\w+(?:\\([^)]*\\))?(?:\\.\\w+(?:\\([^)]*\\))?)*)(?:[ \\t]|(?=\\r?\\n)))|(\\})|((?:.|[\\r\\n\\f])+?)/gi;\nconst STYLE_REGEX = /(?:^|\\.)(\\w+)(?:\\(([^)]*)\\))?/g;\nconst STRING_REGEX = /^(['\"])((?:\\\\.|(?!\\1)[^\\\\])*)\\1$/;\nconst ESCAPE_REGEX = /\\\\(u[a-f\\d]{4}|x[a-f\\d]{2}|.)|([^\\\\])/gi;\n\nconst ESCAPES = new Map([\n\t['n', '\\n'],\n\t['r', '\\r'],\n\t['t', '\\t'],\n\t['b', '\\b'],\n\t['f', '\\f'],\n\t['v', '\\v'],\n\t['0', '\\0'],\n\t['\\\\', '\\\\'],\n\t['e', '\\u001B'],\n\t['a', '\\u0007']\n]);\n\nfunction unescape(c) {\n\tif ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {\n\t\treturn String.fromCharCode(parseInt(c.slice(1), 16));\n\t}\n\n\treturn ESCAPES.get(c) || c;\n}\n\nfunction parseArguments(name, args) {\n\tconst results = [];\n\tconst chunks = args.trim().split(/\\s*,\\s*/g);\n\tlet matches;\n\n\tfor (const chunk of chunks) {\n\t\tif (!isNaN(chunk)) {\n\t\t\tresults.push(Number(chunk));\n\t\t} else if ((matches = chunk.match(STRING_REGEX))) {\n\t\t\tresults.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));\n\t\t} else {\n\t\t\tthrow new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);\n\t\t}\n\t}\n\n\treturn results;\n}\n\nfunction parseStyle(style) {\n\tSTYLE_REGEX.lastIndex = 0;\n\n\tconst results = [];\n\tlet matches;\n\n\twhile ((matches = STYLE_REGEX.exec(style)) !== null) {\n\t\tconst name = matches[1];\n\n\t\tif (matches[2]) {\n\t\t\tconst args = parseArguments(name, matches[2]);\n\t\t\tresults.push([name].concat(args));\n\t\t} else {\n\t\t\tresults.push([name]);\n\t\t}\n\t}\n\n\treturn results;\n}\n\nfunction buildStyle(chalk, styles) {\n\tconst enabled = {};\n\n\tfor (const layer of styles) {\n\t\tfor (const style of layer.styles) {\n\t\t\tenabled[style[0]] = layer.inverse ? null : style.slice(1);\n\t\t}\n\t}\n\n\tlet current = chalk;\n\tfor (const styleName of Object.keys(enabled)) {\n\t\tif (Array.isArray(enabled[styleName])) {\n\t\t\tif (!(styleName in current)) {\n\t\t\t\tthrow new Error(`Unknown Chalk style: ${styleName}`);\n\t\t\t}\n\n\t\t\tif (enabled[styleName].length > 0) {\n\t\t\t\tcurrent = current[styleName].apply(current, enabled[styleName]);\n\t\t\t} else {\n\t\t\t\tcurrent = current[styleName];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn current;\n}\n\nmodule.exports = (chalk, tmp) => {\n\tconst styles = [];\n\tconst chunks = [];\n\tlet chunk = [];\n\n\t// eslint-disable-next-line max-params\n\ttmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {\n\t\tif (escapeChar) {\n\t\t\tchunk.push(unescape(escapeChar));\n\t\t} else if (style) {\n\t\t\tconst str = chunk.join('');\n\t\t\tchunk = [];\n\t\t\tchunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));\n\t\t\tstyles.push({inverse, styles: parseStyle(style)});\n\t\t} else if (close) {\n\t\t\tif (styles.length === 0) {\n\t\t\t\tthrow new Error('Found extraneous } in Chalk template literal');\n\t\t\t}\n\n\t\t\tchunks.push(buildStyle(chalk, styles)(chunk.join('')));\n\t\t\tchunk = [];\n\t\t\tstyles.pop();\n\t\t} else {\n\t\t\tchunk.push(chr);\n\t\t}\n\t});\n\n\tchunks.push(chunk.join(''));\n\n\tif (styles.length > 0) {\n\t\tconst errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\\`}\\`)`;\n\t\tthrow new Error(errMsg);\n\t}\n\n\treturn chunks.join('');\n};\n","/* MIT license */\nvar cssKeywords = require('color-name');\n\n// NOTE: conversions should only return primitive values (i.e. arrays, or\n// values that give correct `typeof` results).\n// do not use box values types (i.e. Number(), String(), etc.)\n\nvar reverseKeywords = {};\nfor (var key in cssKeywords) {\n\tif (cssKeywords.hasOwnProperty(key)) {\n\t\treverseKeywords[cssKeywords[key]] = key;\n\t}\n}\n\nvar convert = module.exports = {\n\trgb: {channels: 3, labels: 'rgb'},\n\thsl: {channels: 3, labels: 'hsl'},\n\thsv: {channels: 3, labels: 'hsv'},\n\thwb: {channels: 3, labels: 'hwb'},\n\tcmyk: {channels: 4, labels: 'cmyk'},\n\txyz: {channels: 3, labels: 'xyz'},\n\tlab: {channels: 3, labels: 'lab'},\n\tlch: {channels: 3, labels: 'lch'},\n\thex: {channels: 1, labels: ['hex']},\n\tkeyword: {channels: 1, labels: ['keyword']},\n\tansi16: {channels: 1, labels: ['ansi16']},\n\tansi256: {channels: 1, labels: ['ansi256']},\n\thcg: {channels: 3, labels: ['h', 'c', 'g']},\n\tapple: {channels: 3, labels: ['r16', 'g16', 'b16']},\n\tgray: {channels: 1, labels: ['gray']}\n};\n\n// hide .channels and .labels properties\nfor (var model in convert) {\n\tif (convert.hasOwnProperty(model)) {\n\t\tif (!('channels' in convert[model])) {\n\t\t\tthrow new Error('missing channels property: ' + model);\n\t\t}\n\n\t\tif (!('labels' in convert[model])) {\n\t\t\tthrow new Error('missing channel labels property: ' + model);\n\t\t}\n\n\t\tif (convert[model].labels.length !== convert[model].channels) {\n\t\t\tthrow new Error('channel and label counts mismatch: ' + model);\n\t\t}\n\n\t\tvar channels = convert[model].channels;\n\t\tvar labels = convert[model].labels;\n\t\tdelete convert[model].channels;\n\t\tdelete convert[model].labels;\n\t\tObject.defineProperty(convert[model], 'channels', {value: channels});\n\t\tObject.defineProperty(convert[model], 'labels', {value: labels});\n\t}\n}\n\nconvert.rgb.hsl = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar min = Math.min(r, g, b);\n\tvar max = Math.max(r, g, b);\n\tvar delta = max - min;\n\tvar h;\n\tvar s;\n\tvar l;\n\n\tif (max === min) {\n\t\th = 0;\n\t} else if (r === max) {\n\t\th = (g - b) / delta;\n\t} else if (g === max) {\n\t\th = 2 + (b - r) / delta;\n\t} else if (b === max) {\n\t\th = 4 + (r - g) / delta;\n\t}\n\n\th = Math.min(h * 60, 360);\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tl = (min + max) / 2;\n\n\tif (max === min) {\n\t\ts = 0;\n\t} else if (l <= 0.5) {\n\t\ts = delta / (max + min);\n\t} else {\n\t\ts = delta / (2 - max - min);\n\t}\n\n\treturn [h, s * 100, l * 100];\n};\n\nconvert.rgb.hsv = function (rgb) {\n\tvar rdif;\n\tvar gdif;\n\tvar bdif;\n\tvar h;\n\tvar s;\n\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar v = Math.max(r, g, b);\n\tvar diff = v - Math.min(r, g, b);\n\tvar diffc = function (c) {\n\t\treturn (v - c) / 6 / diff + 1 / 2;\n\t};\n\n\tif (diff === 0) {\n\t\th = s = 0;\n\t} else {\n\t\ts = diff / v;\n\t\trdif = diffc(r);\n\t\tgdif = diffc(g);\n\t\tbdif = diffc(b);\n\n\t\tif (r === v) {\n\t\t\th = bdif - gdif;\n\t\t} else if (g === v) {\n\t\t\th = (1 / 3) + rdif - bdif;\n\t\t} else if (b === v) {\n\t\t\th = (2 / 3) + gdif - rdif;\n\t\t}\n\t\tif (h < 0) {\n\t\t\th += 1;\n\t\t} else if (h > 1) {\n\t\t\th -= 1;\n\t\t}\n\t}\n\n\treturn [\n\t\th * 360,\n\t\ts * 100,\n\t\tv * 100\n\t];\n};\n\nconvert.rgb.hwb = function (rgb) {\n\tvar r = rgb[0];\n\tvar g = rgb[1];\n\tvar b = rgb[2];\n\tvar h = convert.rgb.hsl(rgb)[0];\n\tvar w = 1 / 255 * Math.min(r, Math.min(g, b));\n\n\tb = 1 - 1 / 255 * Math.max(r, Math.max(g, b));\n\n\treturn [h, w * 100, b * 100];\n};\n\nconvert.rgb.cmyk = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar c;\n\tvar m;\n\tvar y;\n\tvar k;\n\n\tk = Math.min(1 - r, 1 - g, 1 - b);\n\tc = (1 - r - k) / (1 - k) || 0;\n\tm = (1 - g - k) / (1 - k) || 0;\n\ty = (1 - b - k) / (1 - k) || 0;\n\n\treturn [c * 100, m * 100, y * 100, k * 100];\n};\n\n/**\n * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance\n * */\nfunction comparativeDistance(x, y) {\n\treturn (\n\t\tMath.pow(x[0] - y[0], 2) +\n\t\tMath.pow(x[1] - y[1], 2) +\n\t\tMath.pow(x[2] - y[2], 2)\n\t);\n}\n\nconvert.rgb.keyword = function (rgb) {\n\tvar reversed = reverseKeywords[rgb];\n\tif (reversed) {\n\t\treturn reversed;\n\t}\n\n\tvar currentClosestDistance = Infinity;\n\tvar currentClosestKeyword;\n\n\tfor (var keyword in cssKeywords) {\n\t\tif (cssKeywords.hasOwnProperty(keyword)) {\n\t\t\tvar value = cssKeywords[keyword];\n\n\t\t\t// Compute comparative distance\n\t\t\tvar distance = comparativeDistance(rgb, value);\n\n\t\t\t// Check if its less, if so set as closest\n\t\t\tif (distance < currentClosestDistance) {\n\t\t\t\tcurrentClosestDistance = distance;\n\t\t\t\tcurrentClosestKeyword = keyword;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn currentClosestKeyword;\n};\n\nconvert.keyword.rgb = function (keyword) {\n\treturn cssKeywords[keyword];\n};\n\nconvert.rgb.xyz = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\n\t// assume sRGB\n\tr = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);\n\tg = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);\n\tb = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);\n\n\tvar x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);\n\tvar y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);\n\tvar z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);\n\n\treturn [x * 100, y * 100, z * 100];\n};\n\nconvert.rgb.lab = function (rgb) {\n\tvar xyz = convert.rgb.xyz(rgb);\n\tvar x = xyz[0];\n\tvar y = xyz[1];\n\tvar z = xyz[2];\n\tvar l;\n\tvar a;\n\tvar b;\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);\n\n\tl = (116 * y) - 16;\n\ta = 500 * (x - y);\n\tb = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.hsl.rgb = function (hsl) {\n\tvar h = hsl[0] / 360;\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar t1;\n\tvar t2;\n\tvar t3;\n\tvar rgb;\n\tvar val;\n\n\tif (s === 0) {\n\t\tval = l * 255;\n\t\treturn [val, val, val];\n\t}\n\n\tif (l < 0.5) {\n\t\tt2 = l * (1 + s);\n\t} else {\n\t\tt2 = l + s - l * s;\n\t}\n\n\tt1 = 2 * l - t2;\n\n\trgb = [0, 0, 0];\n\tfor (var i = 0; i < 3; i++) {\n\t\tt3 = h + 1 / 3 * -(i - 1);\n\t\tif (t3 < 0) {\n\t\t\tt3++;\n\t\t}\n\t\tif (t3 > 1) {\n\t\t\tt3--;\n\t\t}\n\n\t\tif (6 * t3 < 1) {\n\t\t\tval = t1 + (t2 - t1) * 6 * t3;\n\t\t} else if (2 * t3 < 1) {\n\t\t\tval = t2;\n\t\t} else if (3 * t3 < 2) {\n\t\t\tval = t1 + (t2 - t1) * (2 / 3 - t3) * 6;\n\t\t} else {\n\t\t\tval = t1;\n\t\t}\n\n\t\trgb[i] = val * 255;\n\t}\n\n\treturn rgb;\n};\n\nconvert.hsl.hsv = function (hsl) {\n\tvar h = hsl[0];\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar smin = s;\n\tvar lmin = Math.max(l, 0.01);\n\tvar sv;\n\tvar v;\n\n\tl *= 2;\n\ts *= (l <= 1) ? l : 2 - l;\n\tsmin *= lmin <= 1 ? lmin : 2 - lmin;\n\tv = (l + s) / 2;\n\tsv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);\n\n\treturn [h, sv * 100, v * 100];\n};\n\nconvert.hsv.rgb = function (hsv) {\n\tvar h = hsv[0] / 60;\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\tvar hi = Math.floor(h) % 6;\n\n\tvar f = h - Math.floor(h);\n\tvar p = 255 * v * (1 - s);\n\tvar q = 255 * v * (1 - (s * f));\n\tvar t = 255 * v * (1 - (s * (1 - f)));\n\tv *= 255;\n\n\tswitch (hi) {\n\t\tcase 0:\n\t\t\treturn [v, t, p];\n\t\tcase 1:\n\t\t\treturn [q, v, p];\n\t\tcase 2:\n\t\t\treturn [p, v, t];\n\t\tcase 3:\n\t\t\treturn [p, q, v];\n\t\tcase 4:\n\t\t\treturn [t, p, v];\n\t\tcase 5:\n\t\t\treturn [v, p, q];\n\t}\n};\n\nconvert.hsv.hsl = function (hsv) {\n\tvar h = hsv[0];\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\tvar vmin = Math.max(v, 0.01);\n\tvar lmin;\n\tvar sl;\n\tvar l;\n\n\tl = (2 - s) * v;\n\tlmin = (2 - s) * vmin;\n\tsl = s * vmin;\n\tsl /= (lmin <= 1) ? lmin : 2 - lmin;\n\tsl = sl || 0;\n\tl /= 2;\n\n\treturn [h, sl * 100, l * 100];\n};\n\n// http://dev.w3.org/csswg/css-color/#hwb-to-rgb\nconvert.hwb.rgb = function (hwb) {\n\tvar h = hwb[0] / 360;\n\tvar wh = hwb[1] / 100;\n\tvar bl = hwb[2] / 100;\n\tvar ratio = wh + bl;\n\tvar i;\n\tvar v;\n\tvar f;\n\tvar n;\n\n\t// wh + bl cant be > 1\n\tif (ratio > 1) {\n\t\twh /= ratio;\n\t\tbl /= ratio;\n\t}\n\n\ti = Math.floor(6 * h);\n\tv = 1 - bl;\n\tf = 6 * h - i;\n\n\tif ((i & 0x01) !== 0) {\n\t\tf = 1 - f;\n\t}\n\n\tn = wh + f * (v - wh); // linear interpolation\n\n\tvar r;\n\tvar g;\n\tvar b;\n\tswitch (i) {\n\t\tdefault:\n\t\tcase 6:\n\t\tcase 0: r = v; g = n; b = wh; break;\n\t\tcase 1: r = n; g = v; b = wh; break;\n\t\tcase 2: r = wh; g = v; b = n; break;\n\t\tcase 3: r = wh; g = n; b = v; break;\n\t\tcase 4: r = n; g = wh; b = v; break;\n\t\tcase 5: r = v; g = wh; b = n; break;\n\t}\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.cmyk.rgb = function (cmyk) {\n\tvar c = cmyk[0] / 100;\n\tvar m = cmyk[1] / 100;\n\tvar y = cmyk[2] / 100;\n\tvar k = cmyk[3] / 100;\n\tvar r;\n\tvar g;\n\tvar b;\n\n\tr = 1 - Math.min(1, c * (1 - k) + k);\n\tg = 1 - Math.min(1, m * (1 - k) + k);\n\tb = 1 - Math.min(1, y * (1 - k) + k);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.rgb = function (xyz) {\n\tvar x = xyz[0] / 100;\n\tvar y = xyz[1] / 100;\n\tvar z = xyz[2] / 100;\n\tvar r;\n\tvar g;\n\tvar b;\n\n\tr = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);\n\tg = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);\n\tb = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);\n\n\t// assume sRGB\n\tr = r > 0.0031308\n\t\t? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)\n\t\t: r * 12.92;\n\n\tg = g > 0.0031308\n\t\t? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)\n\t\t: g * 12.92;\n\n\tb = b > 0.0031308\n\t\t? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)\n\t\t: b * 12.92;\n\n\tr = Math.min(Math.max(0, r), 1);\n\tg = Math.min(Math.max(0, g), 1);\n\tb = Math.min(Math.max(0, b), 1);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.lab = function (xyz) {\n\tvar x = xyz[0];\n\tvar y = xyz[1];\n\tvar z = xyz[2];\n\tvar l;\n\tvar a;\n\tvar b;\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);\n\n\tl = (116 * y) - 16;\n\ta = 500 * (x - y);\n\tb = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.lab.xyz = function (lab) {\n\tvar l = lab[0];\n\tvar a = lab[1];\n\tvar b = lab[2];\n\tvar x;\n\tvar y;\n\tvar z;\n\n\ty = (l + 16) / 116;\n\tx = a / 500 + y;\n\tz = y - b / 200;\n\n\tvar y2 = Math.pow(y, 3);\n\tvar x2 = Math.pow(x, 3);\n\tvar z2 = Math.pow(z, 3);\n\ty = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;\n\tx = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;\n\tz = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;\n\n\tx *= 95.047;\n\ty *= 100;\n\tz *= 108.883;\n\n\treturn [x, y, z];\n};\n\nconvert.lab.lch = function (lab) {\n\tvar l = lab[0];\n\tvar a = lab[1];\n\tvar b = lab[2];\n\tvar hr;\n\tvar h;\n\tvar c;\n\n\thr = Math.atan2(b, a);\n\th = hr * 360 / 2 / Math.PI;\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tc = Math.sqrt(a * a + b * b);\n\n\treturn [l, c, h];\n};\n\nconvert.lch.lab = function (lch) {\n\tvar l = lch[0];\n\tvar c = lch[1];\n\tvar h = lch[2];\n\tvar a;\n\tvar b;\n\tvar hr;\n\n\thr = h / 360 * 2 * Math.PI;\n\ta = c * Math.cos(hr);\n\tb = c * Math.sin(hr);\n\n\treturn [l, a, b];\n};\n\nconvert.rgb.ansi16 = function (args) {\n\tvar r = args[0];\n\tvar g = args[1];\n\tvar b = args[2];\n\tvar value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization\n\n\tvalue = Math.round(value / 50);\n\n\tif (value === 0) {\n\t\treturn 30;\n\t}\n\n\tvar ansi = 30\n\t\t+ ((Math.round(b / 255) << 2)\n\t\t| (Math.round(g / 255) << 1)\n\t\t| Math.round(r / 255));\n\n\tif (value === 2) {\n\t\tansi += 60;\n\t}\n\n\treturn ansi;\n};\n\nconvert.hsv.ansi16 = function (args) {\n\t// optimization here; we already know the value and don't need to get\n\t// it converted for us.\n\treturn convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);\n};\n\nconvert.rgb.ansi256 = function (args) {\n\tvar r = args[0];\n\tvar g = args[1];\n\tvar b = args[2];\n\n\t// we use the extended greyscale palette here, with the exception of\n\t// black and white. normal palette only has 4 greyscale shades.\n\tif (r === g && g === b) {\n\t\tif (r < 8) {\n\t\t\treturn 16;\n\t\t}\n\n\t\tif (r > 248) {\n\t\t\treturn 231;\n\t\t}\n\n\t\treturn Math.round(((r - 8) / 247) * 24) + 232;\n\t}\n\n\tvar ansi = 16\n\t\t+ (36 * Math.round(r / 255 * 5))\n\t\t+ (6 * Math.round(g / 255 * 5))\n\t\t+ Math.round(b / 255 * 5);\n\n\treturn ansi;\n};\n\nconvert.ansi16.rgb = function (args) {\n\tvar color = args % 10;\n\n\t// handle greyscale\n\tif (color === 0 || color === 7) {\n\t\tif (args > 50) {\n\t\t\tcolor += 3.5;\n\t\t}\n\n\t\tcolor = color / 10.5 * 255;\n\n\t\treturn [color, color, color];\n\t}\n\n\tvar mult = (~~(args > 50) + 1) * 0.5;\n\tvar r = ((color & 1) * mult) * 255;\n\tvar g = (((color >> 1) & 1) * mult) * 255;\n\tvar b = (((color >> 2) & 1) * mult) * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.ansi256.rgb = function (args) {\n\t// handle greyscale\n\tif (args >= 232) {\n\t\tvar c = (args - 232) * 10 + 8;\n\t\treturn [c, c, c];\n\t}\n\n\targs -= 16;\n\n\tvar rem;\n\tvar r = Math.floor(args / 36) / 5 * 255;\n\tvar g = Math.floor((rem = args % 36) / 6) / 5 * 255;\n\tvar b = (rem % 6) / 5 * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hex = function (args) {\n\tvar integer = ((Math.round(args[0]) & 0xFF) << 16)\n\t\t+ ((Math.round(args[1]) & 0xFF) << 8)\n\t\t+ (Math.round(args[2]) & 0xFF);\n\n\tvar string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.hex.rgb = function (args) {\n\tvar match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);\n\tif (!match) {\n\t\treturn [0, 0, 0];\n\t}\n\n\tvar colorString = match[0];\n\n\tif (match[0].length === 3) {\n\t\tcolorString = colorString.split('').map(function (char) {\n\t\t\treturn char + char;\n\t\t}).join('');\n\t}\n\n\tvar integer = parseInt(colorString, 16);\n\tvar r = (integer >> 16) & 0xFF;\n\tvar g = (integer >> 8) & 0xFF;\n\tvar b = integer & 0xFF;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hcg = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar max = Math.max(Math.max(r, g), b);\n\tvar min = Math.min(Math.min(r, g), b);\n\tvar chroma = (max - min);\n\tvar grayscale;\n\tvar hue;\n\n\tif (chroma < 1) {\n\t\tgrayscale = min / (1 - chroma);\n\t} else {\n\t\tgrayscale = 0;\n\t}\n\n\tif (chroma <= 0) {\n\t\thue = 0;\n\t} else\n\tif (max === r) {\n\t\thue = ((g - b) / chroma) % 6;\n\t} else\n\tif (max === g) {\n\t\thue = 2 + (b - r) / chroma;\n\t} else {\n\t\thue = 4 + (r - g) / chroma + 4;\n\t}\n\n\thue /= 6;\n\thue %= 1;\n\n\treturn [hue * 360, chroma * 100, grayscale * 100];\n};\n\nconvert.hsl.hcg = function (hsl) {\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar c = 1;\n\tvar f = 0;\n\n\tif (l < 0.5) {\n\t\tc = 2.0 * s * l;\n\t} else {\n\t\tc = 2.0 * s * (1.0 - l);\n\t}\n\n\tif (c < 1.0) {\n\t\tf = (l - 0.5 * c) / (1.0 - c);\n\t}\n\n\treturn [hsl[0], c * 100, f * 100];\n};\n\nconvert.hsv.hcg = function (hsv) {\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\n\tvar c = s * v;\n\tvar f = 0;\n\n\tif (c < 1.0) {\n\t\tf = (v - c) / (1 - c);\n\t}\n\n\treturn [hsv[0], c * 100, f * 100];\n};\n\nconvert.hcg.rgb = function (hcg) {\n\tvar h = hcg[0] / 360;\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tif (c === 0.0) {\n\t\treturn [g * 255, g * 255, g * 255];\n\t}\n\n\tvar pure = [0, 0, 0];\n\tvar hi = (h % 1) * 6;\n\tvar v = hi % 1;\n\tvar w = 1 - v;\n\tvar mg = 0;\n\n\tswitch (Math.floor(hi)) {\n\t\tcase 0:\n\t\t\tpure[0] = 1; pure[1] = v; pure[2] = 0; break;\n\t\tcase 1:\n\t\t\tpure[0] = w; pure[1] = 1; pure[2] = 0; break;\n\t\tcase 2:\n\t\t\tpure[0] = 0; pure[1] = 1; pure[2] = v; break;\n\t\tcase 3:\n\t\t\tpure[0] = 0; pure[1] = w; pure[2] = 1; break;\n\t\tcase 4:\n\t\t\tpure[0] = v; pure[1] = 0; pure[2] = 1; break;\n\t\tdefault:\n\t\t\tpure[0] = 1; pure[1] = 0; pure[2] = w;\n\t}\n\n\tmg = (1.0 - c) * g;\n\n\treturn [\n\t\t(c * pure[0] + mg) * 255,\n\t\t(c * pure[1] + mg) * 255,\n\t\t(c * pure[2] + mg) * 255\n\t];\n};\n\nconvert.hcg.hsv = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tvar v = c + g * (1.0 - c);\n\tvar f = 0;\n\n\tif (v > 0.0) {\n\t\tf = c / v;\n\t}\n\n\treturn [hcg[0], f * 100, v * 100];\n};\n\nconvert.hcg.hsl = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tvar l = g * (1.0 - c) + 0.5 * c;\n\tvar s = 0;\n\n\tif (l > 0.0 && l < 0.5) {\n\t\ts = c / (2 * l);\n\t} else\n\tif (l >= 0.5 && l < 1.0) {\n\t\ts = c / (2 * (1 - l));\n\t}\n\n\treturn [hcg[0], s * 100, l * 100];\n};\n\nconvert.hcg.hwb = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\tvar v = c + g * (1.0 - c);\n\treturn [hcg[0], (v - c) * 100, (1 - v) * 100];\n};\n\nconvert.hwb.hcg = function (hwb) {\n\tvar w = hwb[1] / 100;\n\tvar b = hwb[2] / 100;\n\tvar v = 1 - b;\n\tvar c = v - w;\n\tvar g = 0;\n\n\tif (c < 1) {\n\t\tg = (v - c) / (1 - c);\n\t}\n\n\treturn [hwb[0], c * 100, g * 100];\n};\n\nconvert.apple.rgb = function (apple) {\n\treturn [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];\n};\n\nconvert.rgb.apple = function (rgb) {\n\treturn [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];\n};\n\nconvert.gray.rgb = function (args) {\n\treturn [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];\n};\n\nconvert.gray.hsl = convert.gray.hsv = function (args) {\n\treturn [0, 0, args[0]];\n};\n\nconvert.gray.hwb = function (gray) {\n\treturn [0, 100, gray[0]];\n};\n\nconvert.gray.cmyk = function (gray) {\n\treturn [0, 0, 0, gray[0]];\n};\n\nconvert.gray.lab = function (gray) {\n\treturn [gray[0], 0, 0];\n};\n\nconvert.gray.hex = function (gray) {\n\tvar val = Math.round(gray[0] / 100 * 255) & 0xFF;\n\tvar integer = (val << 16) + (val << 8) + val;\n\n\tvar string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.rgb.gray = function (rgb) {\n\tvar val = (rgb[0] + rgb[1] + rgb[2]) / 3;\n\treturn [val / 255 * 100];\n};\n","var conversions = require('./conversions');\nvar route = require('./route');\n\nvar convert = {};\n\nvar models = Object.keys(conversions);\n\nfunction wrapRaw(fn) {\n\tvar wrappedFn = function (args) {\n\t\tif (args === undefined || args === null) {\n\t\t\treturn args;\n\t\t}\n\n\t\tif (arguments.length > 1) {\n\t\t\targs = Array.prototype.slice.call(arguments);\n\t\t}\n\n\t\treturn fn(args);\n\t};\n\n\t// preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nfunction wrapRounded(fn) {\n\tvar wrappedFn = function (args) {\n\t\tif (args === undefined || args === null) {\n\t\t\treturn args;\n\t\t}\n\n\t\tif (arguments.length > 1) {\n\t\t\targs = Array.prototype.slice.call(arguments);\n\t\t}\n\n\t\tvar result = fn(args);\n\n\t\t// we're assuming the result is an array here.\n\t\t// see notice in conversions.js; don't use box types\n\t\t// in conversion functions.\n\t\tif (typeof result === 'object') {\n\t\t\tfor (var len = result.length, i = 0; i < len; i++) {\n\t\t\t\tresult[i] = Math.round(result[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t};\n\n\t// preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nmodels.forEach(function (fromModel) {\n\tconvert[fromModel] = {};\n\n\tObject.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});\n\tObject.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});\n\n\tvar routes = route(fromModel);\n\tvar routeModels = Object.keys(routes);\n\n\trouteModels.forEach(function (toModel) {\n\t\tvar fn = routes[toModel];\n\n\t\tconvert[fromModel][toModel] = wrapRounded(fn);\n\t\tconvert[fromModel][toModel].raw = wrapRaw(fn);\n\t});\n});\n\nmodule.exports = convert;\n","var conversions = require('./conversions');\n\n/*\n\tthis function routes a model to all other models.\n\n\tall functions that are routed have a property `.conversion` attached\n\tto the returned synthetic function. This property is an array\n\tof strings, each with the steps in between the 'from' and 'to'\n\tcolor models (inclusive).\n\n\tconversions that are not possible simply are not included.\n*/\n\nfunction buildGraph() {\n\tvar graph = {};\n\t// https://jsperf.com/object-keys-vs-for-in-with-closure/3\n\tvar models = Object.keys(conversions);\n\n\tfor (var len = models.length, i = 0; i < len; i++) {\n\t\tgraph[models[i]] = {\n\t\t\t// http://jsperf.com/1-vs-infinity\n\t\t\t// micro-opt, but this is simple.\n\t\t\tdistance: -1,\n\t\t\tparent: null\n\t\t};\n\t}\n\n\treturn graph;\n}\n\n// https://en.wikipedia.org/wiki/Breadth-first_search\nfunction deriveBFS(fromModel) {\n\tvar graph = buildGraph();\n\tvar queue = [fromModel]; // unshift -> queue -> pop\n\n\tgraph[fromModel].distance = 0;\n\n\twhile (queue.length) {\n\t\tvar current = queue.pop();\n\t\tvar adjacents = Object.keys(conversions[current]);\n\n\t\tfor (var len = adjacents.length, i = 0; i < len; i++) {\n\t\t\tvar adjacent = adjacents[i];\n\t\t\tvar node = graph[adjacent];\n\n\t\t\tif (node.distance === -1) {\n\t\t\t\tnode.distance = graph[current].distance + 1;\n\t\t\t\tnode.parent = current;\n\t\t\t\tqueue.unshift(adjacent);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn graph;\n}\n\nfunction link(from, to) {\n\treturn function (args) {\n\t\treturn to(from(args));\n\t};\n}\n\nfunction wrapConversion(toModel, graph) {\n\tvar path = [graph[toModel].parent, toModel];\n\tvar fn = conversions[graph[toModel].parent][toModel];\n\n\tvar cur = graph[toModel].parent;\n\twhile (graph[cur].parent) {\n\t\tpath.unshift(graph[cur].parent);\n\t\tfn = link(conversions[graph[cur].parent][cur], fn);\n\t\tcur = graph[cur].parent;\n\t}\n\n\tfn.conversion = path;\n\treturn fn;\n}\n\nmodule.exports = function (fromModel) {\n\tvar graph = deriveBFS(fromModel);\n\tvar conversion = {};\n\n\tvar models = Object.keys(graph);\n\tfor (var len = models.length, i = 0; i < len; i++) {\n\t\tvar toModel = models[i];\n\t\tvar node = graph[toModel];\n\n\t\tif (node.parent === null) {\n\t\t\t// no possible conversion, or this node is the source model.\n\t\t\tcontinue;\n\t\t}\n\n\t\tconversion[toModel] = wrapConversion(toModel, graph);\n\t}\n\n\treturn conversion;\n};\n\n","'use strict'\r\n\r\nmodule.exports = {\r\n\t\"aliceblue\": [240, 248, 255],\r\n\t\"antiquewhite\": [250, 235, 215],\r\n\t\"aqua\": [0, 255, 255],\r\n\t\"aquamarine\": [127, 255, 212],\r\n\t\"azure\": [240, 255, 255],\r\n\t\"beige\": [245, 245, 220],\r\n\t\"bisque\": [255, 228, 196],\r\n\t\"black\": [0, 0, 0],\r\n\t\"blanchedalmond\": [255, 235, 205],\r\n\t\"blue\": [0, 0, 255],\r\n\t\"blueviolet\": [138, 43, 226],\r\n\t\"brown\": [165, 42, 42],\r\n\t\"burlywood\": [222, 184, 135],\r\n\t\"cadetblue\": [95, 158, 160],\r\n\t\"chartreuse\": [127, 255, 0],\r\n\t\"chocolate\": [210, 105, 30],\r\n\t\"coral\": [255, 127, 80],\r\n\t\"cornflowerblue\": [100, 149, 237],\r\n\t\"cornsilk\": [255, 248, 220],\r\n\t\"crimson\": [220, 20, 60],\r\n\t\"cyan\": [0, 255, 255],\r\n\t\"darkblue\": [0, 0, 139],\r\n\t\"darkcyan\": [0, 139, 139],\r\n\t\"darkgoldenrod\": [184, 134, 11],\r\n\t\"darkgray\": [169, 169, 169],\r\n\t\"darkgreen\": [0, 100, 0],\r\n\t\"darkgrey\": [169, 169, 169],\r\n\t\"darkkhaki\": [189, 183, 107],\r\n\t\"darkmagenta\": [139, 0, 139],\r\n\t\"darkolivegreen\": [85, 107, 47],\r\n\t\"darkorange\": [255, 140, 0],\r\n\t\"darkorchid\": [153, 50, 204],\r\n\t\"darkred\": [139, 0, 0],\r\n\t\"darksalmon\": [233, 150, 122],\r\n\t\"darkseagreen\": [143, 188, 143],\r\n\t\"darkslateblue\": [72, 61, 139],\r\n\t\"darkslategray\": [47, 79, 79],\r\n\t\"darkslategrey\": [47, 79, 79],\r\n\t\"darkturquoise\": [0, 206, 209],\r\n\t\"darkviolet\": [148, 0, 211],\r\n\t\"deeppink\": [255, 20, 147],\r\n\t\"deepskyblue\": [0, 191, 255],\r\n\t\"dimgray\": [105, 105, 105],\r\n\t\"dimgrey\": [105, 105, 105],\r\n\t\"dodgerblue\": [30, 144, 255],\r\n\t\"firebrick\": [178, 34, 34],\r\n\t\"floralwhite\": [255, 250, 240],\r\n\t\"forestgreen\": [34, 139, 34],\r\n\t\"fuchsia\": [255, 0, 255],\r\n\t\"gainsboro\": [220, 220, 220],\r\n\t\"ghostwhite\": [248, 248, 255],\r\n\t\"gold\": [255, 215, 0],\r\n\t\"goldenrod\": [218, 165, 32],\r\n\t\"gray\": [128, 128, 128],\r\n\t\"green\": [0, 128, 0],\r\n\t\"greenyellow\": [173, 255, 47],\r\n\t\"grey\": [128, 128, 128],\r\n\t\"honeydew\": [240, 255, 240],\r\n\t\"hotpink\": [255, 105, 180],\r\n\t\"indianred\": [205, 92, 92],\r\n\t\"indigo\": [75, 0, 130],\r\n\t\"ivory\": [255, 255, 240],\r\n\t\"khaki\": [240, 230, 140],\r\n\t\"lavender\": [230, 230, 250],\r\n\t\"lavenderblush\": [255, 240, 245],\r\n\t\"lawngreen\": [124, 252, 0],\r\n\t\"lemonchiffon\": [255, 250, 205],\r\n\t\"lightblue\": [173, 216, 230],\r\n\t\"lightcoral\": [240, 128, 128],\r\n\t\"lightcyan\": [224, 255, 255],\r\n\t\"lightgoldenrodyellow\": [250, 250, 210],\r\n\t\"lightgray\": [211, 211, 211],\r\n\t\"lightgreen\": [144, 238, 144],\r\n\t\"lightgrey\": [211, 211, 211],\r\n\t\"lightpink\": [255, 182, 193],\r\n\t\"lightsalmon\": [255, 160, 122],\r\n\t\"lightseagreen\": [32, 178, 170],\r\n\t\"lightskyblue\": [135, 206, 250],\r\n\t\"lightslategray\": [119, 136, 153],\r\n\t\"lightslategrey\": [119, 136, 153],\r\n\t\"lightsteelblue\": [176, 196, 222],\r\n\t\"lightyellow\": [255, 255, 224],\r\n\t\"lime\": [0, 255, 0],\r\n\t\"limegreen\": [50, 205, 50],\r\n\t\"linen\": [250, 240, 230],\r\n\t\"magenta\": [255, 0, 255],\r\n\t\"maroon\": [128, 0, 0],\r\n\t\"mediumaquamarine\": [102, 205, 170],\r\n\t\"mediumblue\": [0, 0, 205],\r\n\t\"mediumorchid\": [186, 85, 211],\r\n\t\"mediumpurple\": [147, 112, 219],\r\n\t\"mediumseagreen\": [60, 179, 113],\r\n\t\"mediumslateblue\": [123, 104, 238],\r\n\t\"mediumspringgreen\": [0, 250, 154],\r\n\t\"mediumturquoise\": [72, 209, 204],\r\n\t\"mediumvioletred\": [199, 21, 133],\r\n\t\"midnightblue\": [25, 25, 112],\r\n\t\"mintcream\": [245, 255, 250],\r\n\t\"mistyrose\": [255, 228, 225],\r\n\t\"moccasin\": [255, 228, 181],\r\n\t\"navajowhite\": [255, 222, 173],\r\n\t\"navy\": [0, 0, 128],\r\n\t\"oldlace\": [253, 245, 230],\r\n\t\"olive\": [128, 128, 0],\r\n\t\"olivedrab\": [107, 142, 35],\r\n\t\"orange\": [255, 165, 0],\r\n\t\"orangered\": [255, 69, 0],\r\n\t\"orchid\": [218, 112, 214],\r\n\t\"palegoldenrod\": [238, 232, 170],\r\n\t\"palegreen\": [152, 251, 152],\r\n\t\"paleturquoise\": [175, 238, 238],\r\n\t\"palevioletred\": [219, 112, 147],\r\n\t\"papayawhip\": [255, 239, 213],\r\n\t\"peachpuff\": [255, 218, 185],\r\n\t\"peru\": [205, 133, 63],\r\n\t\"pink\": [255, 192, 203],\r\n\t\"plum\": [221, 160, 221],\r\n\t\"powderblue\": [176, 224, 230],\r\n\t\"purple\": [128, 0, 128],\r\n\t\"rebeccapurple\": [102, 51, 153],\r\n\t\"red\": [255, 0, 0],\r\n\t\"rosybrown\": [188, 143, 143],\r\n\t\"royalblue\": [65, 105, 225],\r\n\t\"saddlebrown\": [139, 69, 19],\r\n\t\"salmon\": [250, 128, 114],\r\n\t\"sandybrown\": [244, 164, 96],\r\n\t\"seagreen\": [46, 139, 87],\r\n\t\"seashell\": [255, 245, 238],\r\n\t\"sienna\": [160, 82, 45],\r\n\t\"silver\": [192, 192, 192],\r\n\t\"skyblue\": [135, 206, 235],\r\n\t\"slateblue\": [106, 90, 205],\r\n\t\"slategray\": [112, 128, 144],\r\n\t\"slategrey\": [112, 128, 144],\r\n\t\"snow\": [255, 250, 250],\r\n\t\"springgreen\": [0, 255, 127],\r\n\t\"steelblue\": [70, 130, 180],\r\n\t\"tan\": [210, 180, 140],\r\n\t\"teal\": [0, 128, 128],\r\n\t\"thistle\": [216, 191, 216],\r\n\t\"tomato\": [255, 99, 71],\r\n\t\"turquoise\": [64, 224, 208],\r\n\t\"violet\": [238, 130, 238],\r\n\t\"wheat\": [245, 222, 179],\r\n\t\"white\": [255, 255, 255],\r\n\t\"whitesmoke\": [245, 245, 245],\r\n\t\"yellow\": [255, 255, 0],\r\n\t\"yellowgreen\": [154, 205, 50]\r\n};\r\n","'use strict';\nconst os = require('os');\nconst hasFlag = require('has-flag');\n\nconst env = process.env;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false')) {\n\tforceColor = false;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = true;\n}\nif ('FORCE_COLOR' in env) {\n\tforceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(stream) {\n\tif (forceColor === false) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (stream && !stream.isTTY && forceColor !== true) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor ? 1 : 0;\n\n\tif (process.platform === 'win32') {\n\t\t// Node.js 7.5.0 is the first version of Node.js to include a patch to\n\t\t// libuv that enables 256 color output on Windows. Anything earlier and it\n\t\t// won't work. However, here we target Node.js 8 at minimum as it is an LTS\n\t\t// release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows\n\t\t// release that supports 256 colors. Windows 10 build 14931 is the first release\n\t\t// that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(process.versions.node.split('.')[0]) >= 8 &&\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: getSupportLevel(process.stdout),\n\tstderr: getSupportLevel(process.stderr)\n};\n","'use strict'\n\nvar errSerializer = require('./lib/err')\nvar reqSerializers = require('./lib/req')\nvar resSerializers = require('./lib/res')\n\nmodule.exports = {\n err: errSerializer,\n mapHttpRequest: reqSerializers.mapHttpRequest,\n mapHttpResponse: resSerializers.mapHttpResponse,\n req: reqSerializers.reqSerializer,\n res: resSerializers.resSerializer,\n\n wrapErrorSerializer: function wrapErrorSerializer (customSerializer) {\n if (customSerializer === errSerializer) return customSerializer\n return function wrapErrSerializer (err) {\n return customSerializer(errSerializer(err))\n }\n },\n\n wrapRequestSerializer: function wrapRequestSerializer (customSerializer) {\n if (customSerializer === reqSerializers.reqSerializer) return customSerializer\n return function wrappedReqSerializer (req) {\n return customSerializer(reqSerializers.reqSerializer(req))\n }\n },\n\n wrapResponseSerializer: function wrapResponseSerializer (customSerializer) {\n if (customSerializer === resSerializers.resSerializer) return customSerializer\n return function wrappedResSerializer (res) {\n return customSerializer(resSerializers.resSerializer(res))\n }\n }\n}\n","'use strict'\n\nmodule.exports = errSerializer\n\nconst seen = Symbol('circular-ref-tag')\nconst rawSymbol = Symbol('pino-raw-err-ref')\nconst pinoErrProto = Object.create({}, {\n type: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n message: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n stack: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoErrProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction errSerializer (err) {\n if (!(err instanceof Error)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = err.constructor.name\n _err.message = err.message\n _err.stack = err.stack\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (val instanceof Error) {\n if (!val.hasOwnProperty(seen)) {\n _err[key] = errSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n","'use strict'\n\nmodule.exports = {\n mapHttpRequest,\n reqSerializer\n}\n\nvar rawSymbol = Symbol('pino-raw-req-ref')\nvar pinoReqProto = Object.create({}, {\n id: {\n enumerable: true,\n writable: true,\n value: ''\n },\n method: {\n enumerable: true,\n writable: true,\n value: ''\n },\n url: {\n enumerable: true,\n writable: true,\n value: ''\n },\n headers: {\n enumerable: true,\n writable: true,\n value: {}\n },\n remoteAddress: {\n enumerable: true,\n writable: true,\n value: ''\n },\n remotePort: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoReqProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction reqSerializer (req) {\n // req.info is for hapi compat.\n var connection = req.info || req.connection\n const _req = Object.create(pinoReqProto)\n _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined)))\n _req.method = req.method\n // req.originalUrl is for expressjs compat.\n if (req.originalUrl) {\n _req.url = req.originalUrl\n } else {\n // req.url.path is for hapi compat.\n _req.url = req.path || (req.url ? (req.url.path || req.url) : undefined)\n }\n _req.headers = req.headers\n _req.remoteAddress = connection && connection.remoteAddress\n _req.remotePort = connection && connection.remotePort\n // req.raw is for hapi compat/equivalence\n _req.raw = req.raw || req\n return _req\n}\n\nfunction mapHttpRequest (req) {\n return {\n req: reqSerializer(req)\n }\n}\n","'use strict'\n\nmodule.exports = {\n mapHttpResponse,\n resSerializer\n}\n\nvar rawSymbol = Symbol('pino-raw-res-ref')\nvar pinoResProto = Object.create({}, {\n statusCode: {\n enumerable: true,\n writable: true,\n value: 0\n },\n headers: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoResProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction resSerializer (res) {\n const _res = Object.create(pinoResProto)\n _res.statusCode = res.statusCode\n _res.headers = res.getHeaders ? res.getHeaders() : res._headers\n _res.raw = res\n return _res\n}\n\nfunction mapHttpResponse (res) {\n return {\n res: resSerializer(res)\n }\n}\n","'use strict'\nconst flatstr = require('flatstr')\nconst {\n lsCacheSym,\n levelValSym,\n useLevelLabelsSym,\n levelKeySym,\n useOnlyCustomLevelsSym,\n streamSym\n} = require('./symbols')\nconst { noop, genLog } = require('./tools')\n\nconst levels = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60\n}\nconst logFatal = genLog(levels.fatal)\nconst levelMethods = {\n fatal (...args) {\n const stream = this[streamSym]\n logFatal.call(this, ...args)\n if (typeof stream.flushSync === 'function') {\n try {\n stream.flushSync()\n } catch (e) {\n // https://github.com/pinojs/pino/pull/740#discussion_r346788313\n }\n }\n },\n error: genLog(levels.error),\n warn: genLog(levels.warn),\n info: genLog(levels.info),\n debug: genLog(levels.debug),\n trace: genLog(levels.trace)\n}\n\nconst nums = Object.keys(levels).reduce((o, k) => {\n o[levels[k]] = k\n return o\n}, {})\n\nconst initialLsCache = Object.keys(nums).reduce((o, k) => {\n o[k] = flatstr('{\"level\":' + Number(k))\n return o\n}, {})\n\nfunction genLsCache (instance) {\n const levelName = instance[levelKeySym]\n instance[lsCacheSym] = Object.keys(instance.levels.labels).reduce((o, k) => {\n o[k] = instance[useLevelLabelsSym]\n ? `{\"${levelName}\":\"${instance.levels.labels[k]}\"`\n : flatstr(`{\"${levelName}\":` + Number(k))\n return o\n }, Object.assign({}, instance[lsCacheSym]))\n return instance\n}\n\nfunction isStandardLevel (level, useOnlyCustomLevels) {\n if (useOnlyCustomLevels) {\n return false\n }\n\n switch (level) {\n case 'fatal':\n case 'error':\n case 'warn':\n case 'info':\n case 'debug':\n case 'trace':\n return true\n default:\n return false\n }\n}\n\nfunction setLevel (level) {\n const { labels, values } = this.levels\n if (typeof level === 'number') {\n if (labels[level] === undefined) throw Error('unknown level value' + level)\n level = labels[level]\n }\n if (values[level] === undefined) throw Error('unknown level ' + level)\n const preLevelVal = this[levelValSym]\n const levelVal = this[levelValSym] = values[level]\n const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]\n\n for (var key in values) {\n if (levelVal > values[key]) {\n this[key] = noop\n continue\n }\n this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key] : genLog(values[key])\n }\n\n this.emit(\n 'level-change',\n level,\n levelVal,\n labels[preLevelVal],\n preLevelVal\n )\n}\n\nfunction getLevel (level) {\n const { levels, levelVal } = this\n return levels.labels[levelVal]\n}\n\nfunction isLevelEnabled (logLevel) {\n const { values } = this.levels\n const logLevelVal = values[logLevel]\n return logLevelVal !== undefined && (logLevelVal >= this[levelValSym])\n}\n\nfunction mappings (customLevels = null, useOnlyCustomLevels = false) {\n const customNums = customLevels ? Object.keys(customLevels).reduce((o, k) => {\n o[customLevels[k]] = k\n return o\n }, {}) : null\n\n const labels = Object.assign(\n Object.create(Object.prototype, { Infinity: { value: 'silent' } }),\n useOnlyCustomLevels ? null : nums,\n customNums\n )\n const values = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : levels,\n customLevels\n )\n return { labels, values }\n}\n\nfunction assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) {\n if (typeof defaultLevel === 'number') {\n const values = [].concat(\n Object.keys(customLevels || {}).map(key => customLevels[key]),\n useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level),\n Infinity\n )\n if (!values.includes(defaultLevel)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n return\n }\n\n const labels = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : levels,\n customLevels\n )\n if (!(defaultLevel in labels)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n}\n\nfunction assertNoLevelCollisions (levels, customLevels) {\n const { labels, values } = levels\n for (const k in customLevels) {\n if (k in values) {\n throw Error('levels cannot be overridden')\n }\n if (customLevels[k] in labels) {\n throw Error('pre-existing level values cannot be used for new levels')\n }\n }\n}\n\nmodule.exports = {\n initialLsCache,\n genLsCache,\n levelMethods,\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n assertNoLevelCollisions,\n assertDefaultLevelFound\n}\n","'use strict'\n\nconst { version } = require('../package.json')\n\nconst LOG_VERSION = 1\n\nmodule.exports = { version, LOG_VERSION }\n","'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst { EventEmitter } = require('events')\nconst SonicBoom = require('sonic-boom')\nconst flatstr = require('flatstr')\nconst {\n lsCacheSym,\n levelValSym,\n setLevelSym,\n getLevelSym,\n chindingsSym,\n mixinSym,\n asJsonSym,\n messageKeySym,\n writeSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n serializersSym,\n useOnlyCustomLevelsSym,\n needsMetadataGsym\n} = require('./symbols')\nconst {\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n initialLsCache,\n genLsCache,\n assertNoLevelCollisions\n} = require('./levels')\nconst {\n asChindings,\n asJson\n} = require('./tools')\nconst {\n version,\n LOG_VERSION\n} = require('./meta')\n\n// note: use of class is satirical\n// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127\nconst constructor = class Pino {}\nconst prototype = {\n constructor,\n child,\n bindings,\n setBindings,\n flush,\n isLevelEnabled,\n version,\n get level () { return this[getLevelSym]() },\n set level (lvl) { return this[setLevelSym](lvl) },\n get levelVal () { return this[levelValSym] },\n set levelVal (n) { throw Error('levelVal is read-only') },\n [lsCacheSym]: initialLsCache,\n [writeSym]: write,\n [asJsonSym]: asJson,\n [getLevelSym]: getLevel,\n [setLevelSym]: setLevel,\n LOG_VERSION\n}\n\nObject.setPrototypeOf(prototype, EventEmitter.prototype)\n\nmodule.exports = prototype\n\nfunction child (bindings) {\n const { level } = this\n const serializers = this[serializersSym]\n const chindings = asChindings(this, bindings)\n const instance = Object.create(this)\n if (bindings.hasOwnProperty('serializers') === true) {\n instance[serializersSym] = Object.create(null)\n\n for (var k in serializers) {\n instance[serializersSym][k] = serializers[k]\n }\n const parentSymbols = Object.getOwnPropertySymbols(serializers)\n for (var i = 0; i < parentSymbols.length; i++) {\n const ks = parentSymbols[i]\n instance[serializersSym][ks] = serializers[ks]\n }\n\n for (var bk in bindings.serializers) {\n instance[serializersSym][bk] = bindings.serializers[bk]\n }\n const bindingsSymbols = Object.getOwnPropertySymbols(bindings.serializers)\n for (var bi = 0; bi < bindingsSymbols.length; bi++) {\n const bks = bindingsSymbols[bi]\n instance[serializersSym][bks] = bindings.serializers[bks]\n }\n } else instance[serializersSym] = serializers\n if (bindings.hasOwnProperty('customLevels') === true) {\n assertNoLevelCollisions(this.levels, bindings.customLevels)\n instance.levels = mappings(bindings.customLevels, instance[useOnlyCustomLevelsSym])\n genLsCache(instance)\n }\n instance[chindingsSym] = chindings\n const childLevel = bindings.level || level\n instance[setLevelSym](childLevel)\n\n return instance\n}\n\nfunction bindings () {\n const chindings = this[chindingsSym]\n var chindingsJson = `{${chindings.substr(1)}}` // at least contains ,\"pid\":7068,\"hostname\":\"myMac\"\n var bindingsFromJson = JSON.parse(chindingsJson)\n delete bindingsFromJson.pid\n delete bindingsFromJson.hostname\n return bindingsFromJson\n}\n\nfunction setBindings (newBindings) {\n const chindings = asChindings(this, newBindings)\n this[chindingsSym] = chindings\n}\n\nfunction write (_obj, msg, num) {\n const t = this[timeSym]()\n const messageKey = this[messageKeySym]\n const mixin = this[mixinSym]\n const objError = _obj instanceof Error\n var obj\n\n if (_obj === undefined || _obj === null) {\n obj = mixin ? mixin() : {}\n obj[messageKey] = msg\n } else {\n obj = Object.assign(mixin ? mixin() : {}, _obj)\n if (msg) {\n obj[messageKey] = msg\n } else if (objError) {\n obj[messageKey] = _obj.message\n }\n\n if (objError) {\n obj.stack = _obj.stack\n if (!obj.type) {\n obj.type = 'Error'\n }\n }\n }\n\n const s = this[asJsonSym](obj, num, t)\n\n const stream = this[streamSym]\n if (stream[needsMetadataGsym] === true) {\n stream.lastLevel = num\n // TODO remove in the next major release,\n // it is not needed anymore\n stream.lastMsg = msg\n stream.lastObj = obj\n stream.lastTime = t.slice(this[timeSliceIndexSym])\n stream.lastLogger = this // for child loggers\n }\n if (stream instanceof SonicBoom) stream.write(s)\n else stream.write(flatstr(s))\n}\n\nfunction flush () {\n const stream = this[streamSym]\n if ('flush' in stream) stream.flush()\n}\n","'use strict'\n\nconst fastRedact = require('fast-redact')\nconst { redactFmtSym, wildcardFirstSym } = require('./symbols')\nconst { rx, validator } = fastRedact\n\nconst validate = validator({\n ERR_PATHS_MUST_BE_STRINGS: () => 'pino – redacted paths must be strings',\n ERR_INVALID_PATH: (s) => `pino – redact paths array contains an invalid path (${s})`\n})\n\nconst CENSOR = '[Redacted]'\nconst strict = false // TODO should this be configurable?\n\nfunction redaction (opts, serialize) {\n const { paths, censor } = handle(opts)\n\n const shape = paths.reduce((o, str) => {\n rx.lastIndex = 0\n const first = rx.exec(str)\n const next = rx.exec(str)\n\n // ns is the top-level path segment, brackets + quoting removed.\n let ns = first[1] !== undefined\n ? first[1].replace(/^(?:\"|'|`)(.*)(?:\"|'|`)$/, '$1')\n : first[0]\n\n if (ns === '*') {\n ns = wildcardFirstSym\n }\n\n // top level key:\n if (next === null) {\n o[ns] = null\n return o\n }\n\n // path with at least two segments:\n // if ns is already redacted at the top level, ignore lower level redactions\n if (o[ns] === null) {\n return o\n }\n\n const { index } = next\n const nextPath = `${str.substr(index, str.length - 1)}`\n\n o[ns] = o[ns] || []\n\n // shape is a mix of paths beginning with literal values and wildcard\n // paths [ \"a.b.c\", \"*.b.z\" ] should reduce to a shape of\n // { \"a\": [ \"b.c\", \"b.z\" ], *: [ \"b.z\" ] }\n // note: \"b.z\" is in both \"a\" and * arrays because \"a\" matches the wildcard.\n // (* entry has wildcardFirstSym as key)\n if (ns !== wildcardFirstSym && o[ns].length === 0) {\n // first time ns's get all '*' redactions so far\n o[ns].push(...(o[wildcardFirstSym] || []))\n }\n\n if (ns === wildcardFirstSym) {\n // new * path gets added to all previously registered literal ns's.\n Object.keys(o).forEach(function (k) {\n if (o[k]) {\n o[k].push(nextPath)\n }\n })\n }\n\n o[ns].push(nextPath)\n return o\n }, {})\n\n // the redactor assigned to the format symbol key\n // provides top level redaction for instances where\n // an object is interpolated into the msg string\n const result = {\n [redactFmtSym]: fastRedact({ paths, censor, serialize, strict })\n }\n\n const topCensor = (...args) =>\n typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor)\n\n return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => {\n // top level key:\n if (shape[k] === null) o[k] = topCensor\n else o[k] = fastRedact({ paths: shape[k], censor, serialize, strict })\n return o\n }, result)\n}\n\nfunction handle (opts) {\n if (Array.isArray(opts)) {\n opts = { paths: opts, censor: CENSOR }\n validate(opts)\n return opts\n }\n var { paths, censor = CENSOR, remove } = opts\n if (Array.isArray(paths) === false) { throw Error('pino – redact must contain an array of strings') }\n if (remove === true) censor = undefined\n validate({ paths, censor })\n\n return { paths, censor }\n}\n\nmodule.exports = redaction\n","'use strict'\n\nconst setLevelSym = Symbol('pino.setLevel')\nconst getLevelSym = Symbol('pino.getLevel')\nconst levelValSym = Symbol('pino.levelVal')\nconst useLevelLabelsSym = Symbol('pino.useLevelLabels')\nconst levelKeySym = Symbol('pino.levelKey')\nconst useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels')\nconst mixinSym = Symbol('pino.mixin')\n\nconst lsCacheSym = Symbol('pino.lsCache')\nconst chindingsSym = Symbol('pino.chindings')\nconst parsedChindingsSym = Symbol('pino.parsedChindings')\n\nconst asJsonSym = Symbol('pino.asJson')\nconst writeSym = Symbol('pino.write')\nconst redactFmtSym = Symbol('pino.redactFmt')\n\nconst timeSym = Symbol('pino.time')\nconst timeSliceIndexSym = Symbol('pino.timeSliceIndex')\nconst streamSym = Symbol('pino.stream')\nconst stringifySym = Symbol('pino.stringify')\nconst stringifiersSym = Symbol('pino.stringifiers')\nconst endSym = Symbol('pino.end')\nconst formatOptsSym = Symbol('pino.formatOpts')\nconst messageKeySym = Symbol('pino.messageKey')\nconst nestedKeySym = Symbol('pino.nestedKey')\n\nconst wildcardFirstSym = Symbol('pino.wildcardFirst')\n\n// public symbols, no need to use the same pino\n// version for these\nconst serializersSym = Symbol.for('pino.serializers')\nconst wildcardGsym = Symbol.for('pino.*')\nconst needsMetadataGsym = Symbol.for('pino.metadata')\n\nmodule.exports = {\n setLevelSym,\n getLevelSym,\n levelValSym,\n useLevelLabelsSym,\n mixinSym,\n lsCacheSym,\n chindingsSym,\n parsedChindingsSym,\n asJsonSym,\n writeSym,\n serializersSym,\n redactFmtSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifiersSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n nestedKeySym,\n wildcardFirstSym,\n levelKeySym,\n wildcardGsym,\n needsMetadataGsym,\n useOnlyCustomLevelsSym\n}\n","'use strict'\n\nconst nullTime = () => ''\n\nconst epochTime = () => `,\"time\":${Date.now()}`\n\nconst unixTime = () => `,\"time\":${Math.round(Date.now() / 1000.0)}`\n\nconst isoTime = () => `,\"time\":\"${new Date(Date.now()).toISOString()}\"` // using Date.now() for testability\n\nmodule.exports = { nullTime, epochTime, unixTime, isoTime }\n","'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst format = require('quick-format-unescaped')\nconst { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers')\nconst SonicBoom = require('sonic-boom')\nconst stringifySafe = require('fast-safe-stringify')\nconst {\n lsCacheSym,\n chindingsSym,\n parsedChindingsSym,\n writeSym,\n serializersSym,\n formatOptsSym,\n endSym,\n stringifiersSym,\n stringifySym,\n wildcardFirstSym,\n needsMetadataGsym,\n wildcardGsym,\n redactFmtSym,\n streamSym,\n nestedKeySym\n} = require('./symbols')\n\nfunction noop () {}\n\nfunction genLog (z) {\n return function LOG (o, ...n) {\n if (typeof o === 'object' && o !== null) {\n if (o.method && o.headers && o.socket) {\n o = mapHttpRequest(o)\n } else if (typeof o.setHeader === 'function') {\n o = mapHttpResponse(o)\n }\n if (this[nestedKeySym]) o = { [this[nestedKeySym]]: o }\n this[writeSym](o, format(null, n, this[formatOptsSym]), z)\n } else this[writeSym](null, format(o, n, this[formatOptsSym]), z)\n }\n}\n\n// magically escape strings for json\n// relying on their charCodeAt\n// everything below 32 needs JSON.stringify()\n// 34 and 92 happens all the time, so we\n// have a fast case for them\nfunction asString (str) {\n var result = ''\n var last = 0\n var found = false\n var point = 255\n const l = str.length\n if (l > 100) {\n return JSON.stringify(str)\n }\n for (var i = 0; i < l && point >= 32; i++) {\n point = str.charCodeAt(i)\n if (point === 34 || point === 92) {\n result += str.slice(last, i) + '\\\\'\n last = i\n found = true\n }\n }\n if (!found) {\n result = str\n } else {\n result += str.slice(last)\n }\n return point < 32 ? JSON.stringify(str) : '\"' + result + '\"'\n}\n\nfunction asJson (obj, num, time) {\n const stringify = this[stringifySym]\n const stringifiers = this[stringifiersSym]\n const end = this[endSym]\n const chindings = this[chindingsSym]\n const serializers = this[serializersSym]\n var data = this[lsCacheSym][num] + time\n\n // we need the child bindings added to the output first so instance logged\n // objects can take precedence when JSON.parse-ing the resulting log line\n data = data + chindings\n\n var value\n var notHasOwnProperty = obj.hasOwnProperty === undefined\n if (serializers[wildcardGsym]) {\n obj = serializers[wildcardGsym](obj)\n }\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n for (var key in obj) {\n value = obj[key]\n if ((notHasOwnProperty || obj.hasOwnProperty(key)) && value !== undefined) {\n value = serializers[key] ? serializers[key](value) : value\n\n const stringifier = stringifiers[key] || wildcardStringifier\n\n switch (typeof value) {\n case 'undefined':\n case 'function':\n continue\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicity falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n break\n case 'string':\n value = (stringifier || asString)(value)\n break\n default:\n value = (stringifier || stringify)(value)\n }\n if (value === undefined) continue\n data += ',\"' + key + '\":' + value\n }\n }\n\n return data + end\n}\n\nfunction asChindings (instance, bindings) {\n if (!bindings) {\n throw Error('missing bindings for child Pino')\n }\n var key\n var value\n var data = instance[chindingsSym]\n const stringify = instance[stringifySym]\n const stringifiers = instance[stringifiersSym]\n const serializers = instance[serializersSym]\n if (serializers[wildcardGsym]) {\n bindings = serializers[wildcardGsym](bindings)\n }\n for (key in bindings) {\n value = bindings[key]\n const valid = key !== 'level' &&\n key !== 'serializers' &&\n key !== 'customLevels' &&\n bindings.hasOwnProperty(key) &&\n value !== undefined\n if (valid === true) {\n value = serializers[key] ? serializers[key](value) : value\n value = (stringifiers[key] || stringify)(value)\n if (value === undefined) continue\n data += ',\"' + key + '\":' + value\n }\n }\n return data\n}\n\nfunction getPrettyStream (opts, prettifier, dest, instance) {\n if (prettifier && typeof prettifier === 'function') {\n prettifier = prettifier.bind(instance)\n return prettifierMetaWrapper(prettifier(opts), dest)\n }\n try {\n var prettyFactory = require('pino-pretty')\n prettyFactory.asMetaWrapper = prettifierMetaWrapper\n return prettifierMetaWrapper(prettyFactory(opts), dest)\n } catch (e) {\n throw Error('Missing `pino-pretty` module: `pino-pretty` must be installed separately')\n }\n}\n\nfunction prettifierMetaWrapper (pretty, dest) {\n var warned = false\n return {\n [needsMetadataGsym]: true,\n lastLevel: 0,\n lastMsg: null,\n lastObj: null,\n lastLogger: null,\n flushSync () {\n if (warned) {\n return\n }\n warned = true\n setMetadataProps(dest, this)\n dest.write(pretty(Object.assign({\n level: 40, // warn\n msg: 'pino.final with prettyPrint does not support flushing',\n time: Date.now()\n }, this.chindings())))\n },\n chindings () {\n const lastLogger = this.lastLogger\n var chindings = null\n\n // protection against flushSync being called before logging\n // anything\n if (!lastLogger) {\n return null\n }\n\n if (lastLogger.hasOwnProperty(parsedChindingsSym)) {\n chindings = lastLogger[parsedChindingsSym]\n } else {\n chindings = JSON.parse('{\"v\":1' + lastLogger[chindingsSym] + '}')\n lastLogger[parsedChindingsSym] = chindings\n }\n\n return chindings\n },\n write (chunk) {\n const lastLogger = this.lastLogger\n const chindings = this.chindings()\n\n var time = this.lastTime\n\n if (time.match(/^\\d+/)) {\n time = parseInt(time)\n }\n\n var lastObj = this.lastObj\n var errorProps = null\n\n const obj = Object.assign({\n level: this.lastLevel,\n time\n }, chindings, lastObj, errorProps)\n\n const serializers = lastLogger[serializersSym]\n const keys = Object.keys(serializers)\n var key\n\n for (var i = 0; i < keys.length; i++) {\n key = keys[i]\n if (obj[key] !== undefined) {\n obj[key] = serializers[key](obj[key])\n }\n }\n\n const stringifiers = lastLogger[stringifiersSym]\n const redact = stringifiers[redactFmtSym]\n\n const formatted = pretty(typeof redact === 'function' ? redact(obj) : obj)\n if (formatted === undefined) return\n\n setMetadataProps(dest, this)\n dest.write(formatted)\n }\n }\n}\n\nfunction hasBeenTampered (stream) {\n return stream.write !== stream.constructor.prototype.write\n}\n\nfunction buildSafeSonicBoom (dest, buffer = 0, sync = true) {\n const stream = new SonicBoom(dest, buffer, sync)\n stream.on('error', filterBrokenPipe)\n return stream\n\n function filterBrokenPipe (err) {\n // TODO verify on Windows\n if (err.code === 'EPIPE') {\n // If we get EPIPE, we should stop logging here\n // however we have no control to the consumer of\n // SonicBoom, so we just overwrite the write method\n stream.write = noop\n stream.end = noop\n stream.flushSync = noop\n stream.destroy = noop\n return\n }\n stream.removeListener('error', filterBrokenPipe)\n stream.emit('error', err)\n }\n}\n\nfunction createArgsNormalizer (defaultOptions) {\n return function normalizeArgs (instance, opts = {}, stream) {\n // support stream as a string\n if (typeof opts === 'string') {\n stream = buildSafeSonicBoom(opts)\n opts = {}\n } else if (typeof stream === 'string') {\n stream = buildSafeSonicBoom(stream)\n } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) {\n stream = opts\n opts = null\n }\n opts = Object.assign({}, defaultOptions, opts)\n if ('extreme' in opts) {\n throw Error('The extreme option has been removed, use pino.extreme instead')\n }\n if ('onTerminated' in opts) {\n throw Error('The onTerminated option has been removed, use pino.final instead')\n }\n if ('changeLevelName' in opts) {\n process.emitWarning(\n 'The changeLevelName option is deprecated and will be removed in v7. Use levelKey instead.',\n { code: 'changeLevelName_deprecation' }\n )\n opts.levelKey = opts.changeLevelName\n delete opts.changeLevelName\n }\n const { enabled, prettyPrint, prettifier, messageKey } = opts\n if (enabled === false) opts.level = 'silent'\n stream = stream || process.stdout\n if (stream === process.stdout && stream.fd >= 0 && !hasBeenTampered(stream)) {\n stream = buildSafeSonicBoom(stream.fd)\n }\n if (prettyPrint) {\n const prettyOpts = Object.assign({ messageKey }, prettyPrint)\n stream = getPrettyStream(prettyOpts, prettifier, stream, instance)\n }\n return { opts, stream }\n }\n}\n\nfunction final (logger, handler) {\n if (typeof logger === 'undefined' || typeof logger.child !== 'function') {\n throw Error('expected a pino logger instance')\n }\n const hasHandler = (typeof handler !== 'undefined')\n if (hasHandler && typeof handler !== 'function') {\n throw Error('if supplied, the handler parameter should be a function')\n }\n const stream = logger[streamSym]\n if (typeof stream.flushSync !== 'function') {\n throw Error('final requires a stream that has a flushSync method, such as pino.destination and pino.extreme')\n }\n\n const finalLogger = new Proxy(logger, {\n get: (logger, key) => {\n if (key in logger.levels.values) {\n return (...args) => {\n logger[key](...args)\n stream.flushSync()\n }\n }\n return logger[key]\n }\n })\n\n if (!hasHandler) {\n return finalLogger\n }\n\n return (err = null, ...args) => {\n try {\n stream.flushSync()\n } catch (e) {\n // it's too late to wait for the stream to be ready\n // because this is a final tick scenario.\n // in practice there shouldn't be a situation where it isn't\n // however, swallow the error just in case (and for easier testing)\n }\n return handler(err, finalLogger, ...args)\n }\n}\n\nfunction stringify (obj) {\n try {\n return JSON.stringify(obj)\n } catch (_) {\n return stringifySafe(obj)\n }\n}\n\nfunction setMetadataProps (dest, that) {\n if (dest[needsMetadataGsym] === true) {\n dest.lastLevel = that.lastLevel\n dest.lastMsg = that.lastMsg\n dest.lastObj = that.lastObj\n dest.lastTime = that.lastTime\n dest.lastLogger = that.lastLogger\n }\n}\n\nmodule.exports = {\n noop,\n buildSafeSonicBoom,\n getPrettyStream,\n asChindings,\n asJson,\n genLog,\n createArgsNormalizer,\n final,\n stringify\n}\n","'use strict'\nconst os = require('os')\nconst stdSerializers = require('pino-std-serializers')\nconst redaction = require('./lib/redaction')\nconst time = require('./lib/time')\nconst proto = require('./lib/proto')\nconst symbols = require('./lib/symbols')\nconst { assertDefaultLevelFound, mappings, genLsCache } = require('./lib/levels')\nconst {\n createArgsNormalizer,\n asChindings,\n final,\n stringify,\n buildSafeSonicBoom\n} = require('./lib/tools')\nconst { version, LOG_VERSION } = require('./lib/meta')\nconst {\n chindingsSym,\n redactFmtSym,\n serializersSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifiersSym,\n setLevelSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n nestedKeySym,\n useLevelLabelsSym,\n levelKeySym,\n mixinSym,\n useOnlyCustomLevelsSym\n} = symbols\nconst { epochTime, nullTime } = time\nconst { pid } = process\nconst hostname = os.hostname()\nconst defaultErrorSerializer = stdSerializers.err\nconst defaultOptions = {\n level: 'info',\n useLevelLabels: false,\n messageKey: 'msg',\n nestedKey: null,\n enabled: true,\n prettyPrint: false,\n base: { pid, hostname },\n serializers: Object.assign(Object.create(null), {\n err: defaultErrorSerializer\n }),\n timestamp: epochTime,\n name: undefined,\n redact: null,\n customLevels: null,\n levelKey: 'level',\n useOnlyCustomLevels: false\n}\n\nconst normalize = createArgsNormalizer(defaultOptions)\n\nconst serializers = Object.assign(Object.create(null), stdSerializers)\n\nfunction pino (...args) {\n const instance = {}\n const { opts, stream } = normalize(instance, ...args)\n const {\n redact,\n crlf,\n serializers,\n timestamp,\n messageKey,\n nestedKey,\n base,\n name,\n level,\n customLevels,\n useLevelLabels,\n levelKey,\n mixin,\n useOnlyCustomLevels\n } = opts\n\n const stringifiers = redact ? redaction(redact, stringify) : {}\n const formatOpts = redact\n ? { stringify: stringifiers[redactFmtSym] }\n : { stringify }\n const end = ',\"v\":' + LOG_VERSION + '}' + (crlf ? '\\r\\n' : '\\n')\n const coreChindings = asChindings.bind(null, {\n [chindingsSym]: '',\n [serializersSym]: serializers,\n [stringifiersSym]: stringifiers,\n [stringifySym]: stringify\n })\n const chindings = base === null ? '' : (name === undefined)\n ? coreChindings(base) : coreChindings(Object.assign({}, base, { name }))\n const time = (timestamp instanceof Function)\n ? timestamp : (timestamp ? epochTime : nullTime)\n const timeSliceIndex = time().indexOf(':') + 1\n\n if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')\n if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type \"${typeof mixin}\" - expected \"function\"`)\n\n assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels)\n const levels = mappings(customLevels, useOnlyCustomLevels)\n\n Object.assign(instance, {\n levels,\n [useLevelLabelsSym]: useLevelLabels,\n [levelKeySym]: levelKey,\n [useOnlyCustomLevelsSym]: useOnlyCustomLevels,\n [streamSym]: stream,\n [timeSym]: time,\n [timeSliceIndexSym]: timeSliceIndex,\n [stringifySym]: stringify,\n [stringifiersSym]: stringifiers,\n [endSym]: end,\n [formatOptsSym]: formatOpts,\n [messageKeySym]: messageKey,\n [nestedKeySym]: nestedKey,\n [serializersSym]: serializers,\n [mixinSym]: mixin,\n [chindingsSym]: chindings\n })\n Object.setPrototypeOf(instance, proto)\n\n if (customLevels || useLevelLabels || levelKey !== defaultOptions.levelKey) genLsCache(instance)\n\n instance[setLevelSym](level)\n\n return instance\n}\n\npino.extreme = (dest = process.stdout.fd) => buildSafeSonicBoom(dest, 4096, false)\npino.destination = (dest = process.stdout.fd) => buildSafeSonicBoom(dest, 0, true)\n\npino.final = final\npino.levels = mappings()\npino.stdSerializers = serializers\npino.stdTimeFunctions = Object.assign({}, time)\npino.symbols = symbols\npino.version = version\npino.LOG_VERSION = LOG_VERSION\n\nmodule.exports = pino\n","'use strict';\n\nif (typeof process === 'undefined' ||\n !process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = { nextTick: nextTick };\n} else {\n module.exports = process\n}\n\nfunction nextTick(fn, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n","'use strict'\nfunction tryStringify (o) {\n try { return JSON.stringify(o) } catch(e) { return '\"[Circular]\"' }\n}\n\nmodule.exports = format \n\nfunction format(f, args, opts) {\n var ss = (opts && opts.stringify) || tryStringify\n var offset = 1\n if (f === null) {\n f = args[0]\n offset = 0\n }\n if (typeof f === 'object' && f !== null) {\n var len = args.length + offset\n if (len === 1) return f\n var objects = new Array(len)\n objects[0] = ss(f)\n for (var index = 1; index < len; index++) {\n objects[index] = ss(args[index])\n }\n return objects.join(' ')\n }\n var argLen = args.length\n if (argLen === 0) return f\n var x = ''\n var str = ''\n var a = 1 - offset\n var lastPos = 0\n var flen = (f && f.length) || 0\n for (var i = 0; i < flen;) {\n if (f.charCodeAt(i) === 37 && i + 1 < flen) {\n switch (f.charCodeAt(i + 1)) {\n case 100: // 'd'\n if (a >= argLen)\n break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n if (args[a] == null) break\n str += Number(args[a])\n lastPos = i = i + 2\n break\n case 79: // 'O'\n case 111: // 'o'\n case 106: // 'j'\n if (a >= argLen)\n break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n if (args[a] === undefined) break\n var type = typeof args[a]\n if (type === 'string') {\n str += '\\'' + args[a] + '\\''\n lastPos = i + 2\n i++\n break\n }\n if (type === 'function') {\n str += args[a].name || ''\n lastPos = i + 2\n i++\n break\n }\n str += ss(args[a])\n lastPos = i + 2\n i++\n break\n case 115: // 's'\n if (a >= argLen)\n break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += String(args[a])\n lastPos = i + 2\n i++\n break\n case 37: // '%'\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += '%'\n lastPos = i + 2\n i++\n break\n }\n ++a\n }\n ++i\n }\n if (lastPos === 0)\n str = f\n else if (lastPos < flen) {\n str += f.slice(lastPos)\n }\n while (a < argLen) {\n x = args[a++]\n if (x === null || (typeof x !== 'object')) {\n str += ' ' + String(x)\n } else {\n str += ' ' + ss(x)\n }\n }\n\n return str\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\n/**/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/**/\n\nmodule.exports = Duplex;\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n\n pna.nextTick(cb, err);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\nmodule.exports = Readable;\n\n/**/\nvar isArray = require('isarray');\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n\n/**/\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar debugUtil = require('util');\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/**/\n\nvar BufferList = require('./internal/streams/BufferList');\nvar destroyImpl = require('./internal/streams/destroy');\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n 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]];\n}\n\nfunction ReadableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n if (!(this instanceof Readable)) return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\n\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n\n return needMoreData(state);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', src._readableState.awaitDrain);\n src._readableState.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = { hasUnpiped: false };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, unpipeInfo);\n }return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this, unpipeInfo);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n 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);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict';\n\nmodule.exports = Transform;\n\nvar Duplex = require('./_stream_duplex');\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n\n cb(er);\n\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\nmodule.exports = Writable;\n\n/* */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n 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);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /**/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /**/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending && !state.finished) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n if (state.corkedRequestsFree) {\n state.corkedRequestsFree.next = corkReq;\n } else {\n state.corkedRequestsFree = corkReq;\n }\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\n\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};","'use strict';\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar Buffer = require('safe-buffer').Buffer;\nvar util = require('util');\n\nfunction copyBuffer(src, target, offset) {\n src.copy(target, offset);\n}\n\nmodule.exports = function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n BufferList.prototype.push = function push(v) {\n var entry = { data: v, next: null };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n };\n\n BufferList.prototype.unshift = function unshift(v) {\n var entry = { data: v, next: this.head };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n };\n\n BufferList.prototype.shift = function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n };\n\n BufferList.prototype.clear = function clear() {\n this.head = this.tail = null;\n this.length = 0;\n };\n\n BufferList.prototype.join = function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }return ret;\n };\n\n BufferList.prototype.concat = function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n if (this.length === 1) return this.head.data;\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n };\n\n return BufferList;\n}();\n\nif (util && util.inspect && util.inspect.custom) {\n module.exports.prototype[util.inspect.custom] = function () {\n var obj = util.inspect({ length: this.length });\n return this.constructor.name + ' ' + obj;\n };\n}","'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {\n pna.nextTick(emitErrorNT, this, err);\n }\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n pna.nextTick(emitErrorNT, _this, err);\n if (_this._writableState) {\n _this._writableState.errorEmitted = true;\n }\n } else if (cb) {\n cb(err);\n }\n });\n\n return this;\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};","module.exports = require('stream');\n","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream;\n exports = module.exports = Stream.Readable;\n exports.Readable = Stream.Readable;\n exports.Writable = Stream.Writable;\n exports.Duplex = Stream.Duplex;\n exports.Transform = Stream.Transform;\n exports.PassThrough = Stream.PassThrough;\n exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n}\n","'use strict';\n\nvar fs = require('fs'),\n join = require('path').join,\n resolve = require('path').resolve,\n dirname = require('path').dirname,\n defaultOptions = {\n extensions: ['js', 'json', 'coffee'],\n recurse: true,\n rename: function (name) {\n return name;\n },\n visit: function (obj) {\n return obj;\n }\n };\n\nfunction checkFileInclusion(path, filename, options) {\n return (\n // verify file has valid extension\n (new RegExp('\\\\.(' + options.extensions.join('|') + ')$', 'i').test(filename)) &&\n\n // if options.include is a RegExp, evaluate it and make sure the path passes\n !(options.include && options.include instanceof RegExp && !options.include.test(path)) &&\n\n // if options.include is a function, evaluate it and make sure the path passes\n !(options.include && typeof options.include === 'function' && !options.include(path, filename)) &&\n\n // if options.exclude is a RegExp, evaluate it and make sure the path doesn't pass\n !(options.exclude && options.exclude instanceof RegExp && options.exclude.test(path)) &&\n\n // if options.exclude is a function, evaluate it and make sure the path doesn't pass\n !(options.exclude && typeof options.exclude === 'function' && options.exclude(path, filename))\n );\n}\n\nfunction requireDirectory(m, path, options) {\n var retval = {};\n\n // path is optional\n if (path && !options && typeof path !== 'string') {\n options = path;\n path = null;\n }\n\n // default options\n options = options || {};\n for (var prop in defaultOptions) {\n if (typeof options[prop] === 'undefined') {\n options[prop] = defaultOptions[prop];\n }\n }\n\n // if no path was passed in, assume the equivelant of __dirname from caller\n // otherwise, resolve path relative to the equivalent of __dirname\n path = !path ? dirname(m.filename) : resolve(dirname(m.filename), path);\n\n // get the path of each file in specified directory, append to current tree node, recurse\n fs.readdirSync(path).forEach(function (filename) {\n var joined = join(path, filename),\n files,\n key,\n obj;\n\n if (fs.statSync(joined).isDirectory() && options.recurse) {\n // this node is a directory; recurse\n files = requireDirectory(m, joined, options);\n // exclude empty directories\n if (Object.keys(files).length) {\n retval[options.rename(filename, joined, filename)] = files;\n }\n } else {\n if (joined !== m.filename && checkFileInclusion(joined, filename, options)) {\n // hash node key shouldn't include file extension\n key = filename.substring(0, filename.lastIndexOf('.'));\n obj = m.require(joined);\n retval[options.rename(key, joined, filename)] = options.visit(obj, joined, filename) || obj;\n }\n }\n });\n\n return retval;\n}\n\nmodule.exports = requireDirectory;\nmodule.exports.defaults = defaultOptions;\n",null,null,"'use strict';\nvar path = require('path');\nvar Module = require('module');\n\nmodule.exports = function (fromDir, moduleId) {\n\tif (typeof fromDir !== 'string' || typeof moduleId !== 'string') {\n\t\tthrow new TypeError('Expected `fromDir` and `moduleId` to be a string');\n\t}\n\n\tfromDir = path.resolve(fromDir);\n\n\tvar fromFile = path.join(fromDir, 'noop.js');\n\n\ttry {\n\t\treturn Module._resolveFilename(moduleId, {\n\t\t\tid: fromFile,\n\t\t\tfilename: fromFile,\n\t\t\tpaths: Module._nodeModulePaths(fromDir)\n\t\t});\n\t} catch (err) {\n\t\treturn null;\n\t}\n};\n","/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","'use strict';\n\nconst {\n unassigned_code_points,\n commonly_mapped_to_nothing,\n non_ASCII_space_characters,\n prohibited_characters,\n bidirectional_r_al,\n bidirectional_l,\n} = require('./lib/memory-code-points');\n\nmodule.exports = saslprep;\n\n// 2.1. Mapping\n\n/**\n * non-ASCII space characters [StringPrep, C.1.2] that can be\n * mapped to SPACE (U+0020)\n */\nconst mapping2space = non_ASCII_space_characters;\n\n/**\n * the \"commonly mapped to nothing\" characters [StringPrep, B.1]\n * that can be mapped to nothing.\n */\nconst mapping2nothing = commonly_mapped_to_nothing;\n\n// utils\nconst getCodePoint = character => character.codePointAt(0);\nconst first = x => x[0];\nconst last = x => x[x.length - 1];\n\n/**\n * Convert provided string into an array of Unicode Code Points.\n * Based on https://stackoverflow.com/a/21409165/1556249\n * and https://www.npmjs.com/package/code-point-at.\n * @param {string} input\n * @returns {number[]}\n */\nfunction toCodePoints(input) {\n const codepoints = [];\n const size = input.length;\n\n for (let i = 0; i < size; i += 1) {\n const before = input.charCodeAt(i);\n\n if (before >= 0xd800 && before <= 0xdbff && size > i + 1) {\n const next = input.charCodeAt(i + 1);\n\n if (next >= 0xdc00 && next <= 0xdfff) {\n codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000);\n i += 1;\n continue;\n }\n }\n\n codepoints.push(before);\n }\n\n return codepoints;\n}\n\n/**\n * SASLprep.\n * @param {string} input\n * @param {Object} opts\n * @param {boolean} opts.allowUnassigned\n * @returns {string}\n */\nfunction saslprep(input, opts = {}) {\n if (typeof input !== 'string') {\n throw new TypeError('Expected string.');\n }\n\n if (input.length === 0) {\n return '';\n }\n\n // 1. Map\n const mapped_input = toCodePoints(input)\n // 1.1 mapping to space\n .map(character => (mapping2space.get(character) ? 0x20 : character))\n // 1.2 mapping to nothing\n .filter(character => !mapping2nothing.get(character));\n\n // 2. Normalize\n const normalized_input = String.fromCodePoint\n .apply(null, mapped_input)\n .normalize('NFKC');\n\n const normalized_map = toCodePoints(normalized_input);\n\n // 3. Prohibit\n const hasProhibited = normalized_map.some(character =>\n prohibited_characters.get(character)\n );\n\n if (hasProhibited) {\n throw new Error(\n 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3'\n );\n }\n\n // Unassigned Code Points\n if (opts.allowUnassigned !== true) {\n const hasUnassigned = normalized_map.some(character =>\n unassigned_code_points.get(character)\n );\n\n if (hasUnassigned) {\n throw new Error(\n 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5'\n );\n }\n }\n\n // 4. check bidi\n\n const hasBidiRAL = normalized_map.some(character =>\n bidirectional_r_al.get(character)\n );\n\n const hasBidiL = normalized_map.some(character =>\n bidirectional_l.get(character)\n );\n\n // 4.1 If a string contains any RandALCat character, the string MUST NOT\n // contain any LCat character.\n if (hasBidiRAL && hasBidiL) {\n throw new Error(\n 'String must not contain RandALCat and LCat at the same time,' +\n ' see https://tools.ietf.org/html/rfc3454#section-6'\n );\n }\n\n /**\n * 4.2 If a string contains any RandALCat character, a RandALCat\n * character MUST be the first character of the string, and a\n * RandALCat character MUST be the last character of the string.\n */\n\n const isFirstBidiRAL = bidirectional_r_al.get(\n getCodePoint(first(normalized_input))\n );\n const isLastBidiRAL = bidirectional_r_al.get(\n getCodePoint(last(normalized_input))\n );\n\n if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) {\n throw new Error(\n 'Bidirectional RandALCat character must be the first and the last' +\n ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6'\n );\n }\n\n return normalized_input;\n}\n",null,"exports = module.exports = SemVer\n\nvar debug\n/* istanbul ignore next */\nif (typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)) {\n debug = function () {\n var args = Array.prototype.slice.call(arguments, 0)\n args.unshift('SEMVER')\n console.log.apply(console, args)\n }\n} else {\n debug = function () {}\n}\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nexports.SEMVER_SPEC_VERSION = '2.0.0'\n\nvar MAX_LENGTH = 256\nvar MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n /* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nvar MAX_SAFE_COMPONENT_LENGTH = 16\n\n// The actual regexps go on exports.re\nvar re = exports.re = []\nvar src = exports.src = []\nvar R = 0\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\nvar NUMERICIDENTIFIER = R++\nsrc[NUMERICIDENTIFIER] = '0|[1-9]\\\\d*'\nvar NUMERICIDENTIFIERLOOSE = R++\nsrc[NUMERICIDENTIFIERLOOSE] = '[0-9]+'\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\nvar NONNUMERICIDENTIFIER = R++\nsrc[NONNUMERICIDENTIFIER] = '\\\\d*[a-zA-Z-][a-zA-Z0-9-]*'\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\nvar MAINVERSION = R++\nsrc[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\\\.' +\n '(' + src[NUMERICIDENTIFIER] + ')\\\\.' +\n '(' + src[NUMERICIDENTIFIER] + ')'\n\nvar MAINVERSIONLOOSE = R++\nsrc[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\\\.' +\n '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\\\.' +\n '(' + src[NUMERICIDENTIFIERLOOSE] + ')'\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n\nvar PRERELEASEIDENTIFIER = R++\nsrc[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] +\n '|' + src[NONNUMERICIDENTIFIER] + ')'\n\nvar PRERELEASEIDENTIFIERLOOSE = R++\nsrc[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] +\n '|' + src[NONNUMERICIDENTIFIER] + ')'\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\nvar PRERELEASE = R++\nsrc[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] +\n '(?:\\\\.' + src[PRERELEASEIDENTIFIER] + ')*))'\n\nvar PRERELEASELOOSE = R++\nsrc[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] +\n '(?:\\\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\nvar BUILDIDENTIFIER = R++\nsrc[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\nvar BUILD = R++\nsrc[BUILD] = '(?:\\\\+(' + src[BUILDIDENTIFIER] +\n '(?:\\\\.' + src[BUILDIDENTIFIER] + ')*))'\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\nvar FULL = R++\nvar FULLPLAIN = 'v?' + src[MAINVERSION] +\n src[PRERELEASE] + '?' +\n src[BUILD] + '?'\n\nsrc[FULL] = '^' + FULLPLAIN + '$'\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\nvar LOOSEPLAIN = '[v=\\\\s]*' + src[MAINVERSIONLOOSE] +\n src[PRERELEASELOOSE] + '?' +\n src[BUILD] + '?'\n\nvar LOOSE = R++\nsrc[LOOSE] = '^' + LOOSEPLAIN + '$'\n\nvar GTLT = R++\nsrc[GTLT] = '((?:<|>)?=?)'\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\nvar XRANGEIDENTIFIERLOOSE = R++\nsrc[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\\\*'\nvar XRANGEIDENTIFIER = R++\nsrc[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\\\*'\n\nvar XRANGEPLAIN = R++\nsrc[XRANGEPLAIN] = '[v=\\\\s]*(' + src[XRANGEIDENTIFIER] + ')' +\n '(?:\\\\.(' + src[XRANGEIDENTIFIER] + ')' +\n '(?:\\\\.(' + src[XRANGEIDENTIFIER] + ')' +\n '(?:' + src[PRERELEASE] + ')?' +\n src[BUILD] + '?' +\n ')?)?'\n\nvar XRANGEPLAINLOOSE = R++\nsrc[XRANGEPLAINLOOSE] = '[v=\\\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:\\\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:\\\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:' + src[PRERELEASELOOSE] + ')?' +\n src[BUILD] + '?' +\n ')?)?'\n\nvar XRANGE = R++\nsrc[XRANGE] = '^' + src[GTLT] + '\\\\s*' + src[XRANGEPLAIN] + '$'\nvar XRANGELOOSE = R++\nsrc[XRANGELOOSE] = '^' + src[GTLT] + '\\\\s*' + src[XRANGEPLAINLOOSE] + '$'\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\nvar COERCE = R++\nsrc[COERCE] = '(?:^|[^\\\\d])' +\n '(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +\n '(?:\\\\.(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +\n '(?:\\\\.(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +\n '(?:$|[^\\\\d])'\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\nvar LONETILDE = R++\nsrc[LONETILDE] = '(?:~>?)'\n\nvar TILDETRIM = R++\nsrc[TILDETRIM] = '(\\\\s*)' + src[LONETILDE] + '\\\\s+'\nre[TILDETRIM] = new RegExp(src[TILDETRIM], 'g')\nvar tildeTrimReplace = '$1~'\n\nvar TILDE = R++\nsrc[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'\nvar TILDELOOSE = R++\nsrc[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\nvar LONECARET = R++\nsrc[LONECARET] = '(?:\\\\^)'\n\nvar CARETTRIM = R++\nsrc[CARETTRIM] = '(\\\\s*)' + src[LONECARET] + '\\\\s+'\nre[CARETTRIM] = new RegExp(src[CARETTRIM], 'g')\nvar caretTrimReplace = '$1^'\n\nvar CARET = R++\nsrc[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'\nvar CARETLOOSE = R++\nsrc[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\nvar COMPARATORLOOSE = R++\nsrc[COMPARATORLOOSE] = '^' + src[GTLT] + '\\\\s*(' + LOOSEPLAIN + ')$|^$'\nvar COMPARATOR = R++\nsrc[COMPARATOR] = '^' + src[GTLT] + '\\\\s*(' + FULLPLAIN + ')$|^$'\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\nvar COMPARATORTRIM = R++\nsrc[COMPARATORTRIM] = '(\\\\s*)' + src[GTLT] +\n '\\\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'\n\n// this one has to use the /g flag\nre[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g')\nvar comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\nvar HYPHENRANGE = R++\nsrc[HYPHENRANGE] = '^\\\\s*(' + src[XRANGEPLAIN] + ')' +\n '\\\\s+-\\\\s+' +\n '(' + src[XRANGEPLAIN] + ')' +\n '\\\\s*$'\n\nvar HYPHENRANGELOOSE = R++\nsrc[HYPHENRANGELOOSE] = '^\\\\s*(' + src[XRANGEPLAINLOOSE] + ')' +\n '\\\\s+-\\\\s+' +\n '(' + src[XRANGEPLAINLOOSE] + ')' +\n '\\\\s*$'\n\n// Star ranges basically just allow anything at all.\nvar STAR = R++\nsrc[STAR] = '(<|>)?=?\\\\s*\\\\*'\n\n// Compile to actual regexp objects.\n// All are flag-free, unless they were created above with a flag.\nfor (var i = 0; i < R; i++) {\n debug(i, src[i])\n if (!re[i]) {\n re[i] = new RegExp(src[i])\n }\n}\n\nexports.parse = parse\nfunction parse (version, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n if (version.length > MAX_LENGTH) {\n return null\n }\n\n var r = options.loose ? re[LOOSE] : re[FULL]\n if (!r.test(version)) {\n return null\n }\n\n try {\n return new SemVer(version, options)\n } catch (er) {\n return null\n }\n}\n\nexports.valid = valid\nfunction valid (version, options) {\n var v = parse(version, options)\n return v ? v.version : null\n}\n\nexports.clean = clean\nfunction clean (version, options) {\n var s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\n\nexports.SemVer = SemVer\n\nfunction SemVer (version, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n if (version instanceof SemVer) {\n if (version.loose === options.loose) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError('Invalid Version: ' + version)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')\n }\n\n if (!(this instanceof SemVer)) {\n return new SemVer(version, options)\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n\n var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL])\n\n if (!m) {\n throw new TypeError('Invalid Version: ' + version)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map(function (id) {\n if (/^[0-9]+$/.test(id)) {\n var num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n}\n\nSemVer.prototype.format = function () {\n this.version = this.major + '.' + this.minor + '.' + this.patch\n if (this.prerelease.length) {\n this.version += '-' + this.prerelease.join('.')\n }\n return this.version\n}\n\nSemVer.prototype.toString = function () {\n return this.version\n}\n\nSemVer.prototype.compare = function (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return this.compareMain(other) || this.comparePre(other)\n}\n\nSemVer.prototype.compareMain = function (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return compareIdentifiers(this.major, other.major) ||\n compareIdentifiers(this.minor, other.minor) ||\n compareIdentifiers(this.patch, other.patch)\n}\n\nSemVer.prototype.comparePre = function (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n var i = 0\n do {\n var a = this.prerelease[i]\n var b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n}\n\n// preminor will bump the version up to the next minor release, and immediately\n// down to pre-release. premajor and prepatch work the same way.\nSemVer.prototype.inc = function (release, identifier) {\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier)\n this.inc('pre', identifier)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier)\n }\n this.inc('pre', identifier)\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 \"pre\" would become 1.0.0-0 which is the wrong direction.\n case 'pre':\n if (this.prerelease.length === 0) {\n this.prerelease = [0]\n } else {\n var i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n this.prerelease.push(0)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n if (this.prerelease[0] === identifier) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = [identifier, 0]\n }\n } else {\n this.prerelease = [identifier, 0]\n }\n }\n break\n\n default:\n throw new Error('invalid increment argument: ' + release)\n }\n this.format()\n this.raw = this.version\n return this\n}\n\nexports.inc = inc\nfunction inc (version, release, loose, identifier) {\n if (typeof (loose) === 'string') {\n identifier = loose\n loose = undefined\n }\n\n try {\n return new SemVer(version, loose).inc(release, identifier).version\n } catch (er) {\n return null\n }\n}\n\nexports.diff = diff\nfunction diff (version1, version2) {\n if (eq(version1, version2)) {\n return null\n } else {\n var v1 = parse(version1)\n var v2 = parse(version2)\n var prefix = ''\n if (v1.prerelease.length || v2.prerelease.length) {\n prefix = 'pre'\n var defaultResult = 'prerelease'\n }\n for (var key in v1) {\n if (key === 'major' || key === 'minor' || key === 'patch') {\n if (v1[key] !== v2[key]) {\n return prefix + key\n }\n }\n }\n return defaultResult // may be undefined\n }\n}\n\nexports.compareIdentifiers = compareIdentifiers\n\nvar numeric = /^[0-9]+$/\nfunction compareIdentifiers (a, b) {\n var anum = numeric.test(a)\n var bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nexports.rcompareIdentifiers = rcompareIdentifiers\nfunction rcompareIdentifiers (a, b) {\n return compareIdentifiers(b, a)\n}\n\nexports.major = major\nfunction major (a, loose) {\n return new SemVer(a, loose).major\n}\n\nexports.minor = minor\nfunction minor (a, loose) {\n return new SemVer(a, loose).minor\n}\n\nexports.patch = patch\nfunction patch (a, loose) {\n return new SemVer(a, loose).patch\n}\n\nexports.compare = compare\nfunction compare (a, b, loose) {\n return new SemVer(a, loose).compare(new SemVer(b, loose))\n}\n\nexports.compareLoose = compareLoose\nfunction compareLoose (a, b) {\n return compare(a, b, true)\n}\n\nexports.rcompare = rcompare\nfunction rcompare (a, b, loose) {\n return compare(b, a, loose)\n}\n\nexports.sort = sort\nfunction sort (list, loose) {\n return list.sort(function (a, b) {\n return exports.compare(a, b, loose)\n })\n}\n\nexports.rsort = rsort\nfunction rsort (list, loose) {\n return list.sort(function (a, b) {\n return exports.rcompare(a, b, loose)\n })\n}\n\nexports.gt = gt\nfunction gt (a, b, loose) {\n return compare(a, b, loose) > 0\n}\n\nexports.lt = lt\nfunction lt (a, b, loose) {\n return compare(a, b, loose) < 0\n}\n\nexports.eq = eq\nfunction eq (a, b, loose) {\n return compare(a, b, loose) === 0\n}\n\nexports.neq = neq\nfunction neq (a, b, loose) {\n return compare(a, b, loose) !== 0\n}\n\nexports.gte = gte\nfunction gte (a, b, loose) {\n return compare(a, b, loose) >= 0\n}\n\nexports.lte = lte\nfunction lte (a, b, loose) {\n return compare(a, b, loose) <= 0\n}\n\nexports.cmp = cmp\nfunction cmp (a, op, b, loose) {\n switch (op) {\n case '===':\n if (typeof a === 'object')\n a = a.version\n if (typeof b === 'object')\n b = b.version\n return a === b\n\n case '!==':\n if (typeof a === 'object')\n a = a.version\n if (typeof b === 'object')\n b = b.version\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError('Invalid operator: ' + op)\n }\n}\n\nexports.Comparator = Comparator\nfunction Comparator (comp, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n if (!(this instanceof Comparator)) {\n return new Comparator(comp, options)\n }\n\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n}\n\nvar ANY = {}\nComparator.prototype.parse = function (comp) {\n var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]\n var m = comp.match(r)\n\n if (!m) {\n throw new TypeError('Invalid comparator: ' + comp)\n }\n\n this.operator = m[1]\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n}\n\nComparator.prototype.toString = function () {\n return this.value\n}\n\nComparator.prototype.test = function (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n version = new SemVer(version, this.options)\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n}\n\nComparator.prototype.intersects = function (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n var rangeTmp\n\n if (this.operator === '') {\n rangeTmp = new Range(comp.value, options)\n return satisfies(this.value, rangeTmp, options)\n } else if (comp.operator === '') {\n rangeTmp = new Range(this.value, options)\n return satisfies(comp.semver, rangeTmp, options)\n }\n\n var sameDirectionIncreasing =\n (this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '>=' || comp.operator === '>')\n var sameDirectionDecreasing =\n (this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '<=' || comp.operator === '<')\n var sameSemVer = this.semver.version === comp.semver.version\n var differentDirectionsInclusive =\n (this.operator === '>=' || this.operator === '<=') &&\n (comp.operator === '>=' || comp.operator === '<=')\n var oppositeDirectionsLessThan =\n cmp(this.semver, '<', comp.semver, options) &&\n ((this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '<=' || comp.operator === '<'))\n var oppositeDirectionsGreaterThan =\n cmp(this.semver, '>', comp.semver, options) &&\n ((this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '>=' || comp.operator === '>'))\n\n return sameDirectionIncreasing || sameDirectionDecreasing ||\n (sameSemVer && differentDirectionsInclusive) ||\n oppositeDirectionsLessThan || oppositeDirectionsGreaterThan\n}\n\nexports.Range = Range\nfunction Range (range, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (range instanceof Range) {\n if (range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n return new Range(range.value, options)\n }\n\n if (!(this instanceof Range)) {\n return new Range(range, options)\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First, split based on boolean or ||\n this.raw = range\n this.set = range.split(/\\s*\\|\\|\\s*/).map(function (range) {\n return this.parseRange(range.trim())\n }, this).filter(function (c) {\n // throw out any that are not relevant for whatever reason\n return c.length\n })\n\n if (!this.set.length) {\n throw new TypeError('Invalid SemVer Range: ' + range)\n }\n\n this.format()\n}\n\nRange.prototype.format = function () {\n this.range = this.set.map(function (comps) {\n return comps.join(' ').trim()\n }).join('||').trim()\n return this.range\n}\n\nRange.prototype.toString = function () {\n return this.range\n}\n\nRange.prototype.parseRange = function (range) {\n var loose = this.options.loose\n range = range.trim()\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]\n range = range.replace(hr, hyphenReplace)\n debug('hyphen replace', range)\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range, re[COMPARATORTRIM])\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[TILDETRIM], tildeTrimReplace)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[CARETTRIM], caretTrimReplace)\n\n // normalize spaces\n range = range.split(/\\s+/).join(' ')\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]\n var set = range.split(' ').map(function (comp) {\n return parseComparator(comp, this.options)\n }, this).join(' ').split(/\\s+/)\n if (this.options.loose) {\n // in loose mode, throw out any that are not valid comparators\n set = set.filter(function (comp) {\n return !!comp.match(compRe)\n })\n }\n set = set.map(function (comp) {\n return new Comparator(comp, this.options)\n }, this)\n\n return set\n}\n\nRange.prototype.intersects = function (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some(function (thisComparators) {\n return thisComparators.every(function (thisComparator) {\n return range.set.some(function (rangeComparators) {\n return rangeComparators.every(function (rangeComparator) {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n })\n })\n}\n\n// Mostly just for testing and legacy API reasons\nexports.toComparators = toComparators\nfunction toComparators (range, options) {\n return new Range(range, options).set.map(function (comp) {\n return comp.map(function (c) {\n return c.value\n }).join(' ').trim().split(' ')\n })\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nfunction parseComparator (comp, options) {\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nfunction isX (id) {\n return !id || id.toLowerCase() === 'x' || id === '*'\n}\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0\nfunction replaceTildes (comp, options) {\n return comp.trim().split(/\\s+/).map(function (comp) {\n return replaceTilde(comp, options)\n }).join(' ')\n}\n\nfunction replaceTilde (comp, options) {\n var r = options.loose ? re[TILDELOOSE] : re[TILDE]\n return comp.replace(r, function (_, M, m, p, pr) {\n debug('tilde', comp, _, M, m, p, pr)\n var ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + (+m + 1) + '.0'\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0\n// ^1.2.3 --> >=1.2.3 <2.0.0\n// ^1.2.0 --> >=1.2.0 <2.0.0\nfunction replaceCarets (comp, options) {\n return comp.trim().split(/\\s+/).map(function (comp) {\n return replaceCaret(comp, options)\n }).join(' ')\n}\n\nfunction replaceCaret (comp, options) {\n debug('caret', comp, options)\n var r = options.loose ? re[CARETLOOSE] : re[CARET]\n return comp.replace(r, function (_, M, m, p, pr) {\n debug('caret', comp, _, M, m, p, pr)\n var ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (isX(p)) {\n if (M === '0') {\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n } else {\n ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + m + '.' + (+p + 1)\n } else {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n } else {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + (+M + 1) + '.0.0'\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + m + '.' + (+p + 1)\n } else {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n } else {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + (+M + 1) + '.0.0'\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nfunction replaceXRanges (comp, options) {\n debug('replaceXRanges', comp, options)\n return comp.split(/\\s+/).map(function (comp) {\n return replaceXRange(comp, options)\n }).join(' ')\n}\n\nfunction replaceXRange (comp, options) {\n comp = comp.trim()\n var r = options.loose ? re[XRANGELOOSE] : re[XRANGE]\n return comp.replace(r, function (ret, gtlt, M, m, p, pr) {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n var xM = isX(M)\n var xm = xM || isX(m)\n var xp = xm || isX(p)\n var anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n // >1.2.3 => >= 1.2.4\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n ret = gtlt + M + '.' + m + '.' + p\n } else if (xm) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (xp) {\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nfunction replaceStars (comp, options) {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp.trim().replace(re[STAR], '')\n}\n\n// This function is passed to string.replace(re[HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0\nfunction hyphenReplace ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr, tb) {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = '>=' + fM + '.0.0'\n } else if (isX(fp)) {\n from = '>=' + fM + '.' + fm + '.0'\n } else {\n from = '>=' + from\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = '<' + (+tM + 1) + '.0.0'\n } else if (isX(tp)) {\n to = '<' + tM + '.' + (+tm + 1) + '.0'\n } else if (tpr) {\n to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr\n } else {\n to = '<=' + to\n }\n\n return (from + ' ' + to).trim()\n}\n\n// if ANY of the sets match ALL of its comparators, then pass\nRange.prototype.test = function (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n version = new SemVer(version, this.options)\n }\n\n for (var i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n}\n\nfunction testSet (set, version, options) {\n for (var i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n var allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n\nexports.satisfies = satisfies\nfunction satisfies (version, range, options) {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\n\nexports.maxSatisfying = maxSatisfying\nfunction maxSatisfying (versions, range, options) {\n var max = null\n var maxSV = null\n try {\n var rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach(function (v) {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\n\nexports.minSatisfying = minSatisfying\nfunction minSatisfying (versions, range, options) {\n var min = null\n var minSV = null\n try {\n var rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach(function (v) {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\n\nexports.minVersion = minVersion\nfunction minVersion (range, loose) {\n range = new Range(range, loose)\n\n var minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (var i = 0; i < range.set.length; ++i) {\n var comparators = range.set[i]\n\n comparators.forEach(function (comparator) {\n // Clone to avoid manipulating the comparator's semver object.\n var compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!minver || gt(minver, compver)) {\n minver = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error('Unexpected operation: ' + comparator.operator)\n }\n })\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\n\nexports.validRange = validRange\nfunction validRange (range, options) {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\n\n// Determine if version is less than all the versions possible in the range\nexports.ltr = ltr\nfunction ltr (version, range, options) {\n return outside(version, range, '<', options)\n}\n\n// Determine if version is greater than all the versions possible in the range.\nexports.gtr = gtr\nfunction gtr (version, range, options) {\n return outside(version, range, '>', options)\n}\n\nexports.outside = outside\nfunction outside (version, range, hilo, options) {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n var gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisifes the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (var i = 0; i < range.set.length; ++i) {\n var comparators = range.set[i]\n\n var high = null\n var low = null\n\n comparators.forEach(function (comparator) {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nexports.prerelease = prerelease\nfunction prerelease (version, options) {\n var parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\n\nexports.intersects = intersects\nfunction intersects (r1, r2, options) {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2)\n}\n\nexports.coerce = coerce\nfunction coerce (version) {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n var match = version.match(re[COERCE])\n\n if (match == null) {\n return null\n }\n\n return parse(match[1] +\n '.' + (match[2] || '0') +\n '.' + (match[3] || '0'))\n}\n","module.exports = function (blocking) {\n [process.stdout, process.stderr].forEach(function (stream) {\n if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') {\n stream._handle.setBlocking(blocking)\n }\n })\n}\n","'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst flatstr = require('flatstr')\nconst inherits = require('util').inherits\n\nconst BUSY_WRITE_TIMEOUT = 100\n\nconst sleep = require('atomic-sleep')\n\n// 16 MB - magic number\n// This constant ensures that SonicBoom only needs\n// 32 MB of free memory to run. In case of having 1GB+\n// of data to write, this prevents an out of memory\n// condition.\nconst MAX_WRITE = 16 * 1024 * 1024\n\nfunction openFile (file, sonic) {\n sonic._opening = true\n sonic._writing = true\n sonic.file = file\n fs.open(file, 'a', (err, fd) => {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n sonic.fd = fd\n sonic._reopening = false\n sonic._opening = false\n sonic._writing = false\n\n sonic.emit('ready')\n\n if (sonic._reopening) {\n return\n }\n\n // start\n var len = sonic._buf.length\n if (len > 0 && len > sonic.minLength && !sonic.destroyed) {\n actualWrite(sonic)\n }\n })\n}\n\nfunction SonicBoom (fd, minLength, sync) {\n if (!(this instanceof SonicBoom)) {\n return new SonicBoom(fd, minLength, sync)\n }\n\n this._buf = ''\n this.fd = -1\n this._writing = false\n this._writingBuf = ''\n this._ending = false\n this._reopening = false\n this._asyncDrainScheduled = false\n this.file = null\n this.destroyed = false\n this.sync = sync || false\n\n this.minLength = minLength || 0\n\n if (typeof fd === 'number') {\n this.fd = fd\n process.nextTick(() => this.emit('ready'))\n } else if (typeof fd === 'string') {\n openFile(fd, this)\n } else {\n throw new Error('SonicBoom supports only file descriptors and files')\n }\n\n this.release = (err, n) => {\n if (err) {\n if (err.code === 'EAGAIN') {\n if (this.sync) {\n // This error code should not happen in sync mode, because it is\n // not using the underlining operating system asynchronous functions.\n // However it happens, and so we handle it.\n // Ref: https://github.com/pinojs/pino/issues/783\n try {\n sleep(BUSY_WRITE_TIMEOUT)\n this.release(undefined, 0)\n } catch (err) {\n this.release(err)\n }\n } else {\n // Let's give the destination some time to process the chunk.\n setTimeout(() => {\n fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n }, BUSY_WRITE_TIMEOUT)\n }\n } else {\n this.emit('error', err)\n }\n return\n }\n\n if (this._writingBuf.length !== n) {\n this._writingBuf = this._writingBuf.slice(n)\n if (this.sync) {\n try {\n do {\n n = fs.writeSync(this.fd, this._writingBuf, 'utf8')\n this._writingBuf = this._writingBuf.slice(n)\n } while (this._writingBuf.length !== 0)\n } catch (err) {\n this.release(err)\n return\n }\n } else {\n fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n return\n }\n }\n\n this._writingBuf = ''\n\n if (this.destroyed) {\n return\n }\n\n var len = this._buf.length\n if (this._reopening) {\n this._writing = false\n this._reopening = false\n this.reopen()\n } else if (len > 0 && len > this.minLength) {\n actualWrite(this)\n } else if (this._ending) {\n if (len > 0) {\n actualWrite(this)\n } else {\n this._writing = false\n actualClose(this)\n }\n } else {\n this._writing = false\n if (this.sync) {\n if (!this._asyncDrainScheduled) {\n this._asyncDrainScheduled = true\n process.nextTick(emitDrain, this)\n }\n } else {\n this.emit('drain')\n }\n }\n }\n}\n\nfunction emitDrain (sonic) {\n sonic._asyncDrainScheduled = false\n sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nSonicBoom.prototype.write = function (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n this._buf += data\n var len = this._buf.length\n if (!this._writing && len > this.minLength) {\n actualWrite(this)\n }\n return len < 16384\n}\n\nSonicBoom.prototype.flush = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._writing || this.minLength <= 0) {\n return\n }\n\n actualWrite(this)\n}\n\nSonicBoom.prototype.reopen = function (file) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.reopen(file)\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n if (!this.file) {\n throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n }\n\n this._reopening = true\n\n if (this._writing) {\n return\n }\n\n fs.close(this.fd, (err) => {\n if (err) {\n return this.emit('error', err)\n }\n })\n\n openFile(file || this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.end()\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n this._ending = true\n\n if (!this._writing && this._buf.length > 0 && this.fd >= 0) {\n actualWrite(this)\n return\n }\n\n if (this._writing) {\n return\n }\n\n actualClose(this)\n}\n\nSonicBoom.prototype.flushSync = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (this._buf.length > 0) {\n fs.writeSync(this.fd, this._buf, 'utf8')\n this._buf = ''\n }\n}\n\nSonicBoom.prototype.destroy = function () {\n if (this.destroyed) {\n return\n }\n actualClose(this)\n}\n\nfunction actualWrite (sonic) {\n sonic._writing = true\n var buf = sonic._buf\n var release = sonic.release\n if (buf.length > MAX_WRITE) {\n buf = buf.slice(0, MAX_WRITE)\n sonic._buf = sonic._buf.slice(MAX_WRITE)\n } else {\n sonic._buf = ''\n }\n flatstr(buf)\n sonic._writingBuf = buf\n if (sonic.sync) {\n try {\n var written = fs.writeSync(sonic.fd, buf, 'utf8')\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n fs.write(sonic.fd, buf, 'utf8', release)\n }\n}\n\nfunction actualClose (sonic) {\n if (sonic.fd === -1) {\n sonic.once('ready', actualClose.bind(null, sonic))\n return\n }\n // TODO write a test to check if we are not leaking fds\n fs.close(sonic.fd, (err) => {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n if (sonic._ending && !sonic._writing) {\n sonic.emit('finish')\n }\n sonic.emit('close')\n })\n sonic.destroyed = true\n sonic._buf = ''\n}\n\nmodule.exports = SonicBoom\n","var pager = require('memory-pager')\n\nmodule.exports = Bitfield\n\nfunction Bitfield (opts) {\n if (!(this instanceof Bitfield)) return new Bitfield(opts)\n if (!opts) opts = {}\n if (Buffer.isBuffer(opts)) opts = {buffer: opts}\n\n this.pageOffset = opts.pageOffset || 0\n this.pageSize = opts.pageSize || 1024\n this.pages = opts.pages || pager(this.pageSize)\n\n this.byteLength = this.pages.length * this.pageSize\n this.length = 8 * this.byteLength\n\n if (!powerOfTwo(this.pageSize)) throw new Error('The page size should be a power of two')\n\n this._trackUpdates = !!opts.trackUpdates\n this._pageMask = this.pageSize - 1\n\n if (opts.buffer) {\n for (var i = 0; i < opts.buffer.length; i += this.pageSize) {\n this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize))\n }\n this.byteLength = opts.buffer.length\n this.length = 8 * this.byteLength\n }\n}\n\nBitfield.prototype.get = function (i) {\n var o = i & 7\n var j = (i - o) / 8\n\n return !!(this.getByte(j) & (128 >> o))\n}\n\nBitfield.prototype.getByte = function (i) {\n var o = i & this._pageMask\n var j = (i - o) / this.pageSize\n var page = this.pages.get(j, true)\n\n return page ? page.buffer[o + this.pageOffset] : 0\n}\n\nBitfield.prototype.set = function (i, v) {\n var o = i & 7\n var j = (i - o) / 8\n var b = this.getByte(j)\n\n return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o)))\n}\n\nBitfield.prototype.toBuffer = function () {\n var all = alloc(this.pages.length * this.pageSize)\n\n for (var i = 0; i < this.pages.length; i++) {\n var next = this.pages.get(i, true)\n var allOffset = i * this.pageSize\n if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize)\n }\n\n return all\n}\n\nBitfield.prototype.setByte = function (i, b) {\n var o = i & this._pageMask\n var j = (i - o) / this.pageSize\n var page = this.pages.get(j, false)\n\n o += this.pageOffset\n\n if (page.buffer[o] === b) return false\n page.buffer[o] = b\n\n if (i >= this.byteLength) {\n this.byteLength = i + 1\n this.length = this.byteLength * 8\n }\n\n if (this._trackUpdates) this.pages.updated(page)\n\n return true\n}\n\nfunction alloc (n) {\n if (Buffer.alloc) return Buffer.alloc(n)\n var b = new Buffer(n)\n b.fill(0)\n return b\n}\n\nfunction powerOfTwo (x) {\n return !(x & (x - 1))\n}\n","'use strict';\nconst stripAnsi = require('strip-ansi');\nconst isFullwidthCodePoint = require('is-fullwidth-code-point');\nconst emojiRegex = require('emoji-regex')();\n\nmodule.exports = input => {\n\tinput = input.replace(emojiRegex, ' ');\n\n\tif (typeof input !== 'string' || input.length === 0) {\n\t\treturn 0;\n\t}\n\n\tinput = stripAnsi(input);\n\n\tlet width = 0;\n\n\tfor (let i = 0; i < input.length; i++) {\n\t\tconst code = input.codePointAt(i);\n\n\t\t// Ignore control characters\n\t\tif (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore combining characters\n\t\tif (code >= 0x300 && code <= 0x36F) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Surrogates\n\t\tif (code > 0xFFFF) {\n\t\t\ti++;\n\t\t}\n\n\t\twidth += isFullwidthCodePoint(code) ? 2 : 1;\n\t}\n\n\treturn width;\n};\n","'use strict';\n\nmodule.exports = options => {\n\toptions = Object.assign({\n\t\tonlyFirst: false\n\t}, options);\n\n\tconst pattern = [\n\t\t'[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:[a-zA-Z\\\\d]*(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)',\n\t\t'(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-ntqry=><~]))'\n\t].join('|');\n\n\treturn new RegExp(pattern, options.onlyFirst ? undefined : 'g');\n};\n","'use strict';\nconst ansiRegex = require('ansi-regex');\n\nconst stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;\n\nmodule.exports = stripAnsi;\nmodule.exports.default = stripAnsi;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n 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':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n 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;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst yargs_1 = __importDefault(require(\"yargs\"));\nconst wrap = (yargs) => ({\n parse() {\n yargs.parse();\n },\n command(command, description, builder, handler) {\n return wrap(yargs.command(command, description, builder, handler));\n },\n});\nfunction cli(options = {}) {\n return wrap(yargs_1.default\n .demandCommand()\n .strict()\n .help()\n .options(options));\n}\nexports.cli = cli;\n//# sourceMappingURL=CLI.js.map","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst invariant_1 = __importDefault(require(\"invariant\"));\nexports.invariant = invariant_1.default;\n//# sourceMappingURL=Invariant.js.map","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst pino_1 = __importDefault(require(\"pino\"));\nlet forceMode = null;\nlet rootLogger = null;\nclass LoggerWrapper {\n constructor(parentLogger, name) {\n this.name = name;\n this.debug = (thing, ...args) => this.instance.debug(thing, ...args);\n this.info = (thing, ...args) => this.instance.info(thing, ...args);\n this.warn = (thing, ...args) => this.instance.warn(thing, ...args);\n this.error = (thing, ...args) => this.instance.error(thing, ...args);\n this.instance = parentLogger.child({ name });\n }\n child(name) {\n return new LoggerWrapper(this.instance, this.name + ':' + name);\n }\n}\nfunction logger(name) {\n if (!rootLogger) {\n rootLogger = pino_1.default({\n prettyPrint: forceMode === 'pretty' || (forceMode === null && process.stdout.isTTY)\n ? { translateTime: true }\n : false,\n });\n }\n return new LoggerWrapper(rootLogger, name);\n}\nexports.logger = logger;\nlogger.forcePretty = function () {\n forceMode = 'pretty';\n};\nlogger.forceJSON = function () {\n forceMode = 'json';\n};\n//# sourceMappingURL=Logging.js.map","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./CLI\"));\n__export(require(\"./Logging\"));\n__export(require(\"./Invariant\"));\n//# sourceMappingURL=index.js.map","'use strict';\n\nmodule.exports = options => {\n\toptions = Object.assign({\n\t\tonlyFirst: false\n\t}, options);\n\n\tconst pattern = [\n\t\t'[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:[a-zA-Z\\\\d]*(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)',\n\t\t'(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-ntqry=><~]))'\n\t].join('|');\n\n\treturn new RegExp(pattern, options.onlyFirst ? undefined : 'g');\n};\n","'use strict';\nconst colorConvert = require('color-convert');\n\nconst wrapAnsi16 = (fn, offset) => function () {\n\tconst code = fn.apply(colorConvert, arguments);\n\treturn `\\u001B[${code + offset}m`;\n};\n\nconst wrapAnsi256 = (fn, offset) => function () {\n\tconst code = fn.apply(colorConvert, arguments);\n\treturn `\\u001B[${38 + offset};5;${code}m`;\n};\n\nconst wrapAnsi16m = (fn, offset) => function () {\n\tconst rgb = fn.apply(colorConvert, arguments);\n\treturn `\\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;\n};\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\tconst styles = {\n\t\tmodifier: {\n\t\t\treset: [0, 0],\n\t\t\t// 21 isn't widely supported and 22 does the same thing\n\t\t\tbold: [1, 22],\n\t\t\tdim: [2, 22],\n\t\t\titalic: [3, 23],\n\t\t\tunderline: [4, 24],\n\t\t\tinverse: [7, 27],\n\t\t\thidden: [8, 28],\n\t\t\tstrikethrough: [9, 29]\n\t\t},\n\t\tcolor: {\n\t\t\tblack: [30, 39],\n\t\t\tred: [31, 39],\n\t\t\tgreen: [32, 39],\n\t\t\tyellow: [33, 39],\n\t\t\tblue: [34, 39],\n\t\t\tmagenta: [35, 39],\n\t\t\tcyan: [36, 39],\n\t\t\twhite: [37, 39],\n\t\t\tgray: [90, 39],\n\n\t\t\t// Bright color\n\t\t\tredBright: [91, 39],\n\t\t\tgreenBright: [92, 39],\n\t\t\tyellowBright: [93, 39],\n\t\t\tblueBright: [94, 39],\n\t\t\tmagentaBright: [95, 39],\n\t\t\tcyanBright: [96, 39],\n\t\t\twhiteBright: [97, 39]\n\t\t},\n\t\tbgColor: {\n\t\t\tbgBlack: [40, 49],\n\t\t\tbgRed: [41, 49],\n\t\t\tbgGreen: [42, 49],\n\t\t\tbgYellow: [43, 49],\n\t\t\tbgBlue: [44, 49],\n\t\t\tbgMagenta: [45, 49],\n\t\t\tbgCyan: [46, 49],\n\t\t\tbgWhite: [47, 49],\n\n\t\t\t// Bright color\n\t\t\tbgBlackBright: [100, 49],\n\t\t\tbgRedBright: [101, 49],\n\t\t\tbgGreenBright: [102, 49],\n\t\t\tbgYellowBright: [103, 49],\n\t\t\tbgBlueBright: [104, 49],\n\t\t\tbgMagentaBright: [105, 49],\n\t\t\tbgCyanBright: [106, 49],\n\t\t\tbgWhiteBright: [107, 49]\n\t\t}\n\t};\n\n\t// Fix humans\n\tstyles.color.grey = styles.color.gray;\n\n\tfor (const groupName of Object.keys(styles)) {\n\t\tconst group = styles[groupName];\n\n\t\tfor (const styleName of Object.keys(group)) {\n\t\t\tconst style = group[styleName];\n\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false\n\t\t});\n\n\t\tObject.defineProperty(styles, 'codes', {\n\t\t\tvalue: codes,\n\t\t\tenumerable: false\n\t\t});\n\t}\n\n\tconst ansi2ansi = n => n;\n\tconst rgb2rgb = (r, g, b) => [r, g, b];\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = {\n\t\tansi: wrapAnsi16(ansi2ansi, 0)\n\t};\n\tstyles.color.ansi256 = {\n\t\tansi256: wrapAnsi256(ansi2ansi, 0)\n\t};\n\tstyles.color.ansi16m = {\n\t\trgb: wrapAnsi16m(rgb2rgb, 0)\n\t};\n\n\tstyles.bgColor.ansi = {\n\t\tansi: wrapAnsi16(ansi2ansi, 10)\n\t};\n\tstyles.bgColor.ansi256 = {\n\t\tansi256: wrapAnsi256(ansi2ansi, 10)\n\t};\n\tstyles.bgColor.ansi16m = {\n\t\trgb: wrapAnsi16m(rgb2rgb, 10)\n\t};\n\n\tfor (let key of Object.keys(colorConvert)) {\n\t\tif (typeof colorConvert[key] !== 'object') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst suite = colorConvert[key];\n\n\t\tif (key === 'ansi16') {\n\t\t\tkey = 'ansi';\n\t\t}\n\n\t\tif ('ansi16' in suite) {\n\t\t\tstyles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);\n\t\t\tstyles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);\n\t\t}\n\n\t\tif ('ansi256' in suite) {\n\t\t\tstyles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);\n\t\t\tstyles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);\n\t\t}\n\n\t\tif ('rgb' in suite) {\n\t\t\tstyles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);\n\t\t\tstyles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);\n\t\t}\n\t}\n\n\treturn styles;\n}\n\n// Make the export immutable\nObject.defineProperty(module, 'exports', {\n\tenumerable: true,\n\tget: assembleStyles\n});\n","var stringWidth = require('string-width')\nvar stripAnsi = require('strip-ansi')\nvar wrap = require('wrap-ansi')\nvar align = {\n right: alignRight,\n center: alignCenter\n}\nvar top = 0\nvar right = 1\nvar bottom = 2\nvar left = 3\n\nfunction UI (opts) {\n this.width = opts.width\n this.wrap = opts.wrap\n this.rows = []\n}\n\nUI.prototype.span = function () {\n var cols = this.div.apply(this, arguments)\n cols.span = true\n}\n\nUI.prototype.resetOutput = function () {\n this.rows = []\n}\n\nUI.prototype.div = function () {\n if (arguments.length === 0) this.div('')\n if (this.wrap && this._shouldApplyLayoutDSL.apply(this, arguments)) {\n return this._applyLayoutDSL(arguments[0])\n }\n\n var cols = []\n\n for (var i = 0, arg; (arg = arguments[i]) !== undefined; i++) {\n if (typeof arg === 'string') cols.push(this._colFromString(arg))\n else cols.push(arg)\n }\n\n this.rows.push(cols)\n return cols\n}\n\nUI.prototype._shouldApplyLayoutDSL = function () {\n return arguments.length === 1 && typeof arguments[0] === 'string' &&\n /[\\t\\n]/.test(arguments[0])\n}\n\nUI.prototype._applyLayoutDSL = function (str) {\n var _this = this\n var rows = str.split('\\n')\n var leftColumnWidth = 0\n\n // simple heuristic for layout, make sure the\n // second column lines up along the left-hand.\n // don't allow the first column to take up more\n // than 50% of the screen.\n rows.forEach(function (row) {\n var columns = row.split('\\t')\n if (columns.length > 1 && stringWidth(columns[0]) > leftColumnWidth) {\n leftColumnWidth = Math.min(\n Math.floor(_this.width * 0.5),\n stringWidth(columns[0])\n )\n }\n })\n\n // generate a table:\n // replacing ' ' with padding calculations.\n // using the algorithmically generated width.\n rows.forEach(function (row) {\n var columns = row.split('\\t')\n _this.div.apply(_this, columns.map(function (r, i) {\n return {\n text: r.trim(),\n padding: _this._measurePadding(r),\n width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined\n }\n }))\n })\n\n return this.rows[this.rows.length - 1]\n}\n\nUI.prototype._colFromString = function (str) {\n return {\n text: str,\n padding: this._measurePadding(str)\n }\n}\n\nUI.prototype._measurePadding = function (str) {\n // measure padding without ansi escape codes\n var noAnsi = stripAnsi(str)\n return [0, noAnsi.match(/\\s*$/)[0].length, 0, noAnsi.match(/^\\s*/)[0].length]\n}\n\nUI.prototype.toString = function () {\n var _this = this\n var lines = []\n\n _this.rows.forEach(function (row, i) {\n _this.rowToString(row, lines)\n })\n\n // don't display any lines with the\n // hidden flag set.\n lines = lines.filter(function (line) {\n return !line.hidden\n })\n\n return lines.map(function (line) {\n return line.text\n }).join('\\n')\n}\n\nUI.prototype.rowToString = function (row, lines) {\n var _this = this\n var padding\n var rrows = this._rasterize(row)\n var str = ''\n var ts\n var width\n var wrapWidth\n\n rrows.forEach(function (rrow, r) {\n str = ''\n rrow.forEach(function (col, c) {\n ts = '' // temporary string used during alignment/padding.\n width = row[c].width // the width with padding.\n wrapWidth = _this._negatePadding(row[c]) // the width without padding.\n\n ts += col\n\n for (var i = 0; i < wrapWidth - stringWidth(col); i++) {\n ts += ' '\n }\n\n // align the string within its column.\n if (row[c].align && row[c].align !== 'left' && _this.wrap) {\n ts = align[row[c].align](ts, wrapWidth)\n if (stringWidth(ts) < wrapWidth) ts += new Array(width - stringWidth(ts)).join(' ')\n }\n\n // apply border and padding to string.\n padding = row[c].padding || [0, 0, 0, 0]\n if (padding[left]) str += new Array(padding[left] + 1).join(' ')\n str += addBorder(row[c], ts, '| ')\n str += ts\n str += addBorder(row[c], ts, ' |')\n if (padding[right]) str += new Array(padding[right] + 1).join(' ')\n\n // if prior row is span, try to render the\n // current row on the prior line.\n if (r === 0 && lines.length > 0) {\n str = _this._renderInline(str, lines[lines.length - 1])\n }\n })\n\n // remove trailing whitespace.\n lines.push({\n text: str.replace(/ +$/, ''),\n span: row.span\n })\n })\n\n return lines\n}\n\nfunction addBorder (col, ts, style) {\n if (col.border) {\n if (/[.']-+[.']/.test(ts)) return ''\n else if (ts.trim().length) return style\n else return ' '\n }\n return ''\n}\n\n// if the full 'source' can render in\n// the target line, do so.\nUI.prototype._renderInline = function (source, previousLine) {\n var leadingWhitespace = source.match(/^ */)[0].length\n var target = previousLine.text\n var targetTextWidth = stringWidth(target.trimRight())\n\n if (!previousLine.span) return source\n\n // if we're not applying wrapping logic,\n // just always append to the span.\n if (!this.wrap) {\n previousLine.hidden = true\n return target + source\n }\n\n if (leadingWhitespace < targetTextWidth) return source\n\n previousLine.hidden = true\n\n return target.trimRight() + new Array(leadingWhitespace - targetTextWidth + 1).join(' ') + source.trimLeft()\n}\n\nUI.prototype._rasterize = function (row) {\n var _this = this\n var i\n var rrow\n var rrows = []\n var widths = this._columnWidths(row)\n var wrapped\n\n // word wrap all columns, and create\n // a data-structure that is easy to rasterize.\n row.forEach(function (col, c) {\n // leave room for left and right padding.\n col.width = widths[c]\n if (_this.wrap) wrapped = wrap(col.text, _this._negatePadding(col), { hard: true }).split('\\n')\n else wrapped = col.text.split('\\n')\n\n if (col.border) {\n wrapped.unshift('.' + new Array(_this._negatePadding(col) + 3).join('-') + '.')\n wrapped.push(\"'\" + new Array(_this._negatePadding(col) + 3).join('-') + \"'\")\n }\n\n // add top and bottom padding.\n if (col.padding) {\n for (i = 0; i < (col.padding[top] || 0); i++) wrapped.unshift('')\n for (i = 0; i < (col.padding[bottom] || 0); i++) wrapped.push('')\n }\n\n wrapped.forEach(function (str, r) {\n if (!rrows[r]) rrows.push([])\n\n rrow = rrows[r]\n\n for (var i = 0; i < c; i++) {\n if (rrow[i] === undefined) rrow.push('')\n }\n rrow.push(str)\n })\n })\n\n return rrows\n}\n\nUI.prototype._negatePadding = function (col) {\n var wrapWidth = col.width\n if (col.padding) wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0)\n if (col.border) wrapWidth -= 4\n return wrapWidth\n}\n\nUI.prototype._columnWidths = function (row) {\n var _this = this\n var widths = []\n var unset = row.length\n var unsetWidth\n var remainingWidth = this.width\n\n // column widths can be set in config.\n row.forEach(function (col, i) {\n if (col.width) {\n unset--\n widths[i] = col.width\n remainingWidth -= col.width\n } else {\n widths[i] = undefined\n }\n })\n\n // any unset widths should be calculated.\n if (unset) unsetWidth = Math.floor(remainingWidth / unset)\n widths.forEach(function (w, i) {\n if (!_this.wrap) widths[i] = row[i].width || stringWidth(row[i].text)\n else if (w === undefined) widths[i] = Math.max(unsetWidth, _minWidth(row[i]))\n })\n\n return widths\n}\n\n// calculates the minimum width of\n// a column, based on padding preferences.\nfunction _minWidth (col) {\n var padding = col.padding || []\n var minWidth = 1 + (padding[left] || 0) + (padding[right] || 0)\n if (col.border) minWidth += 4\n return minWidth\n}\n\nfunction getWindowWidth () {\n if (typeof process === 'object' && process.stdout && process.stdout.columns) return process.stdout.columns\n}\n\nfunction alignRight (str, width) {\n str = str.trim()\n var padding = ''\n var strWidth = stringWidth(str)\n\n if (strWidth < width) {\n padding = new Array(width - strWidth + 1).join(' ')\n }\n\n return padding + str\n}\n\nfunction alignCenter (str, width) {\n str = str.trim()\n var padding = ''\n var strWidth = stringWidth(str.trim())\n\n if (strWidth < width) {\n padding = new Array(parseInt((width - strWidth) / 2, 10) + 1).join(' ')\n }\n\n return padding + str\n}\n\nmodule.exports = function (opts) {\n opts = opts || {}\n\n return new UI({\n width: (opts || {}).width || getWindowWidth() || 80,\n wrap: typeof opts.wrap === 'boolean' ? opts.wrap : true\n })\n}\n","/* MIT license */\nvar cssKeywords = require('color-name');\n\n// NOTE: conversions should only return primitive values (i.e. arrays, or\n// values that give correct `typeof` results).\n// do not use box values types (i.e. Number(), String(), etc.)\n\nvar reverseKeywords = {};\nfor (var key in cssKeywords) {\n\tif (cssKeywords.hasOwnProperty(key)) {\n\t\treverseKeywords[cssKeywords[key]] = key;\n\t}\n}\n\nvar convert = module.exports = {\n\trgb: {channels: 3, labels: 'rgb'},\n\thsl: {channels: 3, labels: 'hsl'},\n\thsv: {channels: 3, labels: 'hsv'},\n\thwb: {channels: 3, labels: 'hwb'},\n\tcmyk: {channels: 4, labels: 'cmyk'},\n\txyz: {channels: 3, labels: 'xyz'},\n\tlab: {channels: 3, labels: 'lab'},\n\tlch: {channels: 3, labels: 'lch'},\n\thex: {channels: 1, labels: ['hex']},\n\tkeyword: {channels: 1, labels: ['keyword']},\n\tansi16: {channels: 1, labels: ['ansi16']},\n\tansi256: {channels: 1, labels: ['ansi256']},\n\thcg: {channels: 3, labels: ['h', 'c', 'g']},\n\tapple: {channels: 3, labels: ['r16', 'g16', 'b16']},\n\tgray: {channels: 1, labels: ['gray']}\n};\n\n// hide .channels and .labels properties\nfor (var model in convert) {\n\tif (convert.hasOwnProperty(model)) {\n\t\tif (!('channels' in convert[model])) {\n\t\t\tthrow new Error('missing channels property: ' + model);\n\t\t}\n\n\t\tif (!('labels' in convert[model])) {\n\t\t\tthrow new Error('missing channel labels property: ' + model);\n\t\t}\n\n\t\tif (convert[model].labels.length !== convert[model].channels) {\n\t\t\tthrow new Error('channel and label counts mismatch: ' + model);\n\t\t}\n\n\t\tvar channels = convert[model].channels;\n\t\tvar labels = convert[model].labels;\n\t\tdelete convert[model].channels;\n\t\tdelete convert[model].labels;\n\t\tObject.defineProperty(convert[model], 'channels', {value: channels});\n\t\tObject.defineProperty(convert[model], 'labels', {value: labels});\n\t}\n}\n\nconvert.rgb.hsl = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar min = Math.min(r, g, b);\n\tvar max = Math.max(r, g, b);\n\tvar delta = max - min;\n\tvar h;\n\tvar s;\n\tvar l;\n\n\tif (max === min) {\n\t\th = 0;\n\t} else if (r === max) {\n\t\th = (g - b) / delta;\n\t} else if (g === max) {\n\t\th = 2 + (b - r) / delta;\n\t} else if (b === max) {\n\t\th = 4 + (r - g) / delta;\n\t}\n\n\th = Math.min(h * 60, 360);\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tl = (min + max) / 2;\n\n\tif (max === min) {\n\t\ts = 0;\n\t} else if (l <= 0.5) {\n\t\ts = delta / (max + min);\n\t} else {\n\t\ts = delta / (2 - max - min);\n\t}\n\n\treturn [h, s * 100, l * 100];\n};\n\nconvert.rgb.hsv = function (rgb) {\n\tvar rdif;\n\tvar gdif;\n\tvar bdif;\n\tvar h;\n\tvar s;\n\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar v = Math.max(r, g, b);\n\tvar diff = v - Math.min(r, g, b);\n\tvar diffc = function (c) {\n\t\treturn (v - c) / 6 / diff + 1 / 2;\n\t};\n\n\tif (diff === 0) {\n\t\th = s = 0;\n\t} else {\n\t\ts = diff / v;\n\t\trdif = diffc(r);\n\t\tgdif = diffc(g);\n\t\tbdif = diffc(b);\n\n\t\tif (r === v) {\n\t\t\th = bdif - gdif;\n\t\t} else if (g === v) {\n\t\t\th = (1 / 3) + rdif - bdif;\n\t\t} else if (b === v) {\n\t\t\th = (2 / 3) + gdif - rdif;\n\t\t}\n\t\tif (h < 0) {\n\t\t\th += 1;\n\t\t} else if (h > 1) {\n\t\t\th -= 1;\n\t\t}\n\t}\n\n\treturn [\n\t\th * 360,\n\t\ts * 100,\n\t\tv * 100\n\t];\n};\n\nconvert.rgb.hwb = function (rgb) {\n\tvar r = rgb[0];\n\tvar g = rgb[1];\n\tvar b = rgb[2];\n\tvar h = convert.rgb.hsl(rgb)[0];\n\tvar w = 1 / 255 * Math.min(r, Math.min(g, b));\n\n\tb = 1 - 1 / 255 * Math.max(r, Math.max(g, b));\n\n\treturn [h, w * 100, b * 100];\n};\n\nconvert.rgb.cmyk = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar c;\n\tvar m;\n\tvar y;\n\tvar k;\n\n\tk = Math.min(1 - r, 1 - g, 1 - b);\n\tc = (1 - r - k) / (1 - k) || 0;\n\tm = (1 - g - k) / (1 - k) || 0;\n\ty = (1 - b - k) / (1 - k) || 0;\n\n\treturn [c * 100, m * 100, y * 100, k * 100];\n};\n\n/**\n * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance\n * */\nfunction comparativeDistance(x, y) {\n\treturn (\n\t\tMath.pow(x[0] - y[0], 2) +\n\t\tMath.pow(x[1] - y[1], 2) +\n\t\tMath.pow(x[2] - y[2], 2)\n\t);\n}\n\nconvert.rgb.keyword = function (rgb) {\n\tvar reversed = reverseKeywords[rgb];\n\tif (reversed) {\n\t\treturn reversed;\n\t}\n\n\tvar currentClosestDistance = Infinity;\n\tvar currentClosestKeyword;\n\n\tfor (var keyword in cssKeywords) {\n\t\tif (cssKeywords.hasOwnProperty(keyword)) {\n\t\t\tvar value = cssKeywords[keyword];\n\n\t\t\t// Compute comparative distance\n\t\t\tvar distance = comparativeDistance(rgb, value);\n\n\t\t\t// Check if its less, if so set as closest\n\t\t\tif (distance < currentClosestDistance) {\n\t\t\t\tcurrentClosestDistance = distance;\n\t\t\t\tcurrentClosestKeyword = keyword;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn currentClosestKeyword;\n};\n\nconvert.keyword.rgb = function (keyword) {\n\treturn cssKeywords[keyword];\n};\n\nconvert.rgb.xyz = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\n\t// assume sRGB\n\tr = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);\n\tg = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);\n\tb = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);\n\n\tvar x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);\n\tvar y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);\n\tvar z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);\n\n\treturn [x * 100, y * 100, z * 100];\n};\n\nconvert.rgb.lab = function (rgb) {\n\tvar xyz = convert.rgb.xyz(rgb);\n\tvar x = xyz[0];\n\tvar y = xyz[1];\n\tvar z = xyz[2];\n\tvar l;\n\tvar a;\n\tvar b;\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);\n\n\tl = (116 * y) - 16;\n\ta = 500 * (x - y);\n\tb = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.hsl.rgb = function (hsl) {\n\tvar h = hsl[0] / 360;\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar t1;\n\tvar t2;\n\tvar t3;\n\tvar rgb;\n\tvar val;\n\n\tif (s === 0) {\n\t\tval = l * 255;\n\t\treturn [val, val, val];\n\t}\n\n\tif (l < 0.5) {\n\t\tt2 = l * (1 + s);\n\t} else {\n\t\tt2 = l + s - l * s;\n\t}\n\n\tt1 = 2 * l - t2;\n\n\trgb = [0, 0, 0];\n\tfor (var i = 0; i < 3; i++) {\n\t\tt3 = h + 1 / 3 * -(i - 1);\n\t\tif (t3 < 0) {\n\t\t\tt3++;\n\t\t}\n\t\tif (t3 > 1) {\n\t\t\tt3--;\n\t\t}\n\n\t\tif (6 * t3 < 1) {\n\t\t\tval = t1 + (t2 - t1) * 6 * t3;\n\t\t} else if (2 * t3 < 1) {\n\t\t\tval = t2;\n\t\t} else if (3 * t3 < 2) {\n\t\t\tval = t1 + (t2 - t1) * (2 / 3 - t3) * 6;\n\t\t} else {\n\t\t\tval = t1;\n\t\t}\n\n\t\trgb[i] = val * 255;\n\t}\n\n\treturn rgb;\n};\n\nconvert.hsl.hsv = function (hsl) {\n\tvar h = hsl[0];\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar smin = s;\n\tvar lmin = Math.max(l, 0.01);\n\tvar sv;\n\tvar v;\n\n\tl *= 2;\n\ts *= (l <= 1) ? l : 2 - l;\n\tsmin *= lmin <= 1 ? lmin : 2 - lmin;\n\tv = (l + s) / 2;\n\tsv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);\n\n\treturn [h, sv * 100, v * 100];\n};\n\nconvert.hsv.rgb = function (hsv) {\n\tvar h = hsv[0] / 60;\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\tvar hi = Math.floor(h) % 6;\n\n\tvar f = h - Math.floor(h);\n\tvar p = 255 * v * (1 - s);\n\tvar q = 255 * v * (1 - (s * f));\n\tvar t = 255 * v * (1 - (s * (1 - f)));\n\tv *= 255;\n\n\tswitch (hi) {\n\t\tcase 0:\n\t\t\treturn [v, t, p];\n\t\tcase 1:\n\t\t\treturn [q, v, p];\n\t\tcase 2:\n\t\t\treturn [p, v, t];\n\t\tcase 3:\n\t\t\treturn [p, q, v];\n\t\tcase 4:\n\t\t\treturn [t, p, v];\n\t\tcase 5:\n\t\t\treturn [v, p, q];\n\t}\n};\n\nconvert.hsv.hsl = function (hsv) {\n\tvar h = hsv[0];\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\tvar vmin = Math.max(v, 0.01);\n\tvar lmin;\n\tvar sl;\n\tvar l;\n\n\tl = (2 - s) * v;\n\tlmin = (2 - s) * vmin;\n\tsl = s * vmin;\n\tsl /= (lmin <= 1) ? lmin : 2 - lmin;\n\tsl = sl || 0;\n\tl /= 2;\n\n\treturn [h, sl * 100, l * 100];\n};\n\n// http://dev.w3.org/csswg/css-color/#hwb-to-rgb\nconvert.hwb.rgb = function (hwb) {\n\tvar h = hwb[0] / 360;\n\tvar wh = hwb[1] / 100;\n\tvar bl = hwb[2] / 100;\n\tvar ratio = wh + bl;\n\tvar i;\n\tvar v;\n\tvar f;\n\tvar n;\n\n\t// wh + bl cant be > 1\n\tif (ratio > 1) {\n\t\twh /= ratio;\n\t\tbl /= ratio;\n\t}\n\n\ti = Math.floor(6 * h);\n\tv = 1 - bl;\n\tf = 6 * h - i;\n\n\tif ((i & 0x01) !== 0) {\n\t\tf = 1 - f;\n\t}\n\n\tn = wh + f * (v - wh); // linear interpolation\n\n\tvar r;\n\tvar g;\n\tvar b;\n\tswitch (i) {\n\t\tdefault:\n\t\tcase 6:\n\t\tcase 0: r = v; g = n; b = wh; break;\n\t\tcase 1: r = n; g = v; b = wh; break;\n\t\tcase 2: r = wh; g = v; b = n; break;\n\t\tcase 3: r = wh; g = n; b = v; break;\n\t\tcase 4: r = n; g = wh; b = v; break;\n\t\tcase 5: r = v; g = wh; b = n; break;\n\t}\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.cmyk.rgb = function (cmyk) {\n\tvar c = cmyk[0] / 100;\n\tvar m = cmyk[1] / 100;\n\tvar y = cmyk[2] / 100;\n\tvar k = cmyk[3] / 100;\n\tvar r;\n\tvar g;\n\tvar b;\n\n\tr = 1 - Math.min(1, c * (1 - k) + k);\n\tg = 1 - Math.min(1, m * (1 - k) + k);\n\tb = 1 - Math.min(1, y * (1 - k) + k);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.rgb = function (xyz) {\n\tvar x = xyz[0] / 100;\n\tvar y = xyz[1] / 100;\n\tvar z = xyz[2] / 100;\n\tvar r;\n\tvar g;\n\tvar b;\n\n\tr = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);\n\tg = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);\n\tb = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);\n\n\t// assume sRGB\n\tr = r > 0.0031308\n\t\t? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)\n\t\t: r * 12.92;\n\n\tg = g > 0.0031308\n\t\t? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)\n\t\t: g * 12.92;\n\n\tb = b > 0.0031308\n\t\t? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)\n\t\t: b * 12.92;\n\n\tr = Math.min(Math.max(0, r), 1);\n\tg = Math.min(Math.max(0, g), 1);\n\tb = Math.min(Math.max(0, b), 1);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.lab = function (xyz) {\n\tvar x = xyz[0];\n\tvar y = xyz[1];\n\tvar z = xyz[2];\n\tvar l;\n\tvar a;\n\tvar b;\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);\n\n\tl = (116 * y) - 16;\n\ta = 500 * (x - y);\n\tb = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.lab.xyz = function (lab) {\n\tvar l = lab[0];\n\tvar a = lab[1];\n\tvar b = lab[2];\n\tvar x;\n\tvar y;\n\tvar z;\n\n\ty = (l + 16) / 116;\n\tx = a / 500 + y;\n\tz = y - b / 200;\n\n\tvar y2 = Math.pow(y, 3);\n\tvar x2 = Math.pow(x, 3);\n\tvar z2 = Math.pow(z, 3);\n\ty = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;\n\tx = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;\n\tz = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;\n\n\tx *= 95.047;\n\ty *= 100;\n\tz *= 108.883;\n\n\treturn [x, y, z];\n};\n\nconvert.lab.lch = function (lab) {\n\tvar l = lab[0];\n\tvar a = lab[1];\n\tvar b = lab[2];\n\tvar hr;\n\tvar h;\n\tvar c;\n\n\thr = Math.atan2(b, a);\n\th = hr * 360 / 2 / Math.PI;\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tc = Math.sqrt(a * a + b * b);\n\n\treturn [l, c, h];\n};\n\nconvert.lch.lab = function (lch) {\n\tvar l = lch[0];\n\tvar c = lch[1];\n\tvar h = lch[2];\n\tvar a;\n\tvar b;\n\tvar hr;\n\n\thr = h / 360 * 2 * Math.PI;\n\ta = c * Math.cos(hr);\n\tb = c * Math.sin(hr);\n\n\treturn [l, a, b];\n};\n\nconvert.rgb.ansi16 = function (args) {\n\tvar r = args[0];\n\tvar g = args[1];\n\tvar b = args[2];\n\tvar value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization\n\n\tvalue = Math.round(value / 50);\n\n\tif (value === 0) {\n\t\treturn 30;\n\t}\n\n\tvar ansi = 30\n\t\t+ ((Math.round(b / 255) << 2)\n\t\t| (Math.round(g / 255) << 1)\n\t\t| Math.round(r / 255));\n\n\tif (value === 2) {\n\t\tansi += 60;\n\t}\n\n\treturn ansi;\n};\n\nconvert.hsv.ansi16 = function (args) {\n\t// optimization here; we already know the value and don't need to get\n\t// it converted for us.\n\treturn convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);\n};\n\nconvert.rgb.ansi256 = function (args) {\n\tvar r = args[0];\n\tvar g = args[1];\n\tvar b = args[2];\n\n\t// we use the extended greyscale palette here, with the exception of\n\t// black and white. normal palette only has 4 greyscale shades.\n\tif (r === g && g === b) {\n\t\tif (r < 8) {\n\t\t\treturn 16;\n\t\t}\n\n\t\tif (r > 248) {\n\t\t\treturn 231;\n\t\t}\n\n\t\treturn Math.round(((r - 8) / 247) * 24) + 232;\n\t}\n\n\tvar ansi = 16\n\t\t+ (36 * Math.round(r / 255 * 5))\n\t\t+ (6 * Math.round(g / 255 * 5))\n\t\t+ Math.round(b / 255 * 5);\n\n\treturn ansi;\n};\n\nconvert.ansi16.rgb = function (args) {\n\tvar color = args % 10;\n\n\t// handle greyscale\n\tif (color === 0 || color === 7) {\n\t\tif (args > 50) {\n\t\t\tcolor += 3.5;\n\t\t}\n\n\t\tcolor = color / 10.5 * 255;\n\n\t\treturn [color, color, color];\n\t}\n\n\tvar mult = (~~(args > 50) + 1) * 0.5;\n\tvar r = ((color & 1) * mult) * 255;\n\tvar g = (((color >> 1) & 1) * mult) * 255;\n\tvar b = (((color >> 2) & 1) * mult) * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.ansi256.rgb = function (args) {\n\t// handle greyscale\n\tif (args >= 232) {\n\t\tvar c = (args - 232) * 10 + 8;\n\t\treturn [c, c, c];\n\t}\n\n\targs -= 16;\n\n\tvar rem;\n\tvar r = Math.floor(args / 36) / 5 * 255;\n\tvar g = Math.floor((rem = args % 36) / 6) / 5 * 255;\n\tvar b = (rem % 6) / 5 * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hex = function (args) {\n\tvar integer = ((Math.round(args[0]) & 0xFF) << 16)\n\t\t+ ((Math.round(args[1]) & 0xFF) << 8)\n\t\t+ (Math.round(args[2]) & 0xFF);\n\n\tvar string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.hex.rgb = function (args) {\n\tvar match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);\n\tif (!match) {\n\t\treturn [0, 0, 0];\n\t}\n\n\tvar colorString = match[0];\n\n\tif (match[0].length === 3) {\n\t\tcolorString = colorString.split('').map(function (char) {\n\t\t\treturn char + char;\n\t\t}).join('');\n\t}\n\n\tvar integer = parseInt(colorString, 16);\n\tvar r = (integer >> 16) & 0xFF;\n\tvar g = (integer >> 8) & 0xFF;\n\tvar b = integer & 0xFF;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hcg = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar max = Math.max(Math.max(r, g), b);\n\tvar min = Math.min(Math.min(r, g), b);\n\tvar chroma = (max - min);\n\tvar grayscale;\n\tvar hue;\n\n\tif (chroma < 1) {\n\t\tgrayscale = min / (1 - chroma);\n\t} else {\n\t\tgrayscale = 0;\n\t}\n\n\tif (chroma <= 0) {\n\t\thue = 0;\n\t} else\n\tif (max === r) {\n\t\thue = ((g - b) / chroma) % 6;\n\t} else\n\tif (max === g) {\n\t\thue = 2 + (b - r) / chroma;\n\t} else {\n\t\thue = 4 + (r - g) / chroma + 4;\n\t}\n\n\thue /= 6;\n\thue %= 1;\n\n\treturn [hue * 360, chroma * 100, grayscale * 100];\n};\n\nconvert.hsl.hcg = function (hsl) {\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar c = 1;\n\tvar f = 0;\n\n\tif (l < 0.5) {\n\t\tc = 2.0 * s * l;\n\t} else {\n\t\tc = 2.0 * s * (1.0 - l);\n\t}\n\n\tif (c < 1.0) {\n\t\tf = (l - 0.5 * c) / (1.0 - c);\n\t}\n\n\treturn [hsl[0], c * 100, f * 100];\n};\n\nconvert.hsv.hcg = function (hsv) {\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\n\tvar c = s * v;\n\tvar f = 0;\n\n\tif (c < 1.0) {\n\t\tf = (v - c) / (1 - c);\n\t}\n\n\treturn [hsv[0], c * 100, f * 100];\n};\n\nconvert.hcg.rgb = function (hcg) {\n\tvar h = hcg[0] / 360;\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tif (c === 0.0) {\n\t\treturn [g * 255, g * 255, g * 255];\n\t}\n\n\tvar pure = [0, 0, 0];\n\tvar hi = (h % 1) * 6;\n\tvar v = hi % 1;\n\tvar w = 1 - v;\n\tvar mg = 0;\n\n\tswitch (Math.floor(hi)) {\n\t\tcase 0:\n\t\t\tpure[0] = 1; pure[1] = v; pure[2] = 0; break;\n\t\tcase 1:\n\t\t\tpure[0] = w; pure[1] = 1; pure[2] = 0; break;\n\t\tcase 2:\n\t\t\tpure[0] = 0; pure[1] = 1; pure[2] = v; break;\n\t\tcase 3:\n\t\t\tpure[0] = 0; pure[1] = w; pure[2] = 1; break;\n\t\tcase 4:\n\t\t\tpure[0] = v; pure[1] = 0; pure[2] = 1; break;\n\t\tdefault:\n\t\t\tpure[0] = 1; pure[1] = 0; pure[2] = w;\n\t}\n\n\tmg = (1.0 - c) * g;\n\n\treturn [\n\t\t(c * pure[0] + mg) * 255,\n\t\t(c * pure[1] + mg) * 255,\n\t\t(c * pure[2] + mg) * 255\n\t];\n};\n\nconvert.hcg.hsv = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tvar v = c + g * (1.0 - c);\n\tvar f = 0;\n\n\tif (v > 0.0) {\n\t\tf = c / v;\n\t}\n\n\treturn [hcg[0], f * 100, v * 100];\n};\n\nconvert.hcg.hsl = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tvar l = g * (1.0 - c) + 0.5 * c;\n\tvar s = 0;\n\n\tif (l > 0.0 && l < 0.5) {\n\t\ts = c / (2 * l);\n\t} else\n\tif (l >= 0.5 && l < 1.0) {\n\t\ts = c / (2 * (1 - l));\n\t}\n\n\treturn [hcg[0], s * 100, l * 100];\n};\n\nconvert.hcg.hwb = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\tvar v = c + g * (1.0 - c);\n\treturn [hcg[0], (v - c) * 100, (1 - v) * 100];\n};\n\nconvert.hwb.hcg = function (hwb) {\n\tvar w = hwb[1] / 100;\n\tvar b = hwb[2] / 100;\n\tvar v = 1 - b;\n\tvar c = v - w;\n\tvar g = 0;\n\n\tif (c < 1) {\n\t\tg = (v - c) / (1 - c);\n\t}\n\n\treturn [hwb[0], c * 100, g * 100];\n};\n\nconvert.apple.rgb = function (apple) {\n\treturn [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];\n};\n\nconvert.rgb.apple = function (rgb) {\n\treturn [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];\n};\n\nconvert.gray.rgb = function (args) {\n\treturn [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];\n};\n\nconvert.gray.hsl = convert.gray.hsv = function (args) {\n\treturn [0, 0, args[0]];\n};\n\nconvert.gray.hwb = function (gray) {\n\treturn [0, 100, gray[0]];\n};\n\nconvert.gray.cmyk = function (gray) {\n\treturn [0, 0, 0, gray[0]];\n};\n\nconvert.gray.lab = function (gray) {\n\treturn [gray[0], 0, 0];\n};\n\nconvert.gray.hex = function (gray) {\n\tvar val = Math.round(gray[0] / 100 * 255) & 0xFF;\n\tvar integer = (val << 16) + (val << 8) + val;\n\n\tvar string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.rgb.gray = function (rgb) {\n\tvar val = (rgb[0] + rgb[1] + rgb[2]) / 3;\n\treturn [val / 255 * 100];\n};\n","var conversions = require('./conversions');\nvar route = require('./route');\n\nvar convert = {};\n\nvar models = Object.keys(conversions);\n\nfunction wrapRaw(fn) {\n\tvar wrappedFn = function (args) {\n\t\tif (args === undefined || args === null) {\n\t\t\treturn args;\n\t\t}\n\n\t\tif (arguments.length > 1) {\n\t\t\targs = Array.prototype.slice.call(arguments);\n\t\t}\n\n\t\treturn fn(args);\n\t};\n\n\t// preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nfunction wrapRounded(fn) {\n\tvar wrappedFn = function (args) {\n\t\tif (args === undefined || args === null) {\n\t\t\treturn args;\n\t\t}\n\n\t\tif (arguments.length > 1) {\n\t\t\targs = Array.prototype.slice.call(arguments);\n\t\t}\n\n\t\tvar result = fn(args);\n\n\t\t// we're assuming the result is an array here.\n\t\t// see notice in conversions.js; don't use box types\n\t\t// in conversion functions.\n\t\tif (typeof result === 'object') {\n\t\t\tfor (var len = result.length, i = 0; i < len; i++) {\n\t\t\t\tresult[i] = Math.round(result[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t};\n\n\t// preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nmodels.forEach(function (fromModel) {\n\tconvert[fromModel] = {};\n\n\tObject.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});\n\tObject.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});\n\n\tvar routes = route(fromModel);\n\tvar routeModels = Object.keys(routes);\n\n\trouteModels.forEach(function (toModel) {\n\t\tvar fn = routes[toModel];\n\n\t\tconvert[fromModel][toModel] = wrapRounded(fn);\n\t\tconvert[fromModel][toModel].raw = wrapRaw(fn);\n\t});\n});\n\nmodule.exports = convert;\n","var conversions = require('./conversions');\n\n/*\n\tthis function routes a model to all other models.\n\n\tall functions that are routed have a property `.conversion` attached\n\tto the returned synthetic function. This property is an array\n\tof strings, each with the steps in between the 'from' and 'to'\n\tcolor models (inclusive).\n\n\tconversions that are not possible simply are not included.\n*/\n\nfunction buildGraph() {\n\tvar graph = {};\n\t// https://jsperf.com/object-keys-vs-for-in-with-closure/3\n\tvar models = Object.keys(conversions);\n\n\tfor (var len = models.length, i = 0; i < len; i++) {\n\t\tgraph[models[i]] = {\n\t\t\t// http://jsperf.com/1-vs-infinity\n\t\t\t// micro-opt, but this is simple.\n\t\t\tdistance: -1,\n\t\t\tparent: null\n\t\t};\n\t}\n\n\treturn graph;\n}\n\n// https://en.wikipedia.org/wiki/Breadth-first_search\nfunction deriveBFS(fromModel) {\n\tvar graph = buildGraph();\n\tvar queue = [fromModel]; // unshift -> queue -> pop\n\n\tgraph[fromModel].distance = 0;\n\n\twhile (queue.length) {\n\t\tvar current = queue.pop();\n\t\tvar adjacents = Object.keys(conversions[current]);\n\n\t\tfor (var len = adjacents.length, i = 0; i < len; i++) {\n\t\t\tvar adjacent = adjacents[i];\n\t\t\tvar node = graph[adjacent];\n\n\t\t\tif (node.distance === -1) {\n\t\t\t\tnode.distance = graph[current].distance + 1;\n\t\t\t\tnode.parent = current;\n\t\t\t\tqueue.unshift(adjacent);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn graph;\n}\n\nfunction link(from, to) {\n\treturn function (args) {\n\t\treturn to(from(args));\n\t};\n}\n\nfunction wrapConversion(toModel, graph) {\n\tvar path = [graph[toModel].parent, toModel];\n\tvar fn = conversions[graph[toModel].parent][toModel];\n\n\tvar cur = graph[toModel].parent;\n\twhile (graph[cur].parent) {\n\t\tpath.unshift(graph[cur].parent);\n\t\tfn = link(conversions[graph[cur].parent][cur], fn);\n\t\tcur = graph[cur].parent;\n\t}\n\n\tfn.conversion = path;\n\treturn fn;\n}\n\nmodule.exports = function (fromModel) {\n\tvar graph = deriveBFS(fromModel);\n\tvar conversion = {};\n\n\tvar models = Object.keys(graph);\n\tfor (var len = models.length, i = 0; i < len; i++) {\n\t\tvar toModel = models[i];\n\t\tvar node = graph[toModel];\n\n\t\tif (node.parent === null) {\n\t\t\t// no possible conversion, or this node is the source model.\n\t\t\tcontinue;\n\t\t}\n\n\t\tconversion[toModel] = wrapConversion(toModel, graph);\n\t}\n\n\treturn conversion;\n};\n\n","'use strict'\r\n\r\nmodule.exports = {\r\n\t\"aliceblue\": [240, 248, 255],\r\n\t\"antiquewhite\": [250, 235, 215],\r\n\t\"aqua\": [0, 255, 255],\r\n\t\"aquamarine\": [127, 255, 212],\r\n\t\"azure\": [240, 255, 255],\r\n\t\"beige\": [245, 245, 220],\r\n\t\"bisque\": [255, 228, 196],\r\n\t\"black\": [0, 0, 0],\r\n\t\"blanchedalmond\": [255, 235, 205],\r\n\t\"blue\": [0, 0, 255],\r\n\t\"blueviolet\": [138, 43, 226],\r\n\t\"brown\": [165, 42, 42],\r\n\t\"burlywood\": [222, 184, 135],\r\n\t\"cadetblue\": [95, 158, 160],\r\n\t\"chartreuse\": [127, 255, 0],\r\n\t\"chocolate\": [210, 105, 30],\r\n\t\"coral\": [255, 127, 80],\r\n\t\"cornflowerblue\": [100, 149, 237],\r\n\t\"cornsilk\": [255, 248, 220],\r\n\t\"crimson\": [220, 20, 60],\r\n\t\"cyan\": [0, 255, 255],\r\n\t\"darkblue\": [0, 0, 139],\r\n\t\"darkcyan\": [0, 139, 139],\r\n\t\"darkgoldenrod\": [184, 134, 11],\r\n\t\"darkgray\": [169, 169, 169],\r\n\t\"darkgreen\": [0, 100, 0],\r\n\t\"darkgrey\": [169, 169, 169],\r\n\t\"darkkhaki\": [189, 183, 107],\r\n\t\"darkmagenta\": [139, 0, 139],\r\n\t\"darkolivegreen\": [85, 107, 47],\r\n\t\"darkorange\": [255, 140, 0],\r\n\t\"darkorchid\": [153, 50, 204],\r\n\t\"darkred\": [139, 0, 0],\r\n\t\"darksalmon\": [233, 150, 122],\r\n\t\"darkseagreen\": [143, 188, 143],\r\n\t\"darkslateblue\": [72, 61, 139],\r\n\t\"darkslategray\": [47, 79, 79],\r\n\t\"darkslategrey\": [47, 79, 79],\r\n\t\"darkturquoise\": [0, 206, 209],\r\n\t\"darkviolet\": [148, 0, 211],\r\n\t\"deeppink\": [255, 20, 147],\r\n\t\"deepskyblue\": [0, 191, 255],\r\n\t\"dimgray\": [105, 105, 105],\r\n\t\"dimgrey\": [105, 105, 105],\r\n\t\"dodgerblue\": [30, 144, 255],\r\n\t\"firebrick\": [178, 34, 34],\r\n\t\"floralwhite\": [255, 250, 240],\r\n\t\"forestgreen\": [34, 139, 34],\r\n\t\"fuchsia\": [255, 0, 255],\r\n\t\"gainsboro\": [220, 220, 220],\r\n\t\"ghostwhite\": [248, 248, 255],\r\n\t\"gold\": [255, 215, 0],\r\n\t\"goldenrod\": [218, 165, 32],\r\n\t\"gray\": [128, 128, 128],\r\n\t\"green\": [0, 128, 0],\r\n\t\"greenyellow\": [173, 255, 47],\r\n\t\"grey\": [128, 128, 128],\r\n\t\"honeydew\": [240, 255, 240],\r\n\t\"hotpink\": [255, 105, 180],\r\n\t\"indianred\": [205, 92, 92],\r\n\t\"indigo\": [75, 0, 130],\r\n\t\"ivory\": [255, 255, 240],\r\n\t\"khaki\": [240, 230, 140],\r\n\t\"lavender\": [230, 230, 250],\r\n\t\"lavenderblush\": [255, 240, 245],\r\n\t\"lawngreen\": [124, 252, 0],\r\n\t\"lemonchiffon\": [255, 250, 205],\r\n\t\"lightblue\": [173, 216, 230],\r\n\t\"lightcoral\": [240, 128, 128],\r\n\t\"lightcyan\": [224, 255, 255],\r\n\t\"lightgoldenrodyellow\": [250, 250, 210],\r\n\t\"lightgray\": [211, 211, 211],\r\n\t\"lightgreen\": [144, 238, 144],\r\n\t\"lightgrey\": [211, 211, 211],\r\n\t\"lightpink\": [255, 182, 193],\r\n\t\"lightsalmon\": [255, 160, 122],\r\n\t\"lightseagreen\": [32, 178, 170],\r\n\t\"lightskyblue\": [135, 206, 250],\r\n\t\"lightslategray\": [119, 136, 153],\r\n\t\"lightslategrey\": [119, 136, 153],\r\n\t\"lightsteelblue\": [176, 196, 222],\r\n\t\"lightyellow\": [255, 255, 224],\r\n\t\"lime\": [0, 255, 0],\r\n\t\"limegreen\": [50, 205, 50],\r\n\t\"linen\": [250, 240, 230],\r\n\t\"magenta\": [255, 0, 255],\r\n\t\"maroon\": [128, 0, 0],\r\n\t\"mediumaquamarine\": [102, 205, 170],\r\n\t\"mediumblue\": [0, 0, 205],\r\n\t\"mediumorchid\": [186, 85, 211],\r\n\t\"mediumpurple\": [147, 112, 219],\r\n\t\"mediumseagreen\": [60, 179, 113],\r\n\t\"mediumslateblue\": [123, 104, 238],\r\n\t\"mediumspringgreen\": [0, 250, 154],\r\n\t\"mediumturquoise\": [72, 209, 204],\r\n\t\"mediumvioletred\": [199, 21, 133],\r\n\t\"midnightblue\": [25, 25, 112],\r\n\t\"mintcream\": [245, 255, 250],\r\n\t\"mistyrose\": [255, 228, 225],\r\n\t\"moccasin\": [255, 228, 181],\r\n\t\"navajowhite\": [255, 222, 173],\r\n\t\"navy\": [0, 0, 128],\r\n\t\"oldlace\": [253, 245, 230],\r\n\t\"olive\": [128, 128, 0],\r\n\t\"olivedrab\": [107, 142, 35],\r\n\t\"orange\": [255, 165, 0],\r\n\t\"orangered\": [255, 69, 0],\r\n\t\"orchid\": [218, 112, 214],\r\n\t\"palegoldenrod\": [238, 232, 170],\r\n\t\"palegreen\": [152, 251, 152],\r\n\t\"paleturquoise\": [175, 238, 238],\r\n\t\"palevioletred\": [219, 112, 147],\r\n\t\"papayawhip\": [255, 239, 213],\r\n\t\"peachpuff\": [255, 218, 185],\r\n\t\"peru\": [205, 133, 63],\r\n\t\"pink\": [255, 192, 203],\r\n\t\"plum\": [221, 160, 221],\r\n\t\"powderblue\": [176, 224, 230],\r\n\t\"purple\": [128, 0, 128],\r\n\t\"rebeccapurple\": [102, 51, 153],\r\n\t\"red\": [255, 0, 0],\r\n\t\"rosybrown\": [188, 143, 143],\r\n\t\"royalblue\": [65, 105, 225],\r\n\t\"saddlebrown\": [139, 69, 19],\r\n\t\"salmon\": [250, 128, 114],\r\n\t\"sandybrown\": [244, 164, 96],\r\n\t\"seagreen\": [46, 139, 87],\r\n\t\"seashell\": [255, 245, 238],\r\n\t\"sienna\": [160, 82, 45],\r\n\t\"silver\": [192, 192, 192],\r\n\t\"skyblue\": [135, 206, 235],\r\n\t\"slateblue\": [106, 90, 205],\r\n\t\"slategray\": [112, 128, 144],\r\n\t\"slategrey\": [112, 128, 144],\r\n\t\"snow\": [255, 250, 250],\r\n\t\"springgreen\": [0, 255, 127],\r\n\t\"steelblue\": [70, 130, 180],\r\n\t\"tan\": [210, 180, 140],\r\n\t\"teal\": [0, 128, 128],\r\n\t\"thistle\": [216, 191, 216],\r\n\t\"tomato\": [255, 99, 71],\r\n\t\"turquoise\": [64, 224, 208],\r\n\t\"violet\": [238, 130, 238],\r\n\t\"wheat\": [245, 222, 179],\r\n\t\"white\": [255, 255, 255],\r\n\t\"whitesmoke\": [245, 245, 245],\r\n\t\"yellow\": [255, 255, 0],\r\n\t\"yellowgreen\": [154, 205, 50]\r\n};\r\n","'use strict';\nconst path = require('path');\nconst locatePath = require('locate-path');\n\nmodule.exports = (filename, opts = {}) => {\n\tconst startDir = path.resolve(opts.cwd || '');\n\tconst {root} = path.parse(startDir);\n\n\tconst filenames = [].concat(filename);\n\n\treturn new Promise(resolve => {\n\t\t(function find(dir) {\n\t\t\tlocatePath(filenames, {cwd: dir}).then(file => {\n\t\t\t\tif (file) {\n\t\t\t\t\tresolve(path.join(dir, file));\n\t\t\t\t} else if (dir === root) {\n\t\t\t\t\tresolve(null);\n\t\t\t\t} else {\n\t\t\t\t\tfind(path.dirname(dir));\n\t\t\t\t}\n\t\t\t});\n\t\t})(startDir);\n\t});\n};\n\nmodule.exports.sync = (filename, opts = {}) => {\n\tlet dir = path.resolve(opts.cwd || '');\n\tconst {root} = path.parse(dir);\n\n\tconst filenames = [].concat(filename);\n\n\t// eslint-disable-next-line no-constant-condition\n\twhile (true) {\n\t\tconst file = locatePath.sync(filenames, {cwd: dir});\n\n\t\tif (file) {\n\t\t\treturn path.join(dir, file);\n\t\t}\n\n\t\tif (dir === root) {\n\t\t\treturn null;\n\t\t}\n\n\t\tdir = path.dirname(dir);\n\t}\n};\n","'use strict';\nconst path = require('path');\nconst pathExists = require('path-exists');\nconst pLocate = require('p-locate');\n\nmodule.exports = (iterable, options) => {\n\toptions = Object.assign({\n\t\tcwd: process.cwd()\n\t}, options);\n\n\treturn pLocate(iterable, el => pathExists(path.resolve(options.cwd, el)), options);\n};\n\nmodule.exports.sync = (iterable, options) => {\n\toptions = Object.assign({\n\t\tcwd: process.cwd()\n\t}, options);\n\n\tfor (const el of iterable) {\n\t\tif (pathExists.sync(path.resolve(options.cwd, el))) {\n\t\t\treturn el;\n\t\t}\n\t}\n};\n","'use strict';\nconst pLimit = require('p-limit');\n\nclass EndError extends Error {\n\tconstructor(value) {\n\t\tsuper();\n\t\tthis.value = value;\n\t}\n}\n\n// The input can also be a promise, so we `Promise.resolve()` it\nconst testElement = (el, tester) => Promise.resolve(el).then(tester);\n\n// The input can also be a promise, so we `Promise.all()` them both\nconst finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0])));\n\nmodule.exports = (iterable, tester, opts) => {\n\topts = Object.assign({\n\t\tconcurrency: Infinity,\n\t\tpreserveOrder: true\n\t}, opts);\n\n\tconst limit = pLimit(opts.concurrency);\n\n\t// Start all the promises concurrently with optional limit\n\tconst items = [...iterable].map(el => [el, limit(testElement, el, tester)]);\n\n\t// Check the promises either serially or concurrently\n\tconst checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity);\n\n\treturn Promise.all(items.map(el => checkLimit(finder, el)))\n\t\t.then(() => {})\n\t\t.catch(err => err instanceof EndError ? err.value : Promise.reject(err));\n};\n","'use strict';\nconst fs = require('fs');\n\nmodule.exports = fp => new Promise(resolve => {\n\tfs.access(fp, err => {\n\t\tresolve(!err);\n\t});\n});\n\nmodule.exports.sync = fp => {\n\ttry {\n\t\tfs.accessSync(fp);\n\t\treturn true;\n\t} catch (err) {\n\t\treturn false;\n\t}\n};\n","'use strict';\nconst ansiRegex = require('ansi-regex');\n\nconst stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;\n\nmodule.exports = stripAnsi;\nmodule.exports.default = stripAnsi;\n","'use strict';\nconst stringWidth = require('string-width');\nconst stripAnsi = require('strip-ansi');\nconst ansiStyles = require('ansi-styles');\n\nconst ESCAPES = new Set([\n\t'\\u001B',\n\t'\\u009B'\n]);\n\nconst END_CODE = 39;\n\nconst wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`;\n\n// Calculate the length of words split on ' ', ignoring\n// the extra characters added by ansi escape codes\nconst wordLengths = string => string.split(' ').map(character => stringWidth(character));\n\n// Wrap a long word across multiple rows\n// Ansi escape codes do not count towards length\nconst wrapWord = (rows, word, columns) => {\n\tconst characters = [...word];\n\n\tlet insideEscape = false;\n\tlet visible = stringWidth(stripAnsi(rows[rows.length - 1]));\n\n\tfor (const [index, character] of characters.entries()) {\n\t\tconst characterLength = stringWidth(character);\n\n\t\tif (visible + characterLength <= columns) {\n\t\t\trows[rows.length - 1] += character;\n\t\t} else {\n\t\t\trows.push(character);\n\t\t\tvisible = 0;\n\t\t}\n\n\t\tif (ESCAPES.has(character)) {\n\t\t\tinsideEscape = true;\n\t\t} else if (insideEscape && character === 'm') {\n\t\t\tinsideEscape = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (insideEscape) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tvisible += characterLength;\n\n\t\tif (visible === columns && index < characters.length - 1) {\n\t\t\trows.push('');\n\t\t\tvisible = 0;\n\t\t}\n\t}\n\n\t// It's possible that the last row we copy over is only\n\t// ansi escape characters, handle this edge-case\n\tif (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {\n\t\trows[rows.length - 2] += rows.pop();\n\t}\n};\n\n// Trims spaces from a string ignoring invisible sequences\nconst stringVisibleTrimSpacesRight = str => {\n\tconst words = str.split(' ');\n\tlet last = words.length;\n\n\twhile (last > 0) {\n\t\tif (stringWidth(words[last - 1]) > 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlast--;\n\t}\n\n\tif (last === words.length) {\n\t\treturn str;\n\t}\n\n\treturn words.slice(0, last).join(' ') + words.slice(last).join('');\n};\n\n// The wrap-ansi module can be invoked\n// in either 'hard' or 'soft' wrap mode\n//\n// 'hard' will never allow a string to take up more\n// than columns characters\n//\n// 'soft' allows long words to expand past the column length\nconst exec = (string, columns, options = {}) => {\n\tif (options.trim !== false && string.trim() === '') {\n\t\treturn '';\n\t}\n\n\tlet pre = '';\n\tlet ret = '';\n\tlet escapeCode;\n\n\tconst lengths = wordLengths(string);\n\tlet rows = [''];\n\n\tfor (const [index, word] of string.split(' ').entries()) {\n\t\tif (options.trim !== false) {\n\t\t\trows[rows.length - 1] = rows[rows.length - 1].trimLeft();\n\t\t}\n\n\t\tlet rowLength = stringWidth(rows[rows.length - 1]);\n\n\t\tif (index !== 0) {\n\t\t\tif (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {\n\t\t\t\t// If we start with a new word but the current row length equals the length of the columns, add a new row\n\t\t\t\trows.push('');\n\t\t\t\trowLength = 0;\n\t\t\t}\n\n\t\t\tif (rowLength > 0 || options.trim === false) {\n\t\t\t\trows[rows.length - 1] += ' ';\n\t\t\t\trowLength++;\n\t\t\t}\n\t\t}\n\n\t\t// In 'hard' wrap mode, the length of a line is\n\t\t// never allowed to extend past 'columns'\n\t\tif (options.hard && lengths[index] > columns) {\n\t\t\tconst remainingColumns = (columns - rowLength);\n\t\t\tconst breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);\n\t\t\tconst breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);\n\t\t\tif (breaksStartingNextLine < breaksStartingThisLine) {\n\t\t\t\trows.push('');\n\t\t\t}\n\n\t\t\twrapWord(rows, word, columns);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {\n\t\t\tif (options.wordWrap === false && rowLength < columns) {\n\t\t\t\twrapWord(rows, word, columns);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\trows.push('');\n\t\t}\n\n\t\tif (rowLength + lengths[index] > columns && options.wordWrap === false) {\n\t\t\twrapWord(rows, word, columns);\n\t\t\tcontinue;\n\t\t}\n\n\t\trows[rows.length - 1] += word;\n\t}\n\n\tif (options.trim !== false) {\n\t\trows = rows.map(stringVisibleTrimSpacesRight);\n\t}\n\n\tpre = rows.join('\\n');\n\n\tfor (const [index, character] of [...pre].entries()) {\n\t\tret += character;\n\n\t\tif (ESCAPES.has(character)) {\n\t\t\tconst code = parseFloat(/\\d[^m]*/.exec(pre.slice(index, index + 4)));\n\t\t\tescapeCode = code === END_CODE ? null : code;\n\t\t}\n\n\t\tconst code = ansiStyles.codes.get(Number(escapeCode));\n\n\t\tif (escapeCode && code) {\n\t\t\tif (pre[index + 1] === '\\n') {\n\t\t\t\tret += wrapAnsi(code);\n\t\t\t} else if (character === '\\n') {\n\t\t\t\tret += wrapAnsi(escapeCode);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ret;\n};\n\n// For each newline, invoke the method separately\nmodule.exports = (string, columns, options) => {\n\treturn String(string)\n\t\t.normalize()\n\t\t.split('\\n')\n\t\t.map(line => exec(line, columns, options))\n\t\t.join('\\n');\n};\n",null,"// take an un-split argv string and tokenize it.\nmodule.exports = function (argString) {\n if (Array.isArray(argString)) {\n return argString.map(e => typeof e !== 'string' ? e + '' : e)\n }\n\n argString = argString.trim()\n\n var i = 0\n var prevC = null\n var c = null\n var opening = null\n var args = []\n\n for (var ii = 0; ii < argString.length; ii++) {\n prevC = c\n c = argString.charAt(ii)\n\n // split on spaces unless we're in quotes.\n if (c === ' ' && !opening) {\n if (!(prevC === ' ')) {\n i++\n }\n continue\n }\n\n // don't split the string if we're in matching\n // opening or closing single and double quotes.\n if (c === opening) {\n opening = null\n } else if ((c === \"'\" || c === '\"') && !opening) {\n opening = c\n }\n\n if (!args[i]) args[i] = ''\n args[i] += c\n }\n\n return args\n}\n",null,null,"'use strict'\n\n// hoisted due to circular dependency on command.\nmodule.exports = argsert\nconst command = require('./command')()\nconst YError = require('./yerror')\n\nconst positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']\nfunction argsert (expected, callerArguments, length) {\n // TODO: should this eventually raise an exception.\n try {\n // preface the argument description with \"cmd\", so\n // that we can run it through yargs' command parser.\n let position = 0\n let parsed = { demanded: [], optional: [] }\n if (typeof expected === 'object') {\n length = callerArguments\n callerArguments = expected\n } else {\n parsed = command.parseCommand(`cmd ${expected}`)\n }\n const args = [].slice.call(callerArguments)\n\n while (args.length && args[args.length - 1] === undefined) args.pop()\n length = length || args.length\n\n if (length < parsed.demanded.length) {\n throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`)\n }\n\n const totalCommands = parsed.demanded.length + parsed.optional.length\n if (length > totalCommands) {\n throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`)\n }\n\n parsed.demanded.forEach((demanded) => {\n const arg = args.shift()\n const observedType = guessType(arg)\n const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*')\n if (matchingTypes.length === 0) argumentTypeError(observedType, demanded.cmd, position, false)\n position += 1\n })\n\n parsed.optional.forEach((optional) => {\n if (args.length === 0) return\n const arg = args.shift()\n const observedType = guessType(arg)\n const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*')\n if (matchingTypes.length === 0) argumentTypeError(observedType, optional.cmd, position, true)\n position += 1\n })\n } catch (err) {\n console.warn(err.stack)\n }\n}\n\nfunction guessType (arg) {\n if (Array.isArray(arg)) {\n return 'array'\n } else if (arg === null) {\n return 'null'\n }\n return typeof arg\n}\n\nfunction argumentTypeError (observedType, allowedTypes, position, optional) {\n throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`)\n}\n","'use strict'\n\nconst inspect = require('util').inspect\nconst isPromise = require('./is-promise')\nconst { applyMiddleware, commandMiddlewareFactory } = require('./middleware')\nconst path = require('path')\nconst Parser = require('yargs-parser')\n\nconst DEFAULT_MARKER = /(^\\*)|(^\\$0)/\n\n// handles parsing positional arguments,\n// and populating argv with said positional\n// arguments.\nmodule.exports = function command (yargs, usage, validation, globalMiddleware) {\n const self = {}\n let handlers = {}\n let aliasMap = {}\n let defaultCommand\n globalMiddleware = globalMiddleware || []\n\n self.addHandler = function addHandler (cmd, description, builder, handler, commandMiddleware) {\n let aliases = []\n const middlewares = commandMiddlewareFactory(commandMiddleware)\n handler = handler || (() => {})\n\n if (Array.isArray(cmd)) {\n aliases = cmd.slice(1)\n cmd = cmd[0]\n } else if (typeof cmd === 'object') {\n let command = (Array.isArray(cmd.command) || typeof cmd.command === 'string') ? cmd.command : moduleName(cmd)\n if (cmd.aliases) command = [].concat(command).concat(cmd.aliases)\n self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares)\n return\n }\n\n // allow a module to be provided instead of separate builder and handler\n if (typeof builder === 'object' && builder.builder && typeof builder.handler === 'function') {\n self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares)\n return\n }\n\n // parse positionals out of cmd string\n const parsedCommand = self.parseCommand(cmd)\n\n // remove positional args from aliases only\n aliases = aliases.map(alias => self.parseCommand(alias).cmd)\n\n // check for default and filter out '*''\n let isDefault = false\n const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c) => {\n if (DEFAULT_MARKER.test(c)) {\n isDefault = true\n return false\n }\n return true\n })\n\n // standardize on $0 for default command.\n if (parsedAliases.length === 0 && isDefault) parsedAliases.push('$0')\n\n // shift cmd and aliases after filtering out '*'\n if (isDefault) {\n parsedCommand.cmd = parsedAliases[0]\n aliases = parsedAliases.slice(1)\n cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd)\n }\n\n // populate aliasMap\n aliases.forEach((alias) => {\n aliasMap[alias] = parsedCommand.cmd\n })\n\n if (description !== false) {\n usage.command(cmd, description, isDefault, aliases)\n }\n\n handlers[parsedCommand.cmd] = {\n original: cmd,\n description: description,\n handler,\n builder: builder || {},\n middlewares: middlewares || [],\n demanded: parsedCommand.demanded,\n optional: parsedCommand.optional\n }\n\n if (isDefault) defaultCommand = handlers[parsedCommand.cmd]\n }\n\n self.addDirectory = function addDirectory (dir, context, req, callerFile, opts) {\n opts = opts || {}\n // disable recursion to support nested directories of subcommands\n if (typeof opts.recurse !== 'boolean') opts.recurse = false\n // exclude 'json', 'coffee' from require-directory defaults\n if (!Array.isArray(opts.extensions)) opts.extensions = ['js']\n // allow consumer to define their own visitor function\n const parentVisit = typeof opts.visit === 'function' ? opts.visit : o => o\n // call addHandler via visitor function\n opts.visit = function visit (obj, joined, filename) {\n const visited = parentVisit(obj, joined, filename)\n // allow consumer to skip modules with their own visitor\n if (visited) {\n // check for cyclic reference\n // each command file path should only be seen once per execution\n if (~context.files.indexOf(joined)) return visited\n // keep track of visited files in context.files\n context.files.push(joined)\n self.addHandler(visited)\n }\n return visited\n }\n require('require-directory')({ require: req, filename: callerFile }, dir, opts)\n }\n\n // lookup module object from require()d command and derive name\n // if module was not require()d and no name given, throw error\n function moduleName (obj) {\n const mod = require('which-module')(obj)\n if (!mod) throw new Error(`No command name given for module: ${inspect(obj)}`)\n return commandFromFilename(mod.filename)\n }\n\n // derive command name from filename\n function commandFromFilename (filename) {\n return path.basename(filename, path.extname(filename))\n }\n\n function extractDesc (obj) {\n for (let keys = ['describe', 'description', 'desc'], i = 0, l = keys.length, test; i < l; i++) {\n test = obj[keys[i]]\n if (typeof test === 'string' || typeof test === 'boolean') return test\n }\n return false\n }\n\n self.parseCommand = function parseCommand (cmd) {\n const extraSpacesStrippedCommand = cmd.replace(/\\s{2,}/g, ' ')\n const splitCommand = extraSpacesStrippedCommand.split(/\\s+(?![^[]*]|[^<]*>)/)\n const bregex = /\\.*[\\][<>]/g\n const parsedCommand = {\n cmd: (splitCommand.shift()).replace(bregex, ''),\n demanded: [],\n optional: []\n }\n splitCommand.forEach((cmd, i) => {\n let variadic = false\n cmd = cmd.replace(/\\s/g, '')\n if (/\\.+[\\]>]/.test(cmd) && i === splitCommand.length - 1) variadic = true\n if (/^\\[/.test(cmd)) {\n parsedCommand.optional.push({\n cmd: cmd.replace(bregex, '').split('|'),\n variadic\n })\n } else {\n parsedCommand.demanded.push({\n cmd: cmd.replace(bregex, '').split('|'),\n variadic\n })\n }\n })\n return parsedCommand\n }\n\n self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap))\n\n self.getCommandHandlers = () => handlers\n\n self.hasDefaultCommand = () => !!defaultCommand\n\n self.runCommand = function runCommand (command, yargs, parsed, commandIndex) {\n let aliases = parsed.aliases\n const commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand\n const currentContext = yargs.getContext()\n let numFiles = currentContext.files.length\n const parentCommands = currentContext.commands.slice()\n\n // what does yargs look like after the buidler is run?\n let innerArgv = parsed.argv\n let innerYargs = null\n let positionalMap = {}\n if (command) {\n currentContext.commands.push(command)\n currentContext.fullCommands.push(commandHandler.original)\n }\n if (typeof commandHandler.builder === 'function') {\n // a function can be provided, which builds\n // up a yargs chain and possibly returns it.\n innerYargs = commandHandler.builder(yargs.reset(parsed.aliases))\n // if the builder function did not yet parse argv with reset yargs\n // and did not explicitly set a usage() string, then apply the\n // original command string as usage() for consistent behavior with\n // options object below.\n if (yargs.parsed === false) {\n if (shouldUpdateUsage(yargs)) {\n yargs.getUsageInstance().usage(\n usageFromParentCommandsCommandHandler(parentCommands, commandHandler),\n commandHandler.description\n )\n }\n innerArgv = innerYargs ? innerYargs._parseArgs(null, null, true, commandIndex) : yargs._parseArgs(null, null, true, commandIndex)\n } else {\n innerArgv = yargs.parsed.argv\n }\n\n if (innerYargs && yargs.parsed === false) aliases = innerYargs.parsed.aliases\n else aliases = yargs.parsed.aliases\n } else if (typeof commandHandler.builder === 'object') {\n // as a short hand, an object can instead be provided, specifying\n // the options that a command takes.\n innerYargs = yargs.reset(parsed.aliases)\n if (shouldUpdateUsage(innerYargs)) {\n innerYargs.getUsageInstance().usage(\n usageFromParentCommandsCommandHandler(parentCommands, commandHandler),\n commandHandler.description\n )\n }\n Object.keys(commandHandler.builder).forEach((key) => {\n innerYargs.option(key, commandHandler.builder[key])\n })\n innerArgv = innerYargs._parseArgs(null, null, true, commandIndex)\n aliases = innerYargs.parsed.aliases\n }\n\n if (!yargs._hasOutput()) {\n positionalMap = populatePositionals(commandHandler, innerArgv, currentContext, yargs)\n }\n\n const middlewares = globalMiddleware.slice(0).concat(commandHandler.middlewares || [])\n applyMiddleware(innerArgv, yargs, middlewares, true)\n\n // we apply validation post-hoc, so that custom\n // checks get passed populated positional arguments.\n if (!yargs._hasOutput()) yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error)\n\n if (commandHandler.handler && !yargs._hasOutput()) {\n yargs._setHasOutput()\n\n innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false)\n\n const handlerResult = isPromise(innerArgv)\n ? innerArgv.then(argv => commandHandler.handler(argv))\n : commandHandler.handler(innerArgv)\n\n if (isPromise(handlerResult)) {\n handlerResult.catch(error =>\n yargs.getUsageInstance().fail(null, error)\n )\n }\n }\n\n if (command) {\n currentContext.commands.pop()\n currentContext.fullCommands.pop()\n }\n numFiles = currentContext.files.length - numFiles\n if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles)\n\n return innerArgv\n }\n\n function shouldUpdateUsage (yargs) {\n return !yargs.getUsageInstance().getUsageDisabled() &&\n yargs.getUsageInstance().getUsage().length === 0\n }\n\n function usageFromParentCommandsCommandHandler (parentCommands, commandHandler) {\n const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() : commandHandler.original\n const pc = parentCommands.filter((c) => { return !DEFAULT_MARKER.test(c) })\n pc.push(c)\n return `$0 ${pc.join(' ')}`\n }\n\n self.runDefaultBuilderOn = function (yargs) {\n if (shouldUpdateUsage(yargs)) {\n // build the root-level command string from the default string.\n const commandString = DEFAULT_MARKER.test(defaultCommand.original)\n ? defaultCommand.original : defaultCommand.original.replace(/^[^[\\]<>]*/, '$0 ')\n yargs.getUsageInstance().usage(\n commandString,\n defaultCommand.description\n )\n }\n const builder = defaultCommand.builder\n if (typeof builder === 'function') {\n builder(yargs)\n } else {\n Object.keys(builder).forEach((key) => {\n yargs.option(key, builder[key])\n })\n }\n }\n\n // transcribe all positional arguments \"command [apple]\"\n // onto argv.\n function populatePositionals (commandHandler, argv, context, yargs) {\n argv._ = argv._.slice(context.commands.length) // nuke the current commands\n const demanded = commandHandler.demanded.slice(0)\n const optional = commandHandler.optional.slice(0)\n const positionalMap = {}\n\n validation.positionalCount(demanded.length, argv._.length)\n\n while (demanded.length) {\n const demand = demanded.shift()\n populatePositional(demand, argv, positionalMap)\n }\n\n while (optional.length) {\n const maybe = optional.shift()\n populatePositional(maybe, argv, positionalMap)\n }\n\n argv._ = context.commands.concat(argv._)\n\n postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original))\n\n return positionalMap\n }\n\n function populatePositional (positional, argv, positionalMap, parseOptions) {\n const cmd = positional.cmd[0]\n if (positional.variadic) {\n positionalMap[cmd] = argv._.splice(0).map(String)\n } else {\n if (argv._.length) positionalMap[cmd] = [String(argv._.shift())]\n }\n }\n\n // we run yargs-parser against the positional arguments\n // applying the same parsing logic used for flags.\n function postProcessPositionals (argv, positionalMap, parseOptions) {\n // combine the parsing hints we've inferred from the command\n // string with explicitly configured parsing hints.\n const options = Object.assign({}, yargs.getOptions())\n options.default = Object.assign(parseOptions.default, options.default)\n options.alias = Object.assign(parseOptions.alias, options.alias)\n options.array = options.array.concat(parseOptions.array)\n delete options.config // don't load config when processing positionals.\n\n const unparsed = []\n Object.keys(positionalMap).forEach((key) => {\n positionalMap[key].map((value) => {\n unparsed.push(`--${key}`)\n unparsed.push(value)\n })\n })\n\n // short-circuit parse.\n if (!unparsed.length) return\n\n const parsed = Parser.detailed(unparsed, options)\n\n if (parsed.error) {\n yargs.getUsageInstance().fail(parsed.error.message, parsed.error)\n } else {\n // only copy over positional keys (don't overwrite\n // flag arguments that were already parsed).\n const positionalKeys = Object.keys(positionalMap)\n Object.keys(positionalMap).forEach((key) => {\n [].push.apply(positionalKeys, parsed.aliases[key])\n })\n\n Object.keys(parsed.argv).forEach((key) => {\n if (positionalKeys.indexOf(key) !== -1) {\n // any new aliases need to be placed in positionalMap, which\n // is used for validation.\n if (!positionalMap[key]) positionalMap[key] = parsed.argv[key]\n argv[key] = parsed.argv[key]\n }\n })\n }\n }\n\n self.cmdToParseOptions = function (cmdString) {\n const parseOptions = {\n array: [],\n default: {},\n alias: {},\n demand: {}\n }\n\n const parsed = self.parseCommand(cmdString)\n parsed.demanded.forEach((d) => {\n const cmds = d.cmd.slice(0)\n const cmd = cmds.shift()\n if (d.variadic) {\n parseOptions.array.push(cmd)\n parseOptions.default[cmd] = []\n }\n cmds.forEach((c) => {\n parseOptions.alias[cmd] = c\n })\n parseOptions.demand[cmd] = true\n })\n\n parsed.optional.forEach((o) => {\n const cmds = o.cmd.slice(0)\n const cmd = cmds.shift()\n if (o.variadic) {\n parseOptions.array.push(cmd)\n parseOptions.default[cmd] = []\n }\n cmds.forEach((c) => {\n parseOptions.alias[cmd] = c\n })\n })\n\n return parseOptions\n }\n\n self.reset = () => {\n handlers = {}\n aliasMap = {}\n defaultCommand = undefined\n return self\n }\n\n // used by yargs.parse() to freeze\n // the state of commands such that\n // we can apply .parse() multiple times\n // with the same yargs instance.\n let frozen\n self.freeze = () => {\n frozen = {}\n frozen.handlers = handlers\n frozen.aliasMap = aliasMap\n frozen.defaultCommand = defaultCommand\n }\n self.unfreeze = () => {\n handlers = frozen.handlers\n aliasMap = frozen.aliasMap\n defaultCommand = frozen.defaultCommand\n frozen = undefined\n }\n\n return self\n}\n","exports.completionShTemplate =\n`###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc\n# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.\n#\n_yargs_completions()\n{\n local cur_word args type_list\n\n cur_word=\"\\${COMP_WORDS[COMP_CWORD]}\"\n args=(\"\\${COMP_WORDS[@]}\")\n\n # ask yargs to generate completions.\n type_list=$({{app_path}} --get-yargs-completions \"\\${args[@]}\")\n\n COMPREPLY=( $(compgen -W \"\\${type_list}\" -- \\${cur_word}) )\n\n # if no match was found, fall back to filename completion\n if [ \\${#COMPREPLY[@]} -eq 0 ]; then\n COMPREPLY=()\n fi\n\n return 0\n}\ncomplete -o default -F _yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n`\n\nexports.completionZshTemplate = `###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc\n# or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local reply\n local si=$IFS\n IFS=$'\\n' reply=($(COMP_CWORD=\"$((CURRENT-1))\" COMP_LINE=\"$BUFFER\" COMP_POINT=\"$CURSOR\" {{app_path}} --get-yargs-completions \"\\${words[@]}\"))\n IFS=$si\n _describe 'values' reply\n}\ncompdef _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n`\n","'use strict'\nconst path = require('path')\n\n// add bash completions to your\n// yargs-powered applications.\nmodule.exports = function completion (yargs, usage, command) {\n const self = {\n completionKey: 'get-yargs-completions'\n }\n\n const zshShell = process.env.SHELL && process.env.SHELL.indexOf('zsh') !== -1\n // get a list of completion commands.\n // 'args' is the array of strings from the line to be completed\n self.getCompletion = function getCompletion (args, done) {\n const completions = []\n const current = args.length ? args[args.length - 1] : ''\n const argv = yargs.parse(args, true)\n const aliases = yargs.parsed.aliases\n const parentCommands = yargs.getContext().commands\n\n // a custom completion function can be provided\n // to completion().\n if (completionFunction) {\n if (completionFunction.length < 3) {\n const result = completionFunction(current, argv)\n\n // promise based completion function.\n if (typeof result.then === 'function') {\n return result.then((list) => {\n process.nextTick(() => { done(list) })\n }).catch((err) => {\n process.nextTick(() => { throw err })\n })\n }\n\n // synchronous completion function.\n return done(result)\n } else {\n // asynchronous completion function\n return completionFunction(current, argv, (completions) => {\n done(completions)\n })\n }\n }\n\n const handlers = command.getCommandHandlers()\n for (let i = 0, ii = args.length; i < ii; ++i) {\n if (handlers[args[i]] && handlers[args[i]].builder) {\n const builder = handlers[args[i]].builder\n if (typeof builder === 'function') {\n const y = yargs.reset()\n builder(y)\n return y.argv\n }\n }\n }\n\n if (!current.match(/^-/) && parentCommands[parentCommands.length - 1] !== current) {\n usage.getCommands().forEach((usageCommand) => {\n const commandName = command.parseCommand(usageCommand[0]).cmd\n if (args.indexOf(commandName) === -1) {\n if (!zshShell) {\n completions.push(commandName)\n } else {\n const desc = usageCommand[1] || ''\n completions.push(commandName.replace(/:/g, '\\\\:') + ':' + desc)\n }\n }\n })\n }\n\n if (current.match(/^-/) || (current === '' && completions.length === 0)) {\n const descs = usage.getDescriptions()\n Object.keys(yargs.getOptions().key).forEach((key) => {\n // If the key and its aliases aren't in 'args', add the key to 'completions'\n const keyAndAliases = [key].concat(aliases[key] || [])\n const notInArgs = keyAndAliases.every(val => args.indexOf(`--${val}`) === -1)\n if (notInArgs) {\n if (!zshShell) {\n completions.push(`--${key}`)\n } else {\n const desc = descs[key] || ''\n completions.push(`--${key.replace(/:/g, '\\\\:')}:${desc.replace('__yargsString__:', '')}`)\n }\n }\n })\n }\n\n done(completions)\n }\n\n // generate the completion script to add to your .bashrc.\n self.generateCompletionScript = function generateCompletionScript ($0, cmd) {\n const templates = require('./completion-templates')\n let script = zshShell ? templates.completionZshTemplate : templates.completionShTemplate\n const name = path.basename($0)\n\n // add ./to applications not yet installed as bin.\n if ($0.match(/\\.js$/)) $0 = `./${$0}`\n\n script = script.replace(/{{app_name}}/g, name)\n script = script.replace(/{{completion_command}}/g, cmd)\n return script.replace(/{{app_path}}/g, $0)\n }\n\n // register a function to perform your own custom\n // completions., this function can be either\n // synchrnous or asynchronous.\n let completionFunction = null\n self.registerFunction = (fn) => {\n completionFunction = fn\n }\n\n return self\n}\n","/*\nMIT License\n\nCopyright (c) Sindre Sorhus (sindresorhus.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n'use strict'\n\nmodule.exports = (text, separator) => {\n separator = typeof separator === 'undefined' ? '_' : separator\n\n return text\n .replace(/([a-z\\d])([A-Z])/g, `$1${separator}$2`)\n .replace(/([A-Z]+)([A-Z][a-z\\d]+)/g, `$1${separator}$2`)\n .toLowerCase()\n}\n","module.exports = function isPromise (maybePromise) {\n return maybePromise instanceof Promise\n}\n","/*\nCopyright (c) 2011 Andrei Mackenzie\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n// levenshtein distance algorithm, pulled from Andrei Mackenzie's MIT licensed.\n// gist, which can be found here: https://gist.github.com/andrei-m/982927\n'use strict'\n// Compute the edit distance between the two given strings\nmodule.exports = function levenshtein (a, b) {\n if (a.length === 0) return b.length\n if (b.length === 0) return a.length\n\n const matrix = []\n\n // increment along the first column of each row\n let i\n for (i = 0; i <= b.length; i++) {\n matrix[i] = [i]\n }\n\n // increment each column in the first row\n let j\n for (j = 0; j <= a.length; j++) {\n matrix[0][j] = j\n }\n\n // Fill in the rest of the matrix\n for (i = 1; i <= b.length; i++) {\n for (j = 1; j <= a.length; j++) {\n if (b.charAt(i - 1) === a.charAt(j - 1)) {\n matrix[i][j] = matrix[i - 1][j - 1]\n } else {\n matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution\n Math.min(matrix[i][j - 1] + 1, // insertion\n matrix[i - 1][j] + 1)) // deletion\n }\n }\n }\n\n return matrix[b.length][a.length]\n}\n","'use strict'\n\n// hoisted due to circular dependency on command.\nmodule.exports = {\n applyMiddleware,\n commandMiddlewareFactory,\n globalMiddlewareFactory\n}\nconst isPromise = require('./is-promise')\nconst argsert = require('./argsert')\n\nfunction globalMiddlewareFactory (globalMiddleware, context) {\n return function (callback, applyBeforeValidation = false) {\n argsert(' [boolean]', [callback, applyBeforeValidation], arguments.length)\n if (Array.isArray(callback)) {\n for (let i = 0; i < callback.length; i++) {\n if (typeof callback[i] !== 'function') {\n throw Error('middleware must be a function')\n }\n callback[i].applyBeforeValidation = applyBeforeValidation\n }\n Array.prototype.push.apply(globalMiddleware, callback)\n } else if (typeof callback === 'function') {\n callback.applyBeforeValidation = applyBeforeValidation\n globalMiddleware.push(callback)\n }\n return context\n }\n}\n\nfunction commandMiddlewareFactory (commandMiddleware) {\n if (!commandMiddleware) return []\n return commandMiddleware.map(middleware => {\n middleware.applyBeforeValidation = false\n return middleware\n })\n}\n\nfunction applyMiddleware (argv, yargs, middlewares, beforeValidation) {\n const beforeValidationError = new Error('middleware cannot return a promise when applyBeforeValidation is true')\n return middlewares\n .reduce((accumulation, middleware) => {\n if (middleware.applyBeforeValidation !== beforeValidation &&\n !isPromise(accumulation)) {\n return accumulation\n }\n\n if (isPromise(accumulation)) {\n return accumulation\n .then(initialObj =>\n Promise.all([initialObj, middleware(initialObj, yargs)])\n )\n .then(([initialObj, middlewareObj]) =>\n Object.assign(initialObj, middlewareObj)\n )\n } else {\n const result = middleware(argv, yargs)\n if (beforeValidation && isPromise(result)) throw beforeValidationError\n\n return isPromise(result)\n ? result.then(middlewareObj => Object.assign(accumulation, middlewareObj))\n : Object.assign(accumulation, result)\n }\n }, argv)\n}\n","'use strict'\nmodule.exports = function objFilter (original, filter) {\n const obj = {}\n filter = filter || ((k, v) => true)\n Object.keys(original || {}).forEach((key) => {\n if (filter(key, original[key])) {\n obj[key] = original[key]\n }\n })\n return obj\n}\n","'use strict'\n// this file handles outputting usage instructions,\n// failures, etc. keeps logging in one place.\nconst decamelize = require('./decamelize')\nconst stringWidth = require('string-width')\nconst objFilter = require('./obj-filter')\nconst path = require('path')\nconst setBlocking = require('set-blocking')\nconst YError = require('./yerror')\n\nmodule.exports = function usage (yargs, y18n) {\n const __ = y18n.__\n const self = {}\n\n // methods for ouputting/building failure message.\n const fails = []\n self.failFn = function failFn (f) {\n fails.push(f)\n }\n\n let failMessage = null\n let showHelpOnFail = true\n self.showHelpOnFail = function showHelpOnFailFn (enabled, message) {\n if (typeof enabled === 'string') {\n message = enabled\n enabled = true\n } else if (typeof enabled === 'undefined') {\n enabled = true\n }\n failMessage = message\n showHelpOnFail = enabled\n return self\n }\n\n let failureOutput = false\n self.fail = function fail (msg, err) {\n const logger = yargs._getLoggerInstance()\n\n if (fails.length) {\n for (let i = fails.length - 1; i >= 0; --i) {\n fails[i](msg, err, self)\n }\n } else {\n if (yargs.getExitProcess()) setBlocking(true)\n\n // don't output failure message more than once\n if (!failureOutput) {\n failureOutput = true\n if (showHelpOnFail) {\n yargs.showHelp('error')\n logger.error()\n }\n if (msg || err) logger.error(msg || err)\n if (failMessage) {\n if (msg || err) logger.error('')\n logger.error(failMessage)\n }\n }\n\n err = err || new YError(msg)\n if (yargs.getExitProcess()) {\n return yargs.exit(1)\n } else if (yargs._hasParseCallback()) {\n return yargs.exit(1, err)\n } else {\n throw err\n }\n }\n }\n\n // methods for ouputting/building help (usage) message.\n let usages = []\n let usageDisabled = false\n self.usage = (msg, description) => {\n if (msg === null) {\n usageDisabled = true\n usages = []\n return\n }\n usageDisabled = false\n usages.push([msg, description || ''])\n return self\n }\n self.getUsage = () => {\n return usages\n }\n self.getUsageDisabled = () => {\n return usageDisabled\n }\n\n self.getPositionalGroupName = () => {\n return __('Positionals:')\n }\n\n let examples = []\n self.example = (cmd, description) => {\n examples.push([cmd, description || ''])\n }\n\n let commands = []\n self.command = function command (cmd, description, isDefault, aliases) {\n // the last default wins, so cancel out any previously set default\n if (isDefault) {\n commands = commands.map((cmdArray) => {\n cmdArray[2] = false\n return cmdArray\n })\n }\n commands.push([cmd, description || '', isDefault, aliases])\n }\n self.getCommands = () => commands\n\n let descriptions = {}\n self.describe = function describe (key, desc) {\n if (typeof key === 'object') {\n Object.keys(key).forEach((k) => {\n self.describe(k, key[k])\n })\n } else {\n descriptions[key] = desc\n }\n }\n self.getDescriptions = () => descriptions\n\n let epilog\n self.epilog = (msg) => {\n epilog = msg\n }\n\n let wrapSet = false\n let wrap\n self.wrap = (cols) => {\n wrapSet = true\n wrap = cols\n }\n\n function getWrap () {\n if (!wrapSet) {\n wrap = windowWidth()\n wrapSet = true\n }\n\n return wrap\n }\n\n const deferY18nLookupPrefix = '__yargsString__:'\n self.deferY18nLookup = str => deferY18nLookupPrefix + str\n\n const defaultGroup = 'Options:'\n self.help = function help () {\n normalizeAliases()\n\n // handle old demanded API\n const base$0 = path.basename(yargs.$0)\n const demandedOptions = yargs.getDemandedOptions()\n const demandedCommands = yargs.getDemandedCommands()\n const groups = yargs.getGroups()\n const options = yargs.getOptions()\n\n let keys = []\n keys = keys.concat(Object.keys(descriptions))\n keys = keys.concat(Object.keys(demandedOptions))\n keys = keys.concat(Object.keys(demandedCommands))\n keys = keys.concat(Object.keys(options.default))\n keys = keys.filter(filterHiddenOptions)\n keys = Object.keys(keys.reduce((acc, key) => {\n if (key !== '_') acc[key] = true\n return acc\n }, {}))\n\n const theWrap = getWrap()\n const ui = require('cliui')({\n width: theWrap,\n wrap: !!theWrap\n })\n\n // the usage string.\n if (!usageDisabled) {\n if (usages.length) {\n // user-defined usage.\n usages.forEach((usage) => {\n ui.div(`${usage[0].replace(/\\$0/g, base$0)}`)\n if (usage[1]) {\n ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] })\n }\n })\n ui.div()\n } else if (commands.length) {\n let u = null\n // demonstrate how commands are used.\n if (demandedCommands._) {\n u = `${base$0} <${__('command')}>\\n`\n } else {\n u = `${base$0} [${__('command')}]\\n`\n }\n ui.div(`${u}`)\n }\n }\n\n // your application's commands, i.e., non-option\n // arguments populated in '_'.\n if (commands.length) {\n ui.div(__('Commands:'))\n\n const context = yargs.getContext()\n const parentCommands = context.commands.length ? `${context.commands.join(' ')} ` : ''\n\n if (yargs.getParserConfiguration()['sort-commands'] === true) {\n commands = commands.sort((a, b) => a[0].localeCompare(b[0]))\n }\n\n commands.forEach((command) => {\n const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\\$0 ?/, '')}` // drop $0 from default commands.\n ui.span(\n {\n text: commandString,\n padding: [0, 2, 0, 2],\n width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4\n },\n { text: command[1] }\n )\n const hints = []\n if (command[2]) hints.push(`[${__('default:').slice(0, -1)}]`) // TODO hacking around i18n here\n if (command[3] && command[3].length) {\n hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`)\n }\n if (hints.length) {\n ui.div({ text: hints.join(' '), padding: [0, 0, 0, 2], align: 'right' })\n } else {\n ui.div()\n }\n })\n\n ui.div()\n }\n\n // perform some cleanup on the keys array, making it\n // only include top-level keys not their aliases.\n const aliasKeys = (Object.keys(options.alias) || [])\n .concat(Object.keys(yargs.parsed.newAliases) || [])\n\n keys = keys.filter(key => !yargs.parsed.newAliases[key] && aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1))\n\n // populate 'Options:' group with any keys that have not\n // explicitly had a group set.\n if (!groups[defaultGroup]) groups[defaultGroup] = []\n addUngroupedKeys(keys, options.alias, groups)\n\n // display 'Options:' table along with any custom tables:\n Object.keys(groups).forEach((groupName) => {\n if (!groups[groupName].length) return\n\n // if we've grouped the key 'f', but 'f' aliases 'foobar',\n // normalizedKeys should contain only 'foobar'.\n const normalizedKeys = groups[groupName].filter(filterHiddenOptions).map((key) => {\n if (~aliasKeys.indexOf(key)) return key\n for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {\n if (~(options.alias[aliasKey] || []).indexOf(key)) return aliasKey\n }\n return key\n })\n\n if (normalizedKeys.length < 1) return\n\n ui.div(__(groupName))\n\n // actually generate the switches string --foo, -f, --bar.\n const switches = normalizedKeys.reduce((acc, key) => {\n acc[key] = [ key ].concat(options.alias[key] || [])\n .map(sw => {\n // for the special positional group don't\n // add '--' or '-' prefix.\n if (groupName === self.getPositionalGroupName()) return sw\n else return (sw.length > 1 ? '--' : '-') + sw\n })\n .join(', ')\n\n return acc\n }, {})\n\n normalizedKeys.forEach((key) => {\n const kswitch = switches[key]\n let desc = descriptions[key] || ''\n let type = null\n\n if (~desc.lastIndexOf(deferY18nLookupPrefix)) desc = __(desc.substring(deferY18nLookupPrefix.length))\n\n if (~options.boolean.indexOf(key)) type = `[${__('boolean')}]`\n if (~options.count.indexOf(key)) type = `[${__('count')}]`\n if (~options.string.indexOf(key)) type = `[${__('string')}]`\n if (~options.normalize.indexOf(key)) type = `[${__('string')}]`\n if (~options.array.indexOf(key)) type = `[${__('array')}]`\n if (~options.number.indexOf(key)) type = `[${__('number')}]`\n\n const extra = [\n type,\n (key in demandedOptions) ? `[${__('required')}]` : null,\n options.choices && options.choices[key] ? `[${__('choices:')} ${\n self.stringifiedValues(options.choices[key])}]` : null,\n defaultString(options.default[key], options.defaultDescription[key])\n ].filter(Boolean).join(' ')\n\n ui.span(\n { text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches, theWrap) + 4 },\n desc\n )\n\n if (extra) ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' })\n else ui.div()\n })\n\n ui.div()\n })\n\n // describe some common use-cases for your application.\n if (examples.length) {\n ui.div(__('Examples:'))\n\n examples.forEach((example) => {\n example[0] = example[0].replace(/\\$0/g, base$0)\n })\n\n examples.forEach((example) => {\n if (example[1] === '') {\n ui.div(\n {\n text: example[0],\n padding: [0, 2, 0, 2]\n }\n )\n } else {\n ui.div(\n {\n text: example[0],\n padding: [0, 2, 0, 2],\n width: maxWidth(examples, theWrap) + 4\n }, {\n text: example[1]\n }\n )\n }\n })\n\n ui.div()\n }\n\n // the usage string.\n if (epilog) {\n const e = epilog.replace(/\\$0/g, base$0)\n ui.div(`${e}\\n`)\n }\n\n // Remove the trailing white spaces\n return ui.toString().replace(/\\s*$/, '')\n }\n\n // return the maximum width of a string\n // in the left-hand column of a table.\n function maxWidth (table, theWrap, modifier) {\n let width = 0\n\n // table might be of the form [leftColumn],\n // or {key: leftColumn}\n if (!Array.isArray(table)) {\n table = Object.keys(table).map(key => [table[key]])\n }\n\n table.forEach((v) => {\n width = Math.max(\n stringWidth(modifier ? `${modifier} ${v[0]}` : v[0]),\n width\n )\n })\n\n // if we've enabled 'wrap' we should limit\n // the max-width of the left-column.\n if (theWrap) width = Math.min(width, parseInt(theWrap * 0.5, 10))\n\n return width\n }\n\n // make sure any options set for aliases,\n // are copied to the keys being aliased.\n function normalizeAliases () {\n // handle old demanded API\n const demandedOptions = yargs.getDemandedOptions()\n const options = yargs.getOptions()\n\n ;(Object.keys(options.alias) || []).forEach((key) => {\n options.alias[key].forEach((alias) => {\n // copy descriptions.\n if (descriptions[alias]) self.describe(key, descriptions[alias])\n // copy demanded.\n if (alias in demandedOptions) yargs.demandOption(key, demandedOptions[alias])\n // type messages.\n if (~options.boolean.indexOf(alias)) yargs.boolean(key)\n if (~options.count.indexOf(alias)) yargs.count(key)\n if (~options.string.indexOf(alias)) yargs.string(key)\n if (~options.normalize.indexOf(alias)) yargs.normalize(key)\n if (~options.array.indexOf(alias)) yargs.array(key)\n if (~options.number.indexOf(alias)) yargs.number(key)\n })\n })\n }\n\n // given a set of keys, place any keys that are\n // ungrouped under the 'Options:' grouping.\n function addUngroupedKeys (keys, aliases, groups) {\n let groupedKeys = []\n let toCheck = null\n Object.keys(groups).forEach((group) => {\n groupedKeys = groupedKeys.concat(groups[group])\n })\n\n keys.forEach((key) => {\n toCheck = [key].concat(aliases[key])\n if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {\n groups[defaultGroup].push(key)\n }\n })\n return groupedKeys\n }\n\n function filterHiddenOptions (key) {\n return yargs.getOptions().hiddenOptions.indexOf(key) < 0 || yargs.parsed.argv[yargs.getOptions().showHiddenOpt]\n }\n\n self.showHelp = (level) => {\n const logger = yargs._getLoggerInstance()\n if (!level) level = 'error'\n const emit = typeof level === 'function' ? level : logger[level]\n emit(self.help())\n }\n\n self.functionDescription = (fn) => {\n const description = fn.name ? decamelize(fn.name, '-') : __('generated-value')\n return ['(', description, ')'].join('')\n }\n\n self.stringifiedValues = function stringifiedValues (values, separator) {\n let string = ''\n const sep = separator || ', '\n const array = [].concat(values)\n\n if (!values || !array.length) return string\n\n array.forEach((value) => {\n if (string.length) string += sep\n string += JSON.stringify(value)\n })\n\n return string\n }\n\n // format the default-value-string displayed in\n // the right-hand column.\n function defaultString (value, defaultDescription) {\n let string = `[${__('default:')} `\n\n if (value === undefined && !defaultDescription) return null\n\n if (defaultDescription) {\n string += defaultDescription\n } else {\n switch (typeof value) {\n case 'string':\n string += `\"${value}\"`\n break\n case 'object':\n string += JSON.stringify(value)\n break\n default:\n string += value\n }\n }\n\n return `${string}]`\n }\n\n // guess the width of the console window, max-width 80.\n function windowWidth () {\n const maxWidth = 80\n if (typeof process === 'object' && process.stdout && process.stdout.columns) {\n return Math.min(maxWidth, process.stdout.columns)\n } else {\n return maxWidth\n }\n }\n\n // logic for displaying application version.\n let version = null\n self.version = (ver) => {\n version = ver\n }\n\n self.showVersion = () => {\n const logger = yargs._getLoggerInstance()\n logger.log(version)\n }\n\n self.reset = function reset (localLookup) {\n // do not reset wrap here\n // do not reset fails here\n failMessage = null\n failureOutput = false\n usages = []\n usageDisabled = false\n epilog = undefined\n examples = []\n commands = []\n descriptions = objFilter(descriptions, (k, v) => !localLookup[k])\n return self\n }\n\n let frozen\n self.freeze = function freeze () {\n frozen = {}\n frozen.failMessage = failMessage\n frozen.failureOutput = failureOutput\n frozen.usages = usages\n frozen.usageDisabled = usageDisabled\n frozen.epilog = epilog\n frozen.examples = examples\n frozen.commands = commands\n frozen.descriptions = descriptions\n }\n self.unfreeze = function unfreeze () {\n failMessage = frozen.failMessage\n failureOutput = frozen.failureOutput\n usages = frozen.usages\n usageDisabled = frozen.usageDisabled\n epilog = frozen.epilog\n examples = frozen.examples\n commands = frozen.commands\n descriptions = frozen.descriptions\n frozen = undefined\n }\n\n return self\n}\n","'use strict'\nconst argsert = require('./argsert')\nconst objFilter = require('./obj-filter')\nconst specialKeys = ['$0', '--', '_']\n\n// validation-type-stuff, missing params,\n// bad implications, custom checks.\nmodule.exports = function validation (yargs, usage, y18n) {\n const __ = y18n.__\n const __n = y18n.__n\n const self = {}\n\n // validate appropriate # of non-option\n // arguments were provided, i.e., '_'.\n self.nonOptionCount = function nonOptionCount (argv) {\n const demandedCommands = yargs.getDemandedCommands()\n // don't count currently executing commands\n const _s = argv._.length - yargs.getContext().commands.length\n\n if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) {\n if (_s < demandedCommands._.min) {\n if (demandedCommands._.minMsg !== undefined) {\n usage.fail(\n // replace $0 with observed, $1 with expected.\n demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\\$0/g, _s).replace(/\\$1/, demandedCommands._.min) : null\n )\n } else {\n usage.fail(\n __('Not enough non-option arguments: got %s, need at least %s', _s, demandedCommands._.min)\n )\n }\n } else if (_s > demandedCommands._.max) {\n if (demandedCommands._.maxMsg !== undefined) {\n usage.fail(\n // replace $0 with observed, $1 with expected.\n demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\\$0/g, _s).replace(/\\$1/, demandedCommands._.max) : null\n )\n } else {\n usage.fail(\n __('Too many non-option arguments: got %s, maximum of %s', _s, demandedCommands._.max)\n )\n }\n }\n }\n }\n\n // validate the appropriate # of \n // positional arguments were provided:\n self.positionalCount = function positionalCount (required, observed) {\n if (observed < required) {\n usage.fail(\n __('Not enough non-option arguments: got %s, need at least %s', observed, required)\n )\n }\n }\n\n // make sure all the required arguments are present.\n self.requiredArguments = function requiredArguments (argv) {\n const demandedOptions = yargs.getDemandedOptions()\n let missing = null\n\n Object.keys(demandedOptions).forEach((key) => {\n if (!argv.hasOwnProperty(key) || typeof argv[key] === 'undefined') {\n missing = missing || {}\n missing[key] = demandedOptions[key]\n }\n })\n\n if (missing) {\n const customMsgs = []\n Object.keys(missing).forEach((key) => {\n const msg = missing[key]\n if (msg && customMsgs.indexOf(msg) < 0) {\n customMsgs.push(msg)\n }\n })\n\n const customMsg = customMsgs.length ? `\\n${customMsgs.join('\\n')}` : ''\n\n usage.fail(__n(\n 'Missing required argument: %s',\n 'Missing required arguments: %s',\n Object.keys(missing).length,\n Object.keys(missing).join(', ') + customMsg\n ))\n }\n }\n\n // check for unknown arguments (strict-mode).\n self.unknownArguments = function unknownArguments (argv, aliases, positionalMap) {\n const commandKeys = yargs.getCommandInstance().getCommands()\n const unknown = []\n const currentContext = yargs.getContext()\n\n Object.keys(argv).forEach((key) => {\n if (specialKeys.indexOf(key) === -1 &&\n !positionalMap.hasOwnProperty(key) &&\n !yargs._getParseContext().hasOwnProperty(key) &&\n !aliases.hasOwnProperty(key)\n ) {\n unknown.push(key)\n }\n })\n\n if (commandKeys.length > 0) {\n argv._.slice(currentContext.commands.length).forEach((key) => {\n if (commandKeys.indexOf(key) === -1) {\n unknown.push(key)\n }\n })\n }\n\n if (unknown.length > 0) {\n usage.fail(__n(\n 'Unknown argument: %s',\n 'Unknown arguments: %s',\n unknown.length,\n unknown.join(', ')\n ))\n }\n }\n\n // validate arguments limited to enumerated choices\n self.limitedChoices = function limitedChoices (argv) {\n const options = yargs.getOptions()\n const invalid = {}\n\n if (!Object.keys(options.choices).length) return\n\n Object.keys(argv).forEach((key) => {\n if (specialKeys.indexOf(key) === -1 &&\n options.choices.hasOwnProperty(key)) {\n [].concat(argv[key]).forEach((value) => {\n // TODO case-insensitive configurability\n if (options.choices[key].indexOf(value) === -1 &&\n value !== undefined) {\n invalid[key] = (invalid[key] || []).concat(value)\n }\n })\n }\n })\n\n const invalidKeys = Object.keys(invalid)\n\n if (!invalidKeys.length) return\n\n let msg = __('Invalid values:')\n invalidKeys.forEach((key) => {\n msg += `\\n ${__(\n 'Argument: %s, Given: %s, Choices: %s',\n key,\n usage.stringifiedValues(invalid[key]),\n usage.stringifiedValues(options.choices[key])\n )}`\n })\n usage.fail(msg)\n }\n\n // custom checks, added using the `check` option on yargs.\n let checks = []\n self.check = function check (f, global) {\n checks.push({\n func: f,\n global\n })\n }\n\n self.customChecks = function customChecks (argv, aliases) {\n for (let i = 0, f; (f = checks[i]) !== undefined; i++) {\n const func = f.func\n let result = null\n try {\n result = func(argv, aliases)\n } catch (err) {\n usage.fail(err.message ? err.message : err, err)\n continue\n }\n\n if (!result) {\n usage.fail(__('Argument check failed: %s', func.toString()))\n } else if (typeof result === 'string' || result instanceof Error) {\n usage.fail(result.toString(), result)\n }\n }\n }\n\n // check implications, argument foo implies => argument bar.\n let implied = {}\n self.implies = function implies (key, value) {\n argsert(' [array|number|string]', [key, value], arguments.length)\n\n if (typeof key === 'object') {\n Object.keys(key).forEach((k) => {\n self.implies(k, key[k])\n })\n } else {\n yargs.global(key)\n if (!implied[key]) {\n implied[key] = []\n }\n if (Array.isArray(value)) {\n value.forEach((i) => self.implies(key, i))\n } else {\n implied[key].push(value)\n }\n }\n }\n self.getImplied = function getImplied () {\n return implied\n }\n\n self.implications = function implications (argv) {\n const implyFail = []\n\n Object.keys(implied).forEach((key) => {\n const origKey = key\n ;(implied[key] || []).forEach((value) => {\n let num\n let key = origKey\n const origValue = value\n\n // convert string '1' to number 1\n num = Number(key)\n key = isNaN(num) ? key : num\n\n if (typeof key === 'number') {\n // check length of argv._\n key = argv._.length >= key\n } else if (key.match(/^--no-.+/)) {\n // check if key doesn't exist\n key = key.match(/^--no-(.+)/)[1]\n key = !argv[key]\n } else {\n // check if key exists\n key = argv[key]\n }\n\n num = Number(value)\n value = isNaN(num) ? value : num\n\n if (typeof value === 'number') {\n value = argv._.length >= value\n } else if (value.match(/^--no-.+/)) {\n value = value.match(/^--no-(.+)/)[1]\n value = !argv[value]\n } else {\n value = argv[value]\n }\n if (key && !value) {\n implyFail.push(` ${origKey} -> ${origValue}`)\n }\n })\n })\n\n if (implyFail.length) {\n let msg = `${__('Implications failed:')}\\n`\n\n implyFail.forEach((value) => {\n msg += (value)\n })\n\n usage.fail(msg)\n }\n }\n\n let conflicting = {}\n self.conflicts = function conflicts (key, value) {\n argsert(' [array|string]', [key, value], arguments.length)\n\n if (typeof key === 'object') {\n Object.keys(key).forEach((k) => {\n self.conflicts(k, key[k])\n })\n } else {\n yargs.global(key)\n if (!conflicting[key]) {\n conflicting[key] = []\n }\n if (Array.isArray(value)) {\n value.forEach((i) => self.conflicts(key, i))\n } else {\n conflicting[key].push(value)\n }\n }\n }\n self.getConflicting = () => conflicting\n\n self.conflicting = function conflictingFn (argv) {\n Object.keys(argv).forEach((key) => {\n if (conflicting[key]) {\n conflicting[key].forEach((value) => {\n // we default keys to 'undefined' that have been configured, we should not\n // apply conflicting check unless they are a value other than 'undefined'.\n if (value && argv[key] !== undefined && argv[value] !== undefined) {\n usage.fail(__('Arguments %s and %s are mutually exclusive', key, value))\n }\n })\n }\n })\n }\n\n self.recommendCommands = function recommendCommands (cmd, potentialCommands) {\n const distance = require('./levenshtein')\n const threshold = 3 // if it takes more than three edits, let's move on.\n potentialCommands = potentialCommands.sort((a, b) => b.length - a.length)\n\n let recommended = null\n let bestDistance = Infinity\n for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {\n const d = distance(cmd, candidate)\n if (d <= threshold && d < bestDistance) {\n bestDistance = d\n recommended = candidate\n }\n }\n if (recommended) usage.fail(__('Did you mean %s?', recommended))\n }\n\n self.reset = function reset (localLookup) {\n implied = objFilter(implied, (k, v) => !localLookup[k])\n conflicting = objFilter(conflicting, (k, v) => !localLookup[k])\n checks = checks.filter(c => c.global)\n return self\n }\n\n let frozen\n self.freeze = function freeze () {\n frozen = {}\n frozen.implied = implied\n frozen.checks = checks\n frozen.conflicting = conflicting\n }\n self.unfreeze = function unfreeze () {\n implied = frozen.implied\n checks = frozen.checks\n conflicting = frozen.conflicting\n frozen = undefined\n }\n\n return self\n}\n","'use strict'\nfunction YError (msg) {\n this.name = 'YError'\n this.message = msg || 'yargs error'\n Error.captureStackTrace(this, YError)\n}\n\nYError.prototype = Object.create(Error.prototype)\nYError.prototype.constructor = YError\n\nmodule.exports = YError\n",null,"module.exports = require('./lib/tunnel');\n","'use strict';\n\nvar net = require('net');\nvar tls = require('tls');\nvar http = require('http');\nvar https = require('https');\nvar events = require('events');\nvar assert = require('assert');\nvar util = require('util');\n\n\nexports.httpOverHttp = httpOverHttp;\nexports.httpsOverHttp = httpsOverHttp;\nexports.httpOverHttps = httpOverHttps;\nexports.httpsOverHttps = httpsOverHttps;\n\n\nfunction httpOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n return agent;\n}\n\nfunction httpsOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\nfunction httpOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n return agent;\n}\n\nfunction httpsOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\n\nfunction TunnelingAgent(options) {\n var self = this;\n self.options = options || {};\n self.proxyOptions = self.options.proxy || {};\n self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;\n self.requests = [];\n self.sockets = [];\n\n self.on('free', function onFree(socket, host, port, localAddress) {\n var options = toOptions(host, port, localAddress);\n for (var i = 0, len = self.requests.length; i < len; ++i) {\n var pending = self.requests[i];\n if (pending.host === options.host && pending.port === options.port) {\n // Detect the request to connect same origin server,\n // reuse the connection.\n self.requests.splice(i, 1);\n pending.request.onSocket(socket);\n return;\n }\n }\n socket.destroy();\n self.removeSocket(socket);\n });\n}\nutil.inherits(TunnelingAgent, events.EventEmitter);\n\nTunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {\n var self = this;\n var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));\n\n if (self.sockets.length >= this.maxSockets) {\n // We are over limit so we'll add it to the queue.\n self.requests.push(options);\n return;\n }\n\n // If we are under maxSockets create a new one.\n self.createSocket(options, function(socket) {\n socket.on('free', onFree);\n socket.on('close', onCloseOrRemove);\n socket.on('agentRemove', onCloseOrRemove);\n req.onSocket(socket);\n\n function onFree() {\n self.emit('free', socket, options);\n }\n\n function onCloseOrRemove(err) {\n self.removeSocket(socket);\n socket.removeListener('free', onFree);\n socket.removeListener('close', onCloseOrRemove);\n socket.removeListener('agentRemove', onCloseOrRemove);\n }\n });\n};\n\nTunnelingAgent.prototype.createSocket = function createSocket(options, cb) {\n var self = this;\n var placeholder = {};\n self.sockets.push(placeholder);\n\n var connectOptions = mergeOptions({}, self.proxyOptions, {\n method: 'CONNECT',\n path: options.host + ':' + options.port,\n agent: false,\n headers: {\n host: options.host + ':' + options.port\n }\n });\n if (options.localAddress) {\n connectOptions.localAddress = options.localAddress;\n }\n if (connectOptions.proxyAuth) {\n connectOptions.headers = connectOptions.headers || {};\n connectOptions.headers['Proxy-Authorization'] = 'Basic ' +\n new Buffer(connectOptions.proxyAuth).toString('base64');\n }\n\n debug('making CONNECT request');\n var connectReq = self.request(connectOptions);\n connectReq.useChunkedEncodingByDefault = false; // for v0.6\n connectReq.once('response', onResponse); // for v0.6\n connectReq.once('upgrade', onUpgrade); // for v0.6\n connectReq.once('connect', onConnect); // for v0.7 or later\n connectReq.once('error', onError);\n connectReq.end();\n\n function onResponse(res) {\n // Very hacky. This is necessary to avoid http-parser leaks.\n res.upgrade = true;\n }\n\n function onUpgrade(res, socket, head) {\n // Hacky.\n process.nextTick(function() {\n onConnect(res, socket, head);\n });\n }\n\n function onConnect(res, socket, head) {\n connectReq.removeAllListeners();\n socket.removeAllListeners();\n\n if (res.statusCode !== 200) {\n debug('tunneling socket could not be established, statusCode=%d',\n res.statusCode);\n socket.destroy();\n var error = new Error('tunneling socket could not be established, ' +\n 'statusCode=' + res.statusCode);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n if (head.length > 0) {\n debug('got illegal response body from proxy');\n socket.destroy();\n var error = new Error('got illegal response body from proxy');\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n debug('tunneling connection has established');\n self.sockets[self.sockets.indexOf(placeholder)] = socket;\n return cb(socket);\n }\n\n function onError(cause) {\n connectReq.removeAllListeners();\n\n debug('tunneling socket could not be established, cause=%s\\n',\n cause.message, cause.stack);\n var error = new Error('tunneling socket could not be established, ' +\n 'cause=' + cause.message);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n }\n};\n\nTunnelingAgent.prototype.removeSocket = function removeSocket(socket) {\n var pos = this.sockets.indexOf(socket)\n if (pos === -1) {\n return;\n }\n this.sockets.splice(pos, 1);\n\n var pending = this.requests.shift();\n if (pending) {\n // If we have pending requests and a socket gets closed a new one\n // needs to be created to take over in the pool for the one that closed.\n this.createSocket(pending, function(socket) {\n pending.request.onSocket(socket);\n });\n }\n};\n\nfunction createSecureSocket(options, cb) {\n var self = this;\n TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {\n var hostHeader = options.request.getHeader('host');\n var tlsOptions = mergeOptions({}, self.options, {\n socket: socket,\n servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host\n });\n\n // 0 is dummy port for v0.6\n var secureSocket = tls.connect(0, tlsOptions);\n self.sockets[self.sockets.indexOf(socket)] = secureSocket;\n cb(secureSocket);\n });\n}\n\n\nfunction toOptions(host, port, localAddress) {\n if (typeof host === 'string') { // since v0.10\n return {\n host: host,\n port: port,\n localAddress: localAddress\n };\n }\n return host; // for v0.11 or later\n}\n\nfunction mergeOptions(target) {\n for (var i = 1, len = arguments.length; i < len; ++i) {\n var overrides = arguments[i];\n if (typeof overrides === 'object') {\n var keys = Object.keys(overrides);\n for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {\n var k = keys[j];\n if (overrides[k] !== undefined) {\n target[k] = overrides[k];\n }\n }\n }\n }\n return target;\n}\n\n\nvar debug;\nif (process.env.NODE_DEBUG && /\\btunnel\\b/.test(process.env.NODE_DEBUG)) {\n debug = function() {\n var args = Array.prototype.slice.call(arguments);\n if (typeof args[0] === 'string') {\n args[0] = 'TUNNEL: ' + args[0];\n } else {\n args.unshift('TUNNEL:');\n }\n console.error.apply(console, args);\n }\n} else {\n debug = function() {};\n}\nexports.debug = debug; // for test\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n\n if (typeof process === \"object\" && \"version\" in process) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;\n }\n\n return \"\";\n}\n\nexports.getUserAgent = getUserAgent;\n//# sourceMappingURL=index.js.map\n","\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = require('util').deprecate;\n",null,"// Returns a wrapper function that returns a wrapped callback\n// The wrapper function should do some stuff, and return a\n// presumably different callback function.\n// This makes sure that own properties are retained, so that\n// decorations and such are not lost along the way.\nmodule.exports = wrappy\nfunction wrappy (fn, cb) {\n if (fn && cb) return wrappy(fn)(cb)\n\n if (typeof fn !== 'function')\n throw new TypeError('need wrapper function')\n\n Object.keys(fn).forEach(function (k) {\n wrapper[k] = fn[k]\n })\n\n return wrapper\n\n function wrapper() {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i]\n }\n var ret = fn.apply(this, args)\n var cb = args[args.length-1]\n if (typeof ret === 'function' && ret !== cb) {\n Object.keys(cb).forEach(function (k) {\n ret[k] = cb[k]\n })\n }\n return ret\n }\n}\n","var fs = require('fs')\nvar path = require('path')\nvar util = require('util')\n\nfunction Y18N (opts) {\n // configurable options.\n opts = opts || {}\n this.directory = opts.directory || './locales'\n this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true\n this.locale = opts.locale || 'en'\n this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true\n\n // internal stuff.\n this.cache = {}\n this.writeQueue = []\n}\n\nY18N.prototype.__ = function () {\n if (typeof arguments[0] !== 'string') {\n return this._taggedLiteral.apply(this, arguments)\n }\n var args = Array.prototype.slice.call(arguments)\n var str = args.shift()\n var cb = function () {} // start with noop.\n\n if (typeof args[args.length - 1] === 'function') cb = args.pop()\n cb = cb || function () {} // noop.\n\n if (!this.cache[this.locale]) this._readLocaleFile()\n\n // we've observed a new string, update the language file.\n if (!this.cache[this.locale][str] && this.updateFiles) {\n this.cache[this.locale][str] = str\n\n // include the current directory and locale,\n // since these values could change before the\n // write is performed.\n this._enqueueWrite([this.directory, this.locale, cb])\n } else {\n cb()\n }\n\n return util.format.apply(util, [this.cache[this.locale][str] || str].concat(args))\n}\n\nY18N.prototype._taggedLiteral = function (parts) {\n var args = arguments\n var str = ''\n parts.forEach(function (part, i) {\n var arg = args[i + 1]\n str += part\n if (typeof arg !== 'undefined') {\n str += '%s'\n }\n })\n return this.__.apply(null, [str].concat([].slice.call(arguments, 1)))\n}\n\nY18N.prototype._enqueueWrite = function (work) {\n this.writeQueue.push(work)\n if (this.writeQueue.length === 1) this._processWriteQueue()\n}\n\nY18N.prototype._processWriteQueue = function () {\n var _this = this\n var work = this.writeQueue[0]\n\n // destructure the enqueued work.\n var directory = work[0]\n var locale = work[1]\n var cb = work[2]\n\n var languageFile = this._resolveLocaleFile(directory, locale)\n var serializedLocale = JSON.stringify(this.cache[locale], null, 2)\n\n fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) {\n _this.writeQueue.shift()\n if (_this.writeQueue.length > 0) _this._processWriteQueue()\n cb(err)\n })\n}\n\nY18N.prototype._readLocaleFile = function () {\n var localeLookup = {}\n var languageFile = this._resolveLocaleFile(this.directory, this.locale)\n\n try {\n localeLookup = JSON.parse(fs.readFileSync(languageFile, 'utf-8'))\n } catch (err) {\n if (err instanceof SyntaxError) {\n err.message = 'syntax error in ' + languageFile\n }\n\n if (err.code === 'ENOENT') localeLookup = {}\n else throw err\n }\n\n this.cache[this.locale] = localeLookup\n}\n\nY18N.prototype._resolveLocaleFile = function (directory, locale) {\n var file = path.resolve(directory, './', locale + '.json')\n if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {\n // attempt fallback to language only\n var languageFile = path.resolve(directory, './', locale.split('_')[0] + '.json')\n if (this._fileExistsSync(languageFile)) file = languageFile\n }\n return file\n}\n\n// this only exists because fs.existsSync() \"will be deprecated\"\n// see https://nodejs.org/api/fs.html#fs_fs_existssync_path\nY18N.prototype._fileExistsSync = function (file) {\n try {\n return fs.statSync(file).isFile()\n } catch (err) {\n return false\n }\n}\n\nY18N.prototype.__n = function () {\n var args = Array.prototype.slice.call(arguments)\n var singular = args.shift()\n var plural = args.shift()\n var quantity = args.shift()\n\n var cb = function () {} // start with noop.\n if (typeof args[args.length - 1] === 'function') cb = args.pop()\n\n if (!this.cache[this.locale]) this._readLocaleFile()\n\n var str = quantity === 1 ? singular : plural\n if (this.cache[this.locale][singular]) {\n str = this.cache[this.locale][singular][quantity === 1 ? 'one' : 'other']\n }\n\n // we've observed a new string, update the language file.\n if (!this.cache[this.locale][singular] && this.updateFiles) {\n this.cache[this.locale][singular] = {\n one: singular,\n other: plural\n }\n\n // include the current directory and locale,\n // since these values could change before the\n // write is performed.\n this._enqueueWrite([this.directory, this.locale, cb])\n } else {\n cb()\n }\n\n // if a %d placeholder is provided, add quantity\n // to the arguments expanded by util.format.\n var values = [str]\n if (~str.indexOf('%d')) values.push(quantity)\n\n return util.format.apply(util, values.concat(args))\n}\n\nY18N.prototype.setLocale = function (locale) {\n this.locale = locale\n}\n\nY18N.prototype.getLocale = function () {\n return this.locale\n}\n\nY18N.prototype.updateLocale = function (obj) {\n if (!this.cache[this.locale]) this._readLocaleFile()\n\n for (var key in obj) {\n this.cache[this.locale][key] = obj[key]\n }\n}\n\nmodule.exports = function (opts) {\n var y18n = new Y18N(opts)\n\n // bind all functions to y18n, so that\n // they can be used in isolation.\n for (var key in y18n) {\n if (typeof y18n[key] === 'function') {\n y18n[key] = y18n[key].bind(y18n)\n }\n }\n\n return y18n\n}\n",null,"module.exports = require(\"assert\");","module.exports = require(\"buffer\");","module.exports = require(\"child_process\");","module.exports = require(\"crypto\");","module.exports = require(\"dns\");","module.exports = require(\"events\");","module.exports = require(\"fs\");","module.exports = require(\"http\");","module.exports = require(\"https\");","module.exports = require(\"module\");","module.exports = require(\"net\");","module.exports = require(\"os\");","module.exports = require(\"path\");","module.exports = require(\"querystring\");","module.exports = require(\"stream\");","module.exports = require(\"tls\");","module.exports = require(\"url\");","module.exports = require(\"util\");","module.exports = require(\"vm\");","module.exports = require(\"zlib\");","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tif(__webpack_module_cache__[moduleId]) {\n\t\treturn __webpack_module_cache__[moduleId].exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\tvar threw = true;\n\ttry {\n\t\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\t\tthrew = false;\n\t} finally {\n\t\tif(threw) delete __webpack_module_cache__[moduleId];\n\t}\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","\n__webpack_require__.ab = __dirname + \"/\";","// module exports must be returned from runtime so entry inlining is disabled\n// startup\n// Load entry module and return exports\nreturn __webpack_require__(1689);\n"],"mappings":";;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACrFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC5CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClEA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC5FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC9NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACtDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACphBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1XA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC7GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC5nCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACrJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACtWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACjGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC/CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACzYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC/CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACnYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACrzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC7HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AClCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACp1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACjIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACzYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/wBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACrqCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AClCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACv1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC7EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC5GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;A;;;;;;ACtOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACtbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxEA;AACA;AACA;AACA;AACA;A;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC5BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC/CA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACpoDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACvSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClxCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACplBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACrMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnoEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC9QA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC9BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC5GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3VA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC5PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC5fA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACzsBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC5PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClwCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACx2BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC7HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACtZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACrjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;AC/OA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACvnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1bA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC7wBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACr3CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3QA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxhDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClmCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/9BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACzcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACptBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1SA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACvEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC5OA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACzgCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC5CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3hBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC7OA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACj4DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/hBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC7GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC7ZA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmfA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;A;;;;;;ACpfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACtFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACtDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACvDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC9bA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1eA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACtzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC7EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AClnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC5JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;ACxXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACtKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACrOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACjIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACr2BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC/EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACzJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACjJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC1GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACtNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/qBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC1EA;AACA;AACA;A;;;;;ACFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC/DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACvFA;AACA;;;;;;;;;;;;;;;;;;;A;;;;;;ACDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiFA;;;;;;;;AAQA;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;A;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC9JA;AACA;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;A;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC58CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC9TA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACxCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACxSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACtKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACrUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACr2BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC/EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACzJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC/CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC7LA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuhBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;A;;;;;ACvhBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACzCA;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;;;;;;;;;A;;;;;;ACXA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA;;;;;;;;;;;;;;;AAeA;;;;;;;;;;;;;A;;;;;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACtbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACpHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACjCA;AACA;AACA;AACA;AACA;A;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC3DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AClEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;AC7hBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACtVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACZA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoVA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2JA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;A;;;;;AC/gBA;AACA;AACA;A;;;;;;ACFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACzQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;;ACPA;AACA;;AAEA;AACA;;;;;;;A;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AClCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;;;;AC7LA;AACA;AACA;A;;;;;AAFA;AACA;AACA;A;;;;;;;;A;;;;;;;;A;;;;;;ACFA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;;;ACDA;AACA;A;;;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC/BA;AACA;AACA;AACA;AACA;;;;ACJA;AACA;ACDA;AACA;AACA;AACA;;A","sourceRoot":""} \ No newline at end of file diff --git a/dist/licenses.txt b/dist/licenses.txt new file mode 100644 index 0000000..5895601 --- /dev/null +++ b/dist/licenses.txt @@ -0,0 +1,2431 @@ +@actions/core +MIT +The MIT License (MIT) + +Copyright 2019 GitHub + +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. + +@actions/github +MIT + +@actions/http-client +MIT +Actions Http Client for Node.js + +Copyright (c) GitHub, Inc. + +All rights reserved. + +MIT License + +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. + + +@hapi/bourne +BSD-3-Clause +Copyright (c) 2019, Sideway Inc, and project contributors +All rights reserved. + +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 OFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +@octokit/auth-token +MIT +The MIT License + +Copyright (c) 2019 Octokit 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. + + +@octokit/core +MIT +The MIT License + +Copyright (c) 2019 Octokit 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. + + +@octokit/endpoint +MIT +The MIT License + +Copyright (c) 2018 Octokit 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. + + +@octokit/graphql +MIT +The MIT License + +Copyright (c) 2018 Octokit 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. + + +@octokit/plugin-paginate-rest +MIT +MIT License Copyright (c) 2019 Octokit 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 (including the next paragraph) 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. + + +@octokit/plugin-request-log +MIT +MIT License Copyright (c) 2020 Octokit 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 (including the next paragraph) 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. + + +@octokit/plugin-rest-endpoint-methods +MIT +MIT License Copyright (c) 2019 Octokit 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 (including the next paragraph) 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. + + +@octokit/request +MIT +The MIT License + +Copyright (c) 2018 Octokit 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. + + +@octokit/request-error +MIT +The MIT License + +Copyright (c) 2019 Octokit 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. + + +@octokit/rest +MIT +The MIT License + +Copyright (c) 2012 Cloud9 IDE, Inc. (Mike de Boer) +Copyright (c) 2017-2018 Octokit 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. + + +@vercel/ncc +MIT +Copyright 2018 ZEIT, Inc. + +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. + +ansi-regex +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +ansi-styles +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +atomic-sleep +MIT +The MIT License (MIT) +Copyright (c) 2020 David Mark Clements + + +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. + + + +aws4 +MIT +Copyright 2013 Michael Hart (michael.hart.au@gmail.com) + +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. + + +before-after-hook +Apache-2.0 + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 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 (50%) 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. + + 2. 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. + + 3. 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. + + 4. 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. + + 5. 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. + + 6. 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. + + 7. 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. + + 8. 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. + + 9. 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Gregor Martynus and other contributors. + + 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. + + +bl +MIT +The MIT License (MIT) +===================== + +Copyright (c) 2013-2018 bl contributors +---------------------------------- + +*bl contributors listed at * + +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. + + +bson +Apache-2.0 + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 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 (50%) 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. + + 2. 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. + + 3. 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. + + 4. 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. + + 5. 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. + + 6. 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. + + 7. 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. + + 8. 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. + + 9. 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + +camelcase +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +chalk +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +cliui +ISC +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or 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. + + +color-convert +MIT +Copyright (c) 2011-2016 Heather Arthur + +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. + + + +color-name +MIT +The MIT License (MIT) +Copyright (c) 2015 Dmitry Ivanov + +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. + +core-util-is +MIT +Copyright Node.js contributors. All rights reserved. + +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. + + +dateformat +MIT +(c) 2007-2009 Steven Levithan + +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. + + +decamelize +MIT +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +denque +Apache-2.0 +Copyright (c) 2018 Mike Diarmid (Salakar) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this library 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. + + +deprecation +ISC +The ISC License + +Copyright (c) Gregor Martynus and contributors + +Permission to use, copy, modify, and/or 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. + + +emoji-regex +MIT +Copyright Mathias Bynens + +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. + + +escape-string-regexp +MIT +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +fast-redact +MIT +The MIT License (MIT) + +Copyright (c) 2019-2020 David Mark Clements + +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. + +fast-safe-stringify +MIT +The MIT License (MIT) + +Copyright (c) 2016 David Mark Clements +Copyright (c) 2017 David Mark Clements & Matteo Collina +Copyright (c) 2018 David Mark Clements, Matteo Collina & Ruben Bridgewater + +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. + + +find-up +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +flatstr +MIT +The MIT License (MIT) + +Copyright (c) 2016 David Mark Clements + +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. + + +get-caller-file +ISC +ISC License (ISC) +Copyright 2018 Stefan Penner + +Permission to use, copy, modify, and/or 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. + + +has-flag +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +inherits +ISC +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or 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. + + + +invariant +MIT +MIT License + +Copyright (c) 2013-present, Facebook, Inc. + +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. + + +is-fullwidth-code-point +MIT +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +is-plain-object +MIT +The MIT License (MIT) + +Copyright (c) 2014-2017, Jon Schlinkert. + +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. + + +isarray +MIT + +jmespath +Apache 2.0 +Copyright 2014 James Saryerwinnie + +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. + + +locate-path +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +memory-pager +MIT +The MIT License (MIT) + +Copyright (c) 2017 Mathias Buus + +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. + + +mongodb +Apache-2.0 +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 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 (50%) 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. + + 2. 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. + + 3. 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. + + 4. 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. + + 5. 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. + + 6. 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. + + 7. 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. + + 8. 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. + + 9. 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. + +node-fetch +MIT +The MIT License (MIT) + +Copyright (c) 2016 David Frank + +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. + + + +once +ISC +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or 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. + + +p-limit +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +p-locate +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +p-try +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +path-exists +MIT +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +pino +MIT +The MIT License (MIT) + +Copyright (c) 2016-2019 Matteo Collina, David Mark Clements and the Pino contributors + +Pino contributors listed at https://github.com/pinojs/pino#the-team and in +the README file. + +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. + + +pino-pretty +MIT +The MIT License (MIT) + +Copyright (c) 2019 the Pino team + +Pino team listed at https://github.com/pinojs/pino#the-team + +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. + + +pino-std-serializers +MIT +Copyright Mateo Collina, David Mark Clements, James Sumners + +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. + + +process-nextick-args +MIT +# Copyright (c) 2015 Calvin Metcalf + +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.** + + +quick-format-unescaped +MIT +The MIT License (MIT) + +Copyright (c) 2016-2019 David Mark Clements + +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. + + +readable-stream +MIT +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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. +""" + + +require-directory +MIT +The MIT License (MIT) + +Copyright (c) 2011 Troy Goode + +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. + + +require-main-filename +ISC +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or 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. + + +require_optional +Apache-2.0 + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 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 (50%) 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. + + 2. 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. + + 3. 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. + + 4. 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. + + 5. 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. + + 6. 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. + + 7. 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. + + 8. 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. + + 9. 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. + + +resolve-from +MIT +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +safe-buffer +MIT +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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. + + +saslprep +MIT +Copyright (c) 2014 Dmitry Tsvettsikh + +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. + +semver +ISC +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or 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. + + +set-blocking +ISC +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or 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. + + +sonic-boom +MIT +MIT License + +Copyright (c) 2017 Matteo Collina + +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. + + +sparse-bitfield +MIT +The MIT License (MIT) + +Copyright (c) 2016 Mathias Buus + +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. + + +string-width +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +string_decoder +MIT +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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. +""" + + + +strip-ansi +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +supports-color +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +tkt +MIT + +tunnel +MIT +The MIT License (MIT) + +Copyright (c) 2012 Koichi Kobayashi + +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. + + +universal-user-agent +ISC +# [ISC License](https://spdx.org/licenses/ISC) + +Copyright (c) 2018, Gregor Martynus (https://github.com/gr2m) + +Permission to use, copy, modify, and/or 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. + + +util-deprecate +MIT +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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. + + +which-module +ISC +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or 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. + + +wrap-ansi +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + + +wrappy +ISC +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or 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. + + +y18n +ISC +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or 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. + + +yargs +MIT +Copyright 2010 James Halliday (mail@substack.net) +Modified work Copyright 2014 Contributors (ben@npmjs.com) + +This project is free software released under the MIT/X11 license: + +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. + + +yargs-parser +ISC +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or 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. diff --git a/dist/locales/be.json b/dist/locales/be.json new file mode 100644 index 0000000..141ebe1 --- /dev/null +++ b/dist/locales/be.json @@ -0,0 +1,39 @@ +{ + "Commands:": "Каманды:", + "Options:": "Опцыі:", + "Examples:": "Прыклады:", + "boolean": "булевы тып", + "count": "падлік", + "string": "радковы тып", + "number": "лік", + "array": "масіў", + "required": "неабходна", + "default:": "па змаўчанні:", + "choices:": "магчымасці:", + "aliases:": "аліасы:", + "generated-value": "згенераванае значэнне", + "Not enough non-option arguments: got %s, need at least %s": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s", + "Too many non-option arguments: got %s, maximum of %s": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s", + "Missing argument value: %s": { + "one": "Не хапае значэння аргументу: %s", + "other": "Не хапае значэнняў аргументаў: %s" + }, + "Missing required argument: %s": { + "one": "Не хапае неабходнага аргументу: %s", + "other": "Не хапае неабходных аргументаў: %s" + }, + "Unknown argument: %s": { + "one": "Невядомы аргумент: %s", + "other": "Невядомыя аргументы: %s" + }, + "Invalid values:": "Несапраўдныя значэння:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Дадзенае значэнне: %s, Магчымасці: %s", + "Argument check failed: %s": "Праверка аргументаў не ўдалася: %s", + "Implications failed:": "Дадзены аргумент патрабуе наступны дадатковы аргумент:", + "Not enough arguments following: %s": "Недастаткова наступных аргументаў: %s", + "Invalid JSON config file: %s": "Несапраўдны файл канфігурацыі JSON: %s", + "Path to JSON config file": "Шлях да файла канфігурацыі JSON", + "Show help": "Паказаць дапамогу", + "Show version number": "Паказаць нумар версіі", + "Did you mean %s?": "Вы мелі на ўвазе %s?" +} diff --git a/dist/locales/de.json b/dist/locales/de.json new file mode 100644 index 0000000..05d9837 --- /dev/null +++ b/dist/locales/de.json @@ -0,0 +1,39 @@ +{ + "Commands:": "Kommandos:", + "Options:": "Optionen:", + "Examples:": "Beispiele:", + "boolean": "boolean", + "count": "Zähler", + "string": "string", + "number": "Zahl", + "array": "array", + "required": "erforderlich", + "default:": "Standard:", + "choices:": "Möglichkeiten:", + "aliases:": "Aliase:", + "generated-value": "Generierter-Wert", + "Not enough non-option arguments: got %s, need at least %s": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt", + "Too many non-option arguments: got %s, maximum of %s": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt", + "Missing argument value: %s": { + "one": "Fehlender Argumentwert: %s", + "other": "Fehlende Argumentwerte: %s" + }, + "Missing required argument: %s": { + "one": "Fehlendes Argument: %s", + "other": "Fehlende Argumente: %s" + }, + "Unknown argument: %s": { + "one": "Unbekanntes Argument: %s", + "other": "Unbekannte Argumente: %s" + }, + "Invalid values:": "Unzulässige Werte:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeben: %s, Möglichkeiten: %s", + "Argument check failed: %s": "Argumente-Check fehlgeschlagen: %s", + "Implications failed:": "Fehlende abhängige Argumente:", + "Not enough arguments following: %s": "Nicht genügend Argumente nach: %s", + "Invalid JSON config file: %s": "Fehlerhafte JSON-Config Datei: %s", + "Path to JSON config file": "Pfad zur JSON-Config Datei", + "Show help": "Hilfe anzeigen", + "Show version number": "Version anzeigen", + "Did you mean %s?": "Meintest du %s?" +} diff --git a/dist/locales/en.json b/dist/locales/en.json new file mode 100644 index 0000000..b32a63f --- /dev/null +++ b/dist/locales/en.json @@ -0,0 +1,42 @@ +{ + "Commands:": "Commands:", + "Options:": "Options:", + "Examples:": "Examples:", + "boolean": "boolean", + "count": "count", + "string": "string", + "number": "number", + "array": "array", + "required": "required", + "default:": "default:", + "choices:": "choices:", + "aliases:": "aliases:", + "generated-value": "generated-value", + "Not enough non-option arguments: got %s, need at least %s": "Not enough non-option arguments: got %s, need at least %s", + "Too many non-option arguments: got %s, maximum of %s": "Too many non-option arguments: got %s, maximum of %s", + "Missing argument value: %s": { + "one": "Missing argument value: %s", + "other": "Missing argument values: %s" + }, + "Missing required argument: %s": { + "one": "Missing required argument: %s", + "other": "Missing required arguments: %s" + }, + "Unknown argument: %s": { + "one": "Unknown argument: %s", + "other": "Unknown arguments: %s" + }, + "Invalid values:": "Invalid values:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Given: %s, Choices: %s", + "Argument check failed: %s": "Argument check failed: %s", + "Implications failed:": "Missing dependent arguments:", + "Not enough arguments following: %s": "Not enough arguments following: %s", + "Invalid JSON config file: %s": "Invalid JSON config file: %s", + "Path to JSON config file": "Path to JSON config file", + "Show help": "Show help", + "Show version number": "Show version number", + "Did you mean %s?": "Did you mean %s?", + "Arguments %s and %s are mutually exclusive" : "Arguments %s and %s are mutually exclusive", + "Positionals:": "Positionals:", + "command": "command" +} diff --git a/dist/locales/es.json b/dist/locales/es.json new file mode 100644 index 0000000..d7c8af9 --- /dev/null +++ b/dist/locales/es.json @@ -0,0 +1,39 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opciones:", + "Examples:": "Ejemplos:", + "boolean": "booleano", + "count": "cuenta", + "string": "cadena de caracteres", + "number": "número", + "array": "tabla", + "required": "requerido", + "default:": "defecto:", + "choices:": "selección:", + "aliases:": "alias:", + "generated-value": "valor-generado", + "Not enough non-option arguments: got %s, need at least %s": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s", + "Too many non-option arguments: got %s, maximum of %s": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s", + "Missing argument value: %s": { + "one": "Falta argumento: %s", + "other": "Faltan argumentos: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento requerido: %s", + "other": "Faltan argumentos requeridos: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconocido: %s", + "other": "Argumentos desconocidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Recibido: %s, Seleccionados: %s", + "Argument check failed: %s": "Verificación de argumento ha fallado: %s", + "Implications failed:": "Implicaciones fallidas:", + "Not enough arguments following: %s": "No hay suficientes argumentos después de: %s", + "Invalid JSON config file: %s": "Archivo de configuración JSON inválido: %s", + "Path to JSON config file": "Ruta al archivo de configuración JSON", + "Show help": "Muestra ayuda", + "Show version number": "Muestra número de versión", + "Did you mean %s?": "Quisiste decir %s?" +} diff --git a/dist/locales/fr.json b/dist/locales/fr.json new file mode 100644 index 0000000..cf9c74b --- /dev/null +++ b/dist/locales/fr.json @@ -0,0 +1,37 @@ +{ + "Commands:": "Commandes:", + "Options:": "Options:", + "Examples:": "Exemples:", + "boolean": "booléen", + "count": "comptage", + "string": "chaine de caractère", + "number": "nombre", + "array": "tableau", + "required": "requis", + "default:": "défaut:", + "choices:": "choix:", + "generated-value": "valeur générée", + "Not enough non-option arguments: got %s, need at least %s": "Pas assez d'arguments non-option: reçu %s, besoin d'au moins %s", + "Too many non-option arguments: got %s, maximum of %s": "Trop d'arguments non-option: reçu %s, maximum %s", + "Missing argument value: %s": { + "one": "Argument manquant: %s", + "other": "Arguments manquants: %s" + }, + "Missing required argument: %s": { + "one": "Argument requis manquant: %s", + "other": "Arguments requis manquants: %s" + }, + "Unknown argument: %s": { + "one": "Argument inconnu: %s", + "other": "Arguments inconnus: %s" + }, + "Invalid values:": "Valeurs invalides:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Donné: %s, Choix: %s", + "Argument check failed: %s": "Echec de la vérification de l'argument: %s", + "Implications failed:": "Arguments dépendants manquants:", + "Not enough arguments following: %s": "Pas assez d'arguments suivant: %s", + "Invalid JSON config file: %s": "Fichier de configuration JSON invalide: %s", + "Path to JSON config file": "Chemin du fichier de configuration JSON", + "Show help": "Affiche de l'aide", + "Show version number": "Affiche le numéro de version" +} diff --git a/dist/locales/hi.json b/dist/locales/hi.json new file mode 100644 index 0000000..2cd677a --- /dev/null +++ b/dist/locales/hi.json @@ -0,0 +1,42 @@ +{ + "Commands:": "आदेश:", + "Options:": "विकल्प:", + "Examples:": "उदाहरण:", + "boolean": "सत्यता", + "count": "संख्या", + "string": "वर्णों का तार ", + "number": "अंक", + "array": "सरणी", + "required": "आवश्यक", + "default:": "डिफॉल्ट:", + "choices:": "विकल्प:", + "aliases:": "उपनाम:", + "generated-value": "उत्पन्न-मूल्य", + "Not enough non-option arguments: got %s, need at least %s": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है", + "Too many non-option arguments: got %s, maximum of %s": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य", + "Missing argument value: %s": { + "one": "कुछ तर्को के मूल्य गुम हैं: %s", + "other": "कुछ तर्को के मूल्य गुम हैं: %s" + }, + "Missing required argument: %s": { + "one": "आवश्यक तर्क गुम हैं: %s", + "other": "आवश्यक तर्क गुम हैं: %s" + }, + "Unknown argument: %s": { + "one": "अज्ञात तर्क प्राप्त: %s", + "other": "अज्ञात तर्क प्राप्त: %s" + }, + "Invalid values:": "अमान्य मूल्य:", + "Argument: %s, Given: %s, Choices: %s": "तर्क: %s, प्राप्त: %s, विकल्प: %s", + "Argument check failed: %s": "तर्क जांच विफल: %s", + "Implications failed:": "दिए गए तर्क के लिए अतिरिक्त तर्क की अपेक्षा है:", + "Not enough arguments following: %s": "निम्नलिखित के बाद पर्याप्त तर्क नहीं प्राप्त: %s", + "Invalid JSON config file: %s": "अमान्य JSON config फाइल: %s", + "Path to JSON config file": "JSON config फाइल का पथ", + "Show help": "सहायता दिखाएँ", + "Show version number": "Version संख्या दिखाएँ", + "Did you mean %s?": "क्या आपका मतलब है %s?", + "Arguments %s and %s are mutually exclusive" : "तर्क %s और %s परस्पर अनन्य हैं", + "Positionals:": "स्थानीय:", + "command": "आदेश" +} diff --git a/dist/locales/hu.json b/dist/locales/hu.json new file mode 100644 index 0000000..7b7d166 --- /dev/null +++ b/dist/locales/hu.json @@ -0,0 +1,39 @@ +{ + "Commands:": "Parancsok:", + "Options:": "Opciók:", + "Examples:": "Példák:", + "boolean": "boolean", + "count": "számláló", + "string": "szöveg", + "number": "szám", + "array": "tömb", + "required": "kötelező", + "default:": "alapértelmezett:", + "choices:": "lehetőségek:", + "aliases:": "aliaszok:", + "generated-value": "generált-érték", + "Not enough non-option arguments: got %s, need at least %s": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell", + "Too many non-option arguments: got %s, maximum of %s": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet", + "Missing argument value: %s": { + "one": "Hiányzó argumentum érték: %s", + "other": "Hiányzó argumentum értékek: %s" + }, + "Missing required argument: %s": { + "one": "Hiányzó kötelező argumentum: %s", + "other": "Hiányzó kötelező argumentumok: %s" + }, + "Unknown argument: %s": { + "one": "Ismeretlen argumentum: %s", + "other": "Ismeretlen argumentumok: %s" + }, + "Invalid values:": "Érvénytelen érték:", + "Argument: %s, Given: %s, Choices: %s": "Argumentum: %s, Megadott: %s, Lehetőségek: %s", + "Argument check failed: %s": "Argumentum ellenőrzés sikertelen: %s", + "Implications failed:": "Implikációk sikertelenek:", + "Not enough arguments following: %s": "Nem elég argumentum követi: %s", + "Invalid JSON config file: %s": "Érvénytelen JSON konfigurációs file: %s", + "Path to JSON config file": "JSON konfigurációs file helye", + "Show help": "Súgo megjelenítése", + "Show version number": "Verziószám megjelenítése", + "Did you mean %s?": "Erre gondoltál %s?" +} diff --git a/dist/locales/id.json b/dist/locales/id.json new file mode 100644 index 0000000..87e441c --- /dev/null +++ b/dist/locales/id.json @@ -0,0 +1,43 @@ + +{ + "Commands:": "Perintah:", + "Options:": "Pilihan:", + "Examples:": "Contoh:", + "boolean": "boolean", + "count": "jumlah", + "number": "nomor", + "string": "string", + "array": "larik", + "required": "diperlukan", + "default:": "bawaan:", + "aliases:": "istilah lain:", + "choices:": "pilihan:", + "generated-value": "nilai-yang-dihasilkan", + "Not enough non-option arguments: got %s, need at least %s": "Argumen wajib kurang: hanya %s, minimal %s", + "Too many non-option arguments: got %s, maximum of %s": "Terlalu banyak argumen wajib: ada %s, maksimal %s", + "Missing argument value: %s": { + "one": "Kurang argumen: %s", + "other": "Kurang argumen: %s" + }, + "Missing required argument: %s": { + "one": "Kurang argumen wajib: %s", + "other": "Kurang argumen wajib: %s" + }, + "Unknown argument: %s": { + "one": "Argumen tak diketahui: %s", + "other": "Argumen tak diketahui: %s" + }, + "Invalid values:": "Nilai-nilai tidak valid:", + "Argument: %s, Given: %s, Choices: %s": "Argumen: %s, Diberikan: %s, Pilihan: %s", + "Argument check failed: %s": "Pemeriksaan argument gagal: %s", + "Implications failed:": "Implikasi gagal:", + "Not enough arguments following: %s": "Kurang argumen untuk: %s", + "Invalid JSON config file: %s": "Berkas konfigurasi JSON tidak valid: %s", + "Path to JSON config file": "Alamat berkas konfigurasi JSON", + "Show help": "Lihat bantuan", + "Show version number": "Lihat nomor versi", + "Did you mean %s?": "Maksud Anda: %s?", + "Arguments %s and %s are mutually exclusive" : "Argumen %s dan %s saling eksklusif", + "Positionals:": "Posisional-posisional:", + "command": "perintah" +} diff --git a/dist/locales/it.json b/dist/locales/it.json new file mode 100644 index 0000000..9ee900d --- /dev/null +++ b/dist/locales/it.json @@ -0,0 +1,39 @@ +{ + "Commands:": "Comandi:", + "Options:": "Opzioni:", + "Examples:": "Esempi:", + "boolean": "booleano", + "count": "contatore", + "string": "stringa", + "number": "numero", + "array": "vettore", + "required": "richiesto", + "default:": "predefinito:", + "choices:": "scelte:", + "aliases:": "alias:", + "generated-value": "valore generato", + "Not enough non-option arguments: got %s, need at least %s": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s", + "Too many non-option arguments: got %s, maximum of %s": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s", + "Missing argument value: %s": { + "one": "Argomento mancante: %s", + "other": "Argomenti mancanti: %s" + }, + "Missing required argument: %s": { + "one": "Argomento richiesto mancante: %s", + "other": "Argomenti richiesti mancanti: %s" + }, + "Unknown argument: %s": { + "one": "Argomento sconosciuto: %s", + "other": "Argomenti sconosciuti: %s" + }, + "Invalid values:": "Valori non validi:", + "Argument: %s, Given: %s, Choices: %s": "Argomento: %s, Richiesto: %s, Scelte: %s", + "Argument check failed: %s": "Controllo dell'argomento fallito: %s", + "Implications failed:": "Argomenti dipendenti mancanti:", + "Not enough arguments following: %s": "Argomenti insufficienti dopo: %s", + "Invalid JSON config file: %s": "File di configurazione JSON non valido: %s", + "Path to JSON config file": "Percorso del file di configurazione JSON", + "Show help": "Mostra la schermata di aiuto", + "Show version number": "Mostra il numero di versione", + "Did you mean %s?": "Intendi forse %s?" +} diff --git a/dist/locales/ja.json b/dist/locales/ja.json new file mode 100644 index 0000000..64ee6d3 --- /dev/null +++ b/dist/locales/ja.json @@ -0,0 +1,42 @@ +{ + "Commands:": "コマンド:", + "Options:": "オプション:", + "Examples:": "例:", + "boolean": "真偽", + "count": "カウント", + "string": "文字列", + "number": "数値", + "array": "配列", + "required": "必須", + "default:": "デフォルト:", + "choices:": "選択してください:", + "aliases:": "エイリアス:", + "generated-value": "生成された値", + "Not enough non-option arguments: got %s, need at least %s": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:", + "Too many non-option arguments: got %s, maximum of %s": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:", + "Missing argument value: %s": { + "one": "引数が見つかりません: %s", + "other": "引数が見つかりません: %s" + }, + "Missing required argument: %s": { + "one": "必須の引数が見つかりません: %s", + "other": "必須の引数が見つかりません: %s" + }, + "Unknown argument: %s": { + "one": "未知の引数です: %s", + "other": "未知の引数です: %s" + }, + "Invalid values:": "不正な値です:", + "Argument: %s, Given: %s, Choices: %s": "引数は %s です。指定できるのは %s つです。選択してください: %s", + "Argument check failed: %s": "引数のチェックに失敗しました: %s", + "Implications failed:": "オプションの組み合わせで不正が生じました:", + "Not enough arguments following: %s": "次の引数が不足しています。: %s", + "Invalid JSON config file: %s": "JSONの設定ファイルが不正です: %s", + "Path to JSON config file": "JSONの設定ファイルまでのpath", + "Show help": "ヘルプを表示", + "Show version number": "バージョンを表示", + "Did you mean %s?": "もしかして %s?", + "Arguments %s and %s are mutually exclusive" : "引数 %s と %s は同時に指定できません", + "Positionals:": "位置:", + "command": "コマンド" +} diff --git a/dist/locales/ko.json b/dist/locales/ko.json new file mode 100644 index 0000000..0eaeab2 --- /dev/null +++ b/dist/locales/ko.json @@ -0,0 +1,42 @@ +{ + "Commands:": "명령:", + "Options:": "옵션:", + "Examples:": "예시:", + "boolean": "여부", + "count": "개수", + "string": "문자열", + "number": "숫자", + "array": "배열", + "required": "필수", + "default:": "기본:", + "choices:": "선택:", + "aliases:": "별칭:", + "generated-value": "생성된 값", + "Not enough non-option arguments: got %s, need at least %s": "옵션이 아닌 인자가 충분치 않습니다: %s개를 받았지만, 적어도 %s개는 필요합니다", + "Too many non-option arguments: got %s, maximum of %s": "옵션이 아닌 인자가 너무 많습니다: %s개를 받았지만, %s개 이하여야 합니다", + "Missing argument value: %s": { + "one": "인자값을 받지 못했습니다: %s", + "other": "인자값들을 받지 못했습니다: %s" + }, + "Missing required argument: %s": { + "one": "필수 인자를 받지 못했습니다: %s", + "other": "필수 인자들을 받지 못했습니다: %s" + }, + "Unknown argument: %s": { + "one": "알 수 없는 인자입니다: %s", + "other": "알 수 없는 인자들입니다: %s" + }, + "Invalid values:": "잘못된 값입니다:", + "Argument: %s, Given: %s, Choices: %s": "인자: %s, 입력받은 값: %s, 선택지: %s", + "Argument check failed: %s": "유효하지 않은 인자입니다: %s", + "Implications failed:": "옵션의 조합이 잘못되었습니다:", + "Not enough arguments following: %s": "인자가 충분하게 주어지지 않았습니다: %s", + "Invalid JSON config file: %s": "유효하지 않은 JSON 설정파일입니다: %s", + "Path to JSON config file": "JSON 설정파일 경로", + "Show help": "도움말을 보여줍니다", + "Show version number": "버전 넘버를 보여줍니다", + "Did you mean %s?": "찾고계신게 %s입니까?", + "Arguments %s and %s are mutually exclusive" : "%s와 %s 인자는 같이 사용될 수 없습니다", + "Positionals:": "위치:", + "command": "명령" +} diff --git a/dist/locales/nb.json b/dist/locales/nb.json new file mode 100644 index 0000000..55be1fb --- /dev/null +++ b/dist/locales/nb.json @@ -0,0 +1,37 @@ +{ + "Commands:": "Kommandoer:", + "Options:": "Alternativer:", + "Examples:": "Eksempler:", + "boolean": "boolsk", + "count": "antall", + "string": "streng", + "number": "nummer", + "array": "matrise", + "required": "obligatorisk", + "default:": "standard:", + "choices:": "valg:", + "generated-value": "generert-verdi", + "Not enough non-option arguments: got %s, need at least %s": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s", + "Too many non-option arguments: got %s, maximum of %s": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s", + "Missing argument value: %s": { + "one": "Mangler argument verdi: %s", + "other": "Mangler argument verdier: %s" + }, + "Missing required argument: %s": { + "one": "Mangler obligatorisk argument: %s", + "other": "Mangler obligatoriske argumenter: %s" + }, + "Unknown argument: %s": { + "one": "Ukjent argument: %s", + "other": "Ukjente argumenter: %s" + }, + "Invalid values:": "Ugyldige verdier:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gitt: %s, Valg: %s", + "Argument check failed: %s": "Argumentsjekk mislyktes: %s", + "Implications failed:": "Konsekvensene mislyktes:", + "Not enough arguments following: %s": "Ikke nok følgende argumenter: %s", + "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", + "Path to JSON config file": "Bane til JSON konfigurasjonsfil", + "Show help": "Vis hjelp", + "Show version number": "Vis versjonsnummer" +} diff --git a/dist/locales/nl.json b/dist/locales/nl.json new file mode 100644 index 0000000..5d62e0f --- /dev/null +++ b/dist/locales/nl.json @@ -0,0 +1,42 @@ +{ + "Commands:": "Commando's:", + "Options:": "Opties:", + "Examples:": "Voorbeelden:", + "boolean": "booleaans", + "count": "aantal", + "string": "string", + "number": "getal", + "array": "lijst", + "required": "verplicht", + "default:": "standaard:", + "choices:": "keuzes:", + "aliases:": "aliassen:", + "generated-value": "gegenereerde waarde", + "Not enough non-option arguments: got %s, need at least %s": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig", + "Too many non-option arguments: got %s, maximum of %s": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s", + "Missing argument value: %s": { + "one": "Missende argumentwaarde: %s", + "other": "Missende argumentwaarden: %s" + }, + "Missing required argument: %s": { + "one": "Missend verplicht argument: %s", + "other": "Missende verplichte argumenten: %s" + }, + "Unknown argument: %s": { + "one": "Onbekend argument: %s", + "other": "Onbekende argumenten: %s" + }, + "Invalid values:": "Ongeldige waarden:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeven: %s, Keuzes: %s", + "Argument check failed: %s": "Argumentcontrole mislukt: %s", + "Implications failed:": "Ontbrekende afhankelijke argumenten:", + "Not enough arguments following: %s": "Niet genoeg argumenten na: %s", + "Invalid JSON config file: %s": "Ongeldig JSON-config-bestand: %s", + "Path to JSON config file": "Pad naar JSON-config-bestand", + "Show help": "Toon help", + "Show version number": "Toon versienummer", + "Did you mean %s?": "Bedoelde u misschien %s?", + "Arguments %s and %s are mutually exclusive": "Argumenten %s en %s kunnen niet tegelijk gebruikt worden", + "Positionals:": "Positie-afhankelijke argumenten", + "command": "commando" +} diff --git a/dist/locales/nn.json b/dist/locales/nn.json new file mode 100644 index 0000000..5a3c951 --- /dev/null +++ b/dist/locales/nn.json @@ -0,0 +1,39 @@ +{ + "Commands:": "Kommandoar:", + "Options:": "Alternativ:", + "Examples:": "Døme:", + "boolean": "boolsk", + "count": "mengd", + "string": "streng", + "number": "nummer", + "array": "matrise", + "required": "obligatorisk", + "default:": "standard:", + "choices:": "val:", + "generated-value": "generert-verdi", + "Not enough non-option arguments: got %s, need at least %s": + "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s", + "Too many non-option arguments: got %s, maximum of %s": + "For mange ikkje-alternativ argument: fekk %s, maksimum %s", + "Missing argument value: %s": { + "one": "Manglar argumentverdi: %s", + "other": "Manglar argumentverdiar: %s" + }, + "Missing required argument: %s": { + "one": "Manglar obligatorisk argument: %s", + "other": "Manglar obligatoriske argument: %s" + }, + "Unknown argument: %s": { + "one": "Ukjent argument: %s", + "other": "Ukjende argument: %s" + }, + "Invalid values:": "Ugyldige verdiar:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gjeve: %s, Val: %s", + "Argument check failed: %s": "Argumentsjekk mislukkast: %s", + "Implications failed:": "Konsekvensane mislukkast:", + "Not enough arguments following: %s": "Ikkje nok fylgjande argument: %s", + "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", + "Path to JSON config file": "Bane til JSON konfigurasjonsfil", + "Show help": "Vis hjelp", + "Show version number": "Vis versjonsnummer" +} diff --git a/dist/locales/pirate.json b/dist/locales/pirate.json new file mode 100644 index 0000000..dcb5cb7 --- /dev/null +++ b/dist/locales/pirate.json @@ -0,0 +1,13 @@ +{ + "Commands:": "Choose yer command:", + "Options:": "Options for me hearties!", + "Examples:": "Ex. marks the spot:", + "required": "requi-yar-ed", + "Missing required argument: %s": { + "one": "Ye be havin' to set the followin' argument land lubber: %s", + "other": "Ye be havin' to set the followin' arguments land lubber: %s" + }, + "Show help": "Parlay this here code of conduct", + "Show version number": "'Tis the version ye be askin' fer", + "Arguments %s and %s are mutually exclusive" : "Yon scurvy dogs %s and %s be as bad as rum and a prudish wench" +} diff --git a/dist/locales/pl.json b/dist/locales/pl.json new file mode 100644 index 0000000..6926a45 --- /dev/null +++ b/dist/locales/pl.json @@ -0,0 +1,42 @@ +{ + "Commands:": "Polecenia:", + "Options:": "Opcje:", + "Examples:": "Przykłady:", + "boolean": "boolean", + "count": "ilość", + "string": "ciąg znaków", + "number": "liczba", + "array": "tablica", + "required": "wymagany", + "default:": "domyślny:", + "choices:": "dostępne:", + "aliases:": "aliasy:", + "generated-value": "wygenerowana-wartość", + "Not enough non-option arguments: got %s, need at least %s": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s", + "Too many non-option arguments: got %s, maximum of %s": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s", + "Missing argument value: %s": { + "one": "Brak wartości dla argumentu: %s", + "other": "Brak wartości dla argumentów: %s" + }, + "Missing required argument: %s": { + "one": "Brak wymaganego argumentu: %s", + "other": "Brak wymaganych argumentów: %s" + }, + "Unknown argument: %s": { + "one": "Nieznany argument: %s", + "other": "Nieznane argumenty: %s" + }, + "Invalid values:": "Nieprawidłowe wartości:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Otrzymano: %s, Dostępne: %s", + "Argument check failed: %s": "Weryfikacja argumentów nie powiodła się: %s", + "Implications failed:": "Założenia nie zostały spełnione:", + "Not enough arguments following: %s": "Niewystarczająca ilość argumentów następujących po: %s", + "Invalid JSON config file: %s": "Nieprawidłowy plik konfiguracyjny JSON: %s", + "Path to JSON config file": "Ścieżka do pliku konfiguracyjnego JSON", + "Show help": "Pokaż pomoc", + "Show version number": "Pokaż numer wersji", + "Did you mean %s?": "Czy chodziło Ci o %s?", + "Arguments %s and %s are mutually exclusive": "Argumenty %s i %s wzajemnie się wykluczają", + "Positionals:": "Pozycyjne:", + "command": "polecenie" +} diff --git a/dist/locales/pt.json b/dist/locales/pt.json new file mode 100644 index 0000000..75c3921 --- /dev/null +++ b/dist/locales/pt.json @@ -0,0 +1,38 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opções:", + "Examples:": "Exemplos:", + "boolean": "boolean", + "count": "contagem", + "string": "cadeia de caracteres", + "number": "número", + "array": "arranjo", + "required": "requerido", + "default:": "padrão:", + "choices:": "escolhas:", + "generated-value": "valor-gerado", + "Not enough non-option arguments: got %s, need at least %s": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s", + "Too many non-option arguments: got %s, maximum of %s": "Excesso de argumentos não opcionais: recebido %s, máximo de %s", + "Missing argument value: %s": { + "one": "Falta valor de argumento: %s", + "other": "Falta valores de argumento: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento obrigatório: %s", + "other": "Faltando argumentos obrigatórios: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconhecido: %s", + "other": "Argumentos desconhecidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Escolhas: %s", + "Argument check failed: %s": "Verificação de argumento falhou: %s", + "Implications failed:": "Implicações falharam:", + "Not enough arguments following: %s": "Insuficientes argumentos a seguir: %s", + "Invalid JSON config file: %s": "Arquivo de configuração em JSON esta inválido: %s", + "Path to JSON config file": "Caminho para o arquivo de configuração em JSON", + "Show help": "Mostra ajuda", + "Show version number": "Mostra número de versão", + "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos" +} diff --git a/dist/locales/pt_BR.json b/dist/locales/pt_BR.json new file mode 100644 index 0000000..904cb66 --- /dev/null +++ b/dist/locales/pt_BR.json @@ -0,0 +1,42 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opções:", + "Examples:": "Exemplos:", + "boolean": "booleano", + "count": "contagem", + "string": "string", + "number": "número", + "array": "array", + "required": "obrigatório", + "default:": "padrão:", + "choices:": "opções:", + "aliases:": "sinônimos:", + "generated-value": "valor-gerado", + "Not enough non-option arguments: got %s, need at least %s": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s", + "Too many non-option arguments: got %s, maximum of %s": "Excesso de argumentos: recebido %s, máximo de %s", + "Missing argument value: %s": { + "one": "Falta valor de argumento: %s", + "other": "Falta valores de argumento: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento obrigatório: %s", + "other": "Faltando argumentos obrigatórios: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconhecido: %s", + "other": "Argumentos desconhecidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Opções: %s", + "Argument check failed: %s": "Verificação de argumento falhou: %s", + "Implications failed:": "Implicações falharam:", + "Not enough arguments following: %s": "Argumentos insuficientes a seguir: %s", + "Invalid JSON config file: %s": "Arquivo JSON de configuração inválido: %s", + "Path to JSON config file": "Caminho para o arquivo JSON de configuração", + "Show help": "Exibe ajuda", + "Show version number": "Exibe a versão", + "Did you mean %s?": "Você quis dizer %s?", + "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos", + "Positionals:": "Posicionais:", + "command": "comando" +} diff --git a/dist/locales/ru.json b/dist/locales/ru.json new file mode 100644 index 0000000..cb7b88b --- /dev/null +++ b/dist/locales/ru.json @@ -0,0 +1,39 @@ +{ + "Commands:": "Команды:", + "Options:": "Опции:", + "Examples:": "Примеры:", + "boolean": "булевый тип", + "count": "подсчет", + "string": "строковой тип", + "number": "число", + "array": "массив", + "required": "необходимо", + "default:": "по умолчанию:", + "choices:": "возможности:", + "aliases:": "алиасы:", + "generated-value": "генерированное значение", + "Not enough non-option arguments: got %s, need at least %s": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s", + "Too many non-option arguments: got %s, maximum of %s": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s", + "Missing argument value: %s": { + "one": "Не хватает значения аргумента: %s", + "other": "Не хватает значений аргументов: %s" + }, + "Missing required argument: %s": { + "one": "Не хватает необходимого аргумента: %s", + "other": "Не хватает необходимых аргументов: %s" + }, + "Unknown argument: %s": { + "one": "Неизвестный аргумент: %s", + "other": "Неизвестные аргументы: %s" + }, + "Invalid values:": "Недействительные значения:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Данное значение: %s, Возможности: %s", + "Argument check failed: %s": "Проверка аргументов не удалась: %s", + "Implications failed:": "Данный аргумент требует следующий дополнительный аргумент:", + "Not enough arguments following: %s": "Недостаточно следующих аргументов: %s", + "Invalid JSON config file: %s": "Недействительный файл конфигурации JSON: %s", + "Path to JSON config file": "Путь к файлу конфигурации JSON", + "Show help": "Показать помощь", + "Show version number": "Показать номер версии", + "Did you mean %s?": "Вы имели в виду %s?" +} diff --git a/dist/locales/th.json b/dist/locales/th.json new file mode 100644 index 0000000..3f08dcd --- /dev/null +++ b/dist/locales/th.json @@ -0,0 +1,39 @@ +{ + "Commands:": "คอมมาน", + "Options:": "ออฟชั่น", + "Examples:": "ตัวอย่าง", + "boolean": "บูลีน", + "count": "นับ", + "string": "สตริง", + "number": "ตัวเลข", + "array": "อาเรย์", + "required": "จำเป็น", + "default:": "ค่าเริ่มต้น", + "choices:": "ตัวเลือก", + "aliases:": "เอเลียส", + "generated-value": "ค่าที่ถูกสร้างขึ้น", + "Not enough non-option arguments: got %s, need at least %s": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า", + "Too many non-option arguments: got %s, maximum of %s": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า", + "Missing argument value: %s": { + "one": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s", + "other": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s" + }, + "Missing required argument: %s": { + "one": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s", + "other": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s" + }, + "Unknown argument: %s": { + "one": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s", + "other": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s" + }, + "Invalid values:": "ค่าไม่ถูกต้อง:", + "Argument: %s, Given: %s, Choices: %s": "อาร์กิวเมนต์: %s, ได้รับ: %s, ตัวเลือก: %s", + "Argument check failed: %s": "ตรวจสอบพบอาร์กิวเมนต์ที่ไม่ถูกต้อง: %s", + "Implications failed:": "Implications ไม่สำเร็จ:", + "Not enough arguments following: %s": "ใส่อาร์กิวเมนต์ไม่ครบ: %s", + "Invalid JSON config file: %s": "ไฟล์คอนฟิค JSON ไม่ถูกต้อง: %s", + "Path to JSON config file": "พาทไฟล์คอนฟิค JSON", + "Show help": "ขอความช่วยเหลือ", + "Show version number": "แสดงตัวเลขเวอร์ชั่น", + "Did you mean %s?": "คุณหมายถึง %s?" +} diff --git a/dist/locales/tr.json b/dist/locales/tr.json new file mode 100644 index 0000000..9b06c52 --- /dev/null +++ b/dist/locales/tr.json @@ -0,0 +1,41 @@ +{ + "Commands:": "Komutlar:", + "Options:": "Seçenekler:", + "Examples:": "Örnekler:", + "boolean": "boolean", + "count": "sayı", + "string": "string", + "number": "numara", + "array": "array", + "required": "zorunlu", + "default:": "varsayılan:", + "choices:": "seçimler:", + "aliases:": "takma adlar:", + "generated-value": "oluşturulan-değer", + "Not enough non-option arguments: got %s, need at least %s": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli", + "Too many non-option arguments: got %s, maximum of %s": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s", + "Missing argument value: %s": { + "one": "Eksik argüman değeri: %s", + "other": "Eksik argüman değerleri: %s" + }, + "Missing required argument: %s": { + "one": "Eksik zorunlu argüman: %s", + "other": "Eksik zorunlu argümanlar: %s" + }, + "Unknown argument: %s": { + "one": "Bilinmeyen argüman: %s", + "other": "Bilinmeyen argümanlar: %s" + }, + "Invalid values:": "Geçersiz değerler:", + "Argument: %s, Given: %s, Choices: %s": "Argüman: %s, Verilen: %s, Seçimler: %s", + "Argument check failed: %s": "Argüman kontrolü başarısız oldu: %s", + "Implications failed:": "Sonuçlar başarısız oldu:", + "Not enough arguments following: %s": "%s için yeterli argüman bulunamadı", + "Invalid JSON config file: %s": "Geçersiz JSON yapılandırma dosyası: %s", + "Path to JSON config file": "JSON yapılandırma dosya konumu", + "Show help": "Yardım detaylarını göster", + "Show version number": "Versiyon detaylarını göster", + "Did you mean %s?": "Bunu mu demek istediniz: %s?", + "Positionals:": "Sıralılar:", + "command": "komut" +} diff --git a/dist/locales/zh_CN.json b/dist/locales/zh_CN.json new file mode 100644 index 0000000..03a3d94 --- /dev/null +++ b/dist/locales/zh_CN.json @@ -0,0 +1,41 @@ +{ + "Commands:": "命令:", + "Options:": "选项:", + "Examples:": "示例:", + "boolean": "布尔", + "count": "计数", + "string": "字符串", + "number": "数字", + "array": "数组", + "required": "必需", + "default:": "默认值:", + "choices:": "可选值:", + "generated-value": "生成的值", + "Not enough non-option arguments: got %s, need at least %s": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个", + "Too many non-option arguments: got %s, maximum of %s": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个", + "Missing argument value: %s": { + "one": "没有给此选项指定值:%s", + "other": "没有给这些选项指定值:%s" + }, + "Missing required argument: %s": { + "one": "缺少必须的选项:%s", + "other": "缺少这些必须的选项:%s" + }, + "Unknown argument: %s": { + "one": "无法识别的选项:%s", + "other": "无法识别这些选项:%s" + }, + "Invalid values:": "无效的选项值:", + "Argument: %s, Given: %s, Choices: %s": "选项名称: %s, 传入的值: %s, 可选的值:%s", + "Argument check failed: %s": "选项值验证失败:%s", + "Implications failed:": "缺少依赖的选项:", + "Not enough arguments following: %s": "没有提供足够的值给此选项:%s", + "Invalid JSON config file: %s": "无效的 JSON 配置文件:%s", + "Path to JSON config file": "JSON 配置文件的路径", + "Show help": "显示帮助信息", + "Show version number": "显示版本号", + "Did you mean %s?": "是指 %s?", + "Arguments %s and %s are mutually exclusive" : "选项 %s 和 %s 是互斥的", + "Positionals:": "位置:", + "command": "命令" +} diff --git a/dist/locales/zh_TW.json b/dist/locales/zh_TW.json new file mode 100644 index 0000000..1249888 --- /dev/null +++ b/dist/locales/zh_TW.json @@ -0,0 +1,40 @@ +{ + "Commands:": "命令:", + "Options:": "選項:", + "Examples:": "例:", + "boolean": "布林", + "count": "次數", + "string": "字串", + "number": "數字", + "array": "陣列", + "required": "必須", + "default:": "預設值:", + "choices:": "可選值:", + "aliases:": "別名:", + "generated-value": "生成的值", + "Not enough non-option arguments: got %s, need at least %s": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個", + "Too many non-option arguments: got %s, maximum of %s": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個", + "Missing argument value: %s": { + "one": "此引數無指定值:%s", + "other": "這些引數無指定值:%s" + }, + "Missing required argument: %s": { + "one": "缺少必須的引數:%s", + "other": "缺少這些必須的引數:%s" + }, + "Unknown argument: %s": { + "one": "未知的引數:%s", + "other": "未知的這些引數:%s" + }, + "Invalid values:": "無效的選項值:", + "Argument: %s, Given: %s, Choices: %s": "引數名稱: %s, 傳入的值: %s, 可選的值:%s", + "Argument check failed: %s": "引數驗證失敗:%s", + "Implications failed:": "缺少依賴的選項:", + "Not enough arguments following: %s": "沒有提供足夠的值給此引數:%s", + "Invalid JSON config file: %s": "無效的 JSON 設置文件:%s", + "Path to JSON config file": "JSON 設置文件的路徑", + "Show help": "顯示說明", + "Show version number": "顯示版本", + "Did you mean %s?": "是指 %s?", + "Arguments %s and %s are mutually exclusive" : "引數 %s 和 %s 是互斥的" +} diff --git a/dist/sourcemap-register.js b/dist/sourcemap-register.js new file mode 100644 index 0000000..e822564 --- /dev/null +++ b/dist/sourcemap-register.js @@ -0,0 +1,3910 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 650: +/***/ ((module) => { + +var toString = Object.prototype.toString + +var isModern = ( + typeof Buffer.alloc === 'function' && + typeof Buffer.allocUnsafe === 'function' && + typeof Buffer.from === 'function' +) + +function isArrayBuffer (input) { + return toString.call(input).slice(8, -1) === 'ArrayBuffer' +} + +function fromArrayBuffer (obj, byteOffset, length) { + byteOffset >>>= 0 + + var maxLength = obj.byteLength - byteOffset + + if (maxLength < 0) { + throw new RangeError("'offset' is out of bounds") + } + + if (length === undefined) { + length = maxLength + } else { + length >>>= 0 + + if (length > maxLength) { + throw new RangeError("'length' is out of bounds") + } + } + + return isModern + ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) + : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + return isModern + ? Buffer.from(string, encoding) + : new Buffer(string, encoding) +} + +function bufferFrom (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (isArrayBuffer(value)) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + return isModern + ? Buffer.from(value) + : new Buffer(value) +} + +module.exports = bufferFrom + + +/***/ }), + +/***/ 645: +/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { + +__webpack_require__(284).install(); + + +/***/ }), + +/***/ 284: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var SourceMapConsumer = __webpack_require__(596).SourceMapConsumer; +var path = __webpack_require__(622); + +var fs; +try { + fs = __webpack_require__(747); + if (!fs.existsSync || !fs.readFileSync) { + // fs doesn't have all methods we need + fs = null; + } +} catch (err) { + /* nop */ +} + +var bufferFrom = __webpack_require__(650); + +// Only install once if called multiple times +var errorFormatterInstalled = false; +var uncaughtShimInstalled = false; + +// If true, the caches are reset before a stack trace formatting operation +var emptyCacheBetweenOperations = false; + +// Supports {browser, node, auto} +var environment = "auto"; + +// Maps a file path to a string containing the file contents +var fileContentsCache = {}; + +// Maps a file path to a source map for that file +var sourceMapCache = {}; + +// Regex for detecting source maps +var reSourceMap = /^data:application\/json[^,]+base64,/; + +// Priority list of retrieve handlers +var retrieveFileHandlers = []; +var retrieveMapHandlers = []; + +function isInBrowser() { + if (environment === "browser") + return true; + if (environment === "node") + return false; + return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer")); +} + +function hasGlobalProcessEventEmitter() { + return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function')); +} + +function handlerExec(list) { + return function(arg) { + for (var i = 0; i < list.length; i++) { + var ret = list[i](arg); + if (ret) { + return ret; + } + } + return null; + }; +} + +var retrieveFile = handlerExec(retrieveFileHandlers); + +retrieveFileHandlers.push(function(path) { + // Trim the path to make sure there is no extra whitespace. + path = path.trim(); + if (/^file:/.test(path)) { + // existsSync/readFileSync can't handle file protocol, but once stripped, it works + path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) { + return drive ? + '' : // file:///C:/dir/file -> C:/dir/file + '/'; // file:///root-dir/file -> /root-dir/file + }); + } + if (path in fileContentsCache) { + return fileContentsCache[path]; + } + + var contents = ''; + try { + if (!fs) { + // Use SJAX if we are in the browser + var xhr = new XMLHttpRequest(); + xhr.open('GET', path, /** async */ false); + xhr.send(null); + if (xhr.readyState === 4 && xhr.status === 200) { + contents = xhr.responseText; + } + } else if (fs.existsSync(path)) { + // Otherwise, use the filesystem + contents = fs.readFileSync(path, 'utf8'); + } + } catch (er) { + /* ignore any errors */ + } + + return fileContentsCache[path] = contents; +}); + +// Support URLs relative to a directory, but be careful about a protocol prefix +// in case we are in the browser (i.e. directories may start with "http://" or "file:///") +function supportRelativeURL(file, url) { + if (!file) return url; + var dir = path.dirname(file); + var match = /^\w+:\/\/[^\/]*/.exec(dir); + var protocol = match ? match[0] : ''; + var startPath = dir.slice(protocol.length); + if (protocol && /^\/\w\:/.test(startPath)) { + // handle file:///C:/ paths + protocol += '/'; + return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/'); + } + return protocol + path.resolve(dir.slice(protocol.length), url); +} + +function retrieveSourceMapURL(source) { + var fileData; + + if (isInBrowser()) { + try { + var xhr = new XMLHttpRequest(); + xhr.open('GET', source, false); + xhr.send(null); + fileData = xhr.readyState === 4 ? xhr.responseText : null; + + // Support providing a sourceMappingURL via the SourceMap header + var sourceMapHeader = xhr.getResponseHeader("SourceMap") || + xhr.getResponseHeader("X-SourceMap"); + if (sourceMapHeader) { + return sourceMapHeader; + } + } catch (e) { + } + } + + // Get the URL of the source map + fileData = retrieveFile(source); + var re = /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/)[ \t]*$)/mg; + // Keep executing the search to find the *last* sourceMappingURL to avoid + // picking up sourceMappingURLs from comments, strings, etc. + var lastMatch, match; + while (match = re.exec(fileData)) lastMatch = match; + if (!lastMatch) return null; + return lastMatch[1]; +}; + +// Can be overridden by the retrieveSourceMap option to install. Takes a +// generated source filename; returns a {map, optional url} object, or null if +// there is no source map. The map field may be either a string or the parsed +// JSON object (ie, it must be a valid argument to the SourceMapConsumer +// constructor). +var retrieveSourceMap = handlerExec(retrieveMapHandlers); +retrieveMapHandlers.push(function(source) { + var sourceMappingURL = retrieveSourceMapURL(source); + if (!sourceMappingURL) return null; + + // Read the contents of the source map + var sourceMapData; + if (reSourceMap.test(sourceMappingURL)) { + // Support source map URL as a data url + var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1); + sourceMapData = bufferFrom(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + // Support source map URLs relative to the source URL + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(sourceMappingURL); + } + + if (!sourceMapData) { + return null; + } + + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); + +function mapSourcePosition(position) { + var sourceMap = sourceMapCache[position.source]; + if (!sourceMap) { + // Call the (overrideable) retrieveSourceMap function to get the source map. + var urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap) { + sourceMap = sourceMapCache[position.source] = { + url: urlAndMap.url, + map: new SourceMapConsumer(urlAndMap.map) + }; + + // Load all sources stored inline with the source map into the file cache + // to pretend like they are already loaded. They may not exist on disk. + if (sourceMap.map.sourcesContent) { + sourceMap.map.sources.forEach(function(source, i) { + var contents = sourceMap.map.sourcesContent[i]; + if (contents) { + var url = supportRelativeURL(sourceMap.url, source); + fileContentsCache[url] = contents; + } + }); + } + } else { + sourceMap = sourceMapCache[position.source] = { + url: null, + map: null + }; + } + } + + // Resolve the source URL relative to the URL of the source map + if (sourceMap && sourceMap.map) { + var originalPosition = sourceMap.map.originalPositionFor(position); + + // Only return the original position if a matching line was found. If no + // matching line is found then we return position instead, which will cause + // the stack trace to print the path and line for the compiled file. It is + // better to give a precise location in the compiled file than a vague + // location in the original file. + if (originalPosition.source !== null) { + originalPosition.source = supportRelativeURL( + sourceMap.url, originalPosition.source); + return originalPosition; + } + } + + return position; +} + +// Parses code generated by FormatEvalOrigin(), a function inside V8: +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +function mapEvalOrigin(origin) { + // Most eval() calls are in this format + var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + var position = mapSourcePosition({ + source: match[2], + line: +match[3], + column: match[4] - 1 + }); + return 'eval at ' + match[1] + ' (' + position.source + ':' + + position.line + ':' + (position.column + 1) + ')'; + } + + // Parse nested eval() calls using recursion + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) { + return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')'; + } + + // Make sure we still return useful information if we didn't find anything + return origin; +} + +// This is copied almost verbatim from the V8 source code at +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The +// implementation of wrapCallSite() used to just forward to the actual source +// code of CallSite.prototype.toString but unfortunately a new release of V8 +// did something to the prototype chain and broke the shim. The only fix I +// could find was copy/paste. +function CallSiteToString() { + var fileName; + var fileLocation = ""; + if (this.isNative()) { + fileLocation = "native"; + } else { + fileName = this.getScriptNameOrSourceURL(); + if (!fileName && this.isEval()) { + fileLocation = this.getEvalOrigin(); + fileLocation += ", "; // Expecting source position to follow. + } + + if (fileName) { + fileLocation += fileName; + } else { + // Source code does not originate from a file and is not native, but we + // can still get the source position inside the source string, e.g. in + // an eval string. + fileLocation += ""; + } + var lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += ":" + lineNumber; + var columnNumber = this.getColumnNumber(); + if (columnNumber) { + fileLocation += ":" + columnNumber; + } + } + } + + var line = ""; + var functionName = this.getFunctionName(); + var addSuffix = true; + var isConstructor = this.isConstructor(); + var isMethodCall = !(this.isToplevel() || isConstructor); + if (isMethodCall) { + var typeName = this.getTypeName(); + // Fixes shim to be backward compatable with Node v0 to v4 + if (typeName === "[object Object]") { + typeName = "null"; + } + var methodName = this.getMethodName(); + if (functionName) { + if (typeName && functionName.indexOf(typeName) != 0) { + line += typeName + "."; + } + line += functionName; + if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) { + line += " [as " + methodName + "]"; + } + } else { + line += typeName + "." + (methodName || ""); + } + } else if (isConstructor) { + line += "new " + (functionName || ""); + } else if (functionName) { + line += functionName; + } else { + line += fileLocation; + addSuffix = false; + } + if (addSuffix) { + line += " (" + fileLocation + ")"; + } + return line; +} + +function cloneCallSite(frame) { + var object = {}; + Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { + object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; + }); + object.toString = CallSiteToString; + return object; +} + +function wrapCallSite(frame) { + if(frame.isNative()) { + return frame; + } + + // Most call sites will return the source file from getFileName(), but code + // passed to eval() ending in "//# sourceURL=..." will return the source file + // from getScriptNameOrSourceURL() instead + var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + var line = frame.getLineNumber(); + var column = frame.getColumnNumber() - 1; + + // Fix position in Node where some (internal) code is prepended. + // See https://github.com/evanw/node-source-map-support/issues/36 + var headerLength = 62; + if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) { + column -= headerLength; + } + + var position = mapSourcePosition({ + source: source, + line: line, + column: column + }); + frame = cloneCallSite(frame); + var originalFunctionName = frame.getFunctionName; + frame.getFunctionName = function() { return position.name || originalFunctionName(); }; + frame.getFileName = function() { return position.source; }; + frame.getLineNumber = function() { return position.line; }; + frame.getColumnNumber = function() { return position.column + 1; }; + frame.getScriptNameOrSourceURL = function() { return position.source; }; + return frame; + } + + // Code called using eval() needs special handling + var origin = frame.isEval() && frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(origin); + frame = cloneCallSite(frame); + frame.getEvalOrigin = function() { return origin; }; + return frame; + } + + // If we get here then we were unable to change the source position + return frame; +} + +// This function is part of the V8 stack trace API, for more info see: +// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi +function prepareStackTrace(error, stack) { + if (emptyCacheBetweenOperations) { + fileContentsCache = {}; + sourceMapCache = {}; + } + + return error + stack.map(function(frame) { + return '\n at ' + wrapCallSite(frame); + }).join(''); +} + +// Generate position and snippet of original source with pointer +function getErrorSource(error) { + var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); + if (match) { + var source = match[1]; + var line = +match[2]; + var column = +match[3]; + + // Support the inline sourceContents inside the source map + var contents = fileContentsCache[source]; + + // Support files on disk + if (!contents && fs && fs.existsSync(source)) { + try { + contents = fs.readFileSync(source, 'utf8'); + } catch (er) { + contents = ''; + } + } + + // Format the line from the original source code like node does + if (contents) { + var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; + if (code) { + return source + ':' + line + '\n' + code + '\n' + + new Array(column).join(' ') + '^'; + } + } + } + return null; +} + +function printErrorAndExit (error) { + var source = getErrorSource(error); + + // Ensure error is printed synchronously and not truncated + if (process.stderr._handle && process.stderr._handle.setBlocking) { + process.stderr._handle.setBlocking(true); + } + + if (source) { + console.error(); + console.error(source); + } + + console.error(error.stack); + process.exit(1); +} + +function shimEmitUncaughtException () { + var origEmit = process.emit; + + process.emit = function (type) { + if (type === 'uncaughtException') { + var hasStack = (arguments[1] && arguments[1].stack); + var hasListeners = (this.listeners(type).length > 0); + + if (hasStack && !hasListeners) { + return printErrorAndExit(arguments[1]); + } + } + + return origEmit.apply(this, arguments); + }; +} + +var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0); +var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0); + +exports.wrapCallSite = wrapCallSite; +exports.getErrorSource = getErrorSource; +exports.mapSourcePosition = mapSourcePosition; +exports.retrieveSourceMap = retrieveSourceMap; + +exports.install = function(options) { + options = options || {}; + + if (options.environment) { + environment = options.environment; + if (["node", "browser", "auto"].indexOf(environment) === -1) { + throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}") + } + } + + // Allow sources to be found by methods other than reading the files + // directly from disk. + if (options.retrieveFile) { + if (options.overrideRetrieveFile) { + retrieveFileHandlers.length = 0; + } + + retrieveFileHandlers.unshift(options.retrieveFile); + } + + // Allow source maps to be found by methods other than reading the files + // directly from disk. + if (options.retrieveSourceMap) { + if (options.overrideRetrieveSourceMap) { + retrieveMapHandlers.length = 0; + } + + retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + + // Support runtime transpilers that include inline source maps + if (options.hookRequire && !isInBrowser()) { + var Module; + try { + Module = __webpack_require__(282); + } catch (err) { + // NOP: Loading in catch block to convert webpack error to warning. + } + var $compile = Module.prototype._compile; + + if (!$compile.__sourceMapSupport) { + Module.prototype._compile = function(content, filename) { + fileContentsCache[filename] = content; + sourceMapCache[filename] = undefined; + return $compile.call(this, content, filename); + }; + + Module.prototype._compile.__sourceMapSupport = true; + } + } + + // Configure options + if (!emptyCacheBetweenOperations) { + emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? + options.emptyCacheBetweenOperations : false; + } + + // Install the error reformatter + if (!errorFormatterInstalled) { + errorFormatterInstalled = true; + Error.prepareStackTrace = prepareStackTrace; + } + + if (!uncaughtShimInstalled) { + var installHandler = 'handleUncaughtExceptions' in options ? + options.handleUncaughtExceptions : true; + + // Provide the option to not install the uncaught exception handler. This is + // to support other uncaught exception handlers (in test frameworks, for + // example). If this handler is not installed and there are no other uncaught + // exception handlers, uncaught exceptions will be caught by node's built-in + // exception handler and the process will still be terminated. However, the + // generated JavaScript code will be shown above the stack trace instead of + // the original source code. + if (installHandler && hasGlobalProcessEventEmitter()) { + uncaughtShimInstalled = true; + shimEmitUncaughtException(); + } + } +}; + +exports.resetRetrieveHandlers = function() { + retrieveFileHandlers.length = 0; + retrieveMapHandlers.length = 0; + + retrieveFileHandlers = originalRetrieveFileHandlers.slice(0); + retrieveMapHandlers = originalRetrieveMapHandlers.slice(0); +} + + +/***/ }), + +/***/ 837: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = __webpack_require__(983); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.I = ArraySet; + + +/***/ }), + +/***/ 215: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * 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 Google Inc. 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 + * OWNER 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 base64 = __webpack_require__(537); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; + + +/***/ }), + +/***/ 537: +/***/ ((__unused_webpack_module, exports) => { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; + + +/***/ }), + +/***/ 164: +/***/ ((__unused_webpack_module, exports) => { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; + + +/***/ }), + +/***/ 740: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = __webpack_require__(983); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.H = MappingList; + + +/***/ }), + +/***/ 226: +/***/ ((__unused_webpack_module, exports) => { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +exports.U = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; + + +/***/ }), + +/***/ 327: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var __webpack_unused_export__; +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = __webpack_require__(983); +var binarySearch = __webpack_require__(164); +var ArraySet = __webpack_require__(837)/* .ArraySet */ .I; +var base64VLQ = __webpack_require__(215); +var quickSort = __webpack_require__(226)/* .quickSort */ .U; + +function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +__webpack_unused_export__ = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +__webpack_unused_export__ = IndexedSourceMapConsumer; + + +/***/ }), + +/***/ 341: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = __webpack_require__(215); +var util = __webpack_require__(983); +var ArraySet = __webpack_require__(837)/* .ArraySet */ .I; +var MappingList = __webpack_require__(740)/* .MappingList */ .H; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +exports.h = SourceMapGenerator; + + +/***/ }), + +/***/ 990: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var __webpack_unused_export__; +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = __webpack_require__(341)/* .SourceMapGenerator */ .h; +var util = __webpack_require__(983); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +__webpack_unused_export__ = SourceNode; + + +/***/ }), + +/***/ 983: +/***/ ((__unused_webpack_module, exports) => { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +} +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; + + +/***/ }), + +/***/ 596: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +/* unused reexport */ __webpack_require__(341)/* .SourceMapGenerator */ .h; +exports.SourceMapConsumer = __webpack_require__(327).SourceMapConsumer; +/* unused reexport */ __webpack_require__(990); + + +/***/ }), + +/***/ 747: +/***/ ((module) => { + +"use strict"; +module.exports = require("fs"); + +/***/ }), + +/***/ 282: +/***/ ((module) => { + +"use strict"; +module.exports = require("module"); + +/***/ }), + +/***/ 622: +/***/ ((module) => { + +"use strict"; +module.exports = require("path"); + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(645); +/******/ })() +; \ No newline at end of file diff --git a/entrypoint.sh b/entrypoint.sh deleted file mode 100755 index e877497..0000000 --- a/entrypoint.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -sh -c "node /app/lib/CLIEntrypoint.js $*" \ No newline at end of file diff --git a/jest.config.js b/jest.config.js index 8c7f0a3..304e365 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,7 +1,18 @@ module.exports = { - moduleFileExtensions: ['ts', 'tsx', 'js'], + clearMocks: true, + moduleFileExtensions: ['js', 'ts'], + testEnvironment: 'node', + testMatch: ['**/*.test.ts'], transform: { - '^.+\\.tsx?$': 'ts-jest', + '^.+\\.ts$': 'ts-jest' }, - testMatch: ['**/src/**/*.test.+(ts|tsx|js)'], + verbose: true } + +// module.exports = { +// moduleFileExtensions: ['ts', 'tsx', 'js'], +// transform: { +// '^.+\\.tsx?$': 'ts-jest', +// }, +// testMatch: ['**/src/**/*.test.+(ts|tsx|js)'], +// } diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..3010c79 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,9989 @@ +{ + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "@actions/core": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.5.tgz", + "integrity": "sha512-mwpoNjHSWWh0IiALdDEQi3tru124JKn0yVNziIBzTME8QRv7thwoghVuT1jBRjFvdtoHsqD58IRHy1nf86paRg==" + }, + "@babel/code-frame": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", + "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==", + "dev": true, + "requires": { + "@babel/highlight": "^7.10.4" + } + }, + "@babel/core": { + "version": "7.11.6", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.11.6.tgz", + "integrity": "sha512-Wpcv03AGnmkgm6uS6k8iwhIwTrcP0m17TL1n1sy7qD0qelDu4XNeW0dN0mHfa+Gei211yDaLoEe/VlbXQzM4Bg==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.10.4", + "@babel/generator": "^7.11.6", + "@babel/helper-module-transforms": "^7.11.0", + "@babel/helpers": "^7.10.4", + "@babel/parser": "^7.11.5", + "@babel/template": "^7.10.4", + "@babel/traverse": "^7.11.5", + "@babel/types": "^7.11.5", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.1", + "json5": "^2.1.2", + "lodash": "^4.17.19", + "resolve": "^1.3.2", + "semver": "^5.4.1", + "source-map": "^0.5.0" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + } + } + }, + "@babel/generator": { + "version": "7.11.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.11.6.tgz", + "integrity": "sha512-DWtQ1PV3r+cLbySoHrwn9RWEgKMBLLma4OBQloPRyDYvc5msJM9kvTLo1YnlJd1P/ZuKbdli3ijr5q3FvAF3uA==", + "dev": true, + "requires": { + "@babel/types": "^7.11.5", + "jsesc": "^2.5.1", + "source-map": "^0.5.0" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + } + } + }, + "@babel/helper-function-name": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.10.4.tgz", + "integrity": "sha512-YdaSyz1n8gY44EmN7x44zBn9zQ1Ry2Y+3GTA+3vH6Mizke1Vw0aWDM66FOYEPw8//qKkmqOckrGgTYa+6sceqQ==", + "dev": true, + "requires": { + "@babel/helper-get-function-arity": "^7.10.4", + "@babel/template": "^7.10.4", + "@babel/types": "^7.10.4" + } + }, + "@babel/helper-get-function-arity": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.10.4.tgz", + "integrity": "sha512-EkN3YDB+SRDgiIUnNgcmiD361ti+AVbL3f3Henf6dqqUyr5dMsorno0lJWJuLhDhkI5sYEpgj6y9kB8AOU1I2A==", + "dev": true, + "requires": { + "@babel/types": "^7.10.4" + } + }, + "@babel/helper-member-expression-to-functions": { + "version": "7.11.0", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.11.0.tgz", + "integrity": "sha512-JbFlKHFntRV5qKw3YC0CvQnDZ4XMwgzzBbld7Ly4Mj4cbFy3KywcR8NtNctRToMWJOVvLINJv525Gd6wwVEx/Q==", + "dev": true, + "requires": { + "@babel/types": "^7.11.0" + } + }, + "@babel/helper-module-imports": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.10.4.tgz", + "integrity": "sha512-nEQJHqYavI217oD9+s5MUBzk6x1IlvoS9WTPfgG43CbMEeStE0v+r+TucWdx8KFGowPGvyOkDT9+7DHedIDnVw==", + "dev": true, + "requires": { + "@babel/types": "^7.10.4" + } + }, + "@babel/helper-module-transforms": { + "version": "7.11.0", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.11.0.tgz", + "integrity": "sha512-02EVu8COMuTRO1TAzdMtpBPbe6aQ1w/8fePD2YgQmxZU4gpNWaL9gK3Jp7dxlkUlUCJOTaSeA+Hrm1BRQwqIhg==", + "dev": true, + "requires": { + "@babel/helper-module-imports": "^7.10.4", + "@babel/helper-replace-supers": "^7.10.4", + "@babel/helper-simple-access": "^7.10.4", + "@babel/helper-split-export-declaration": "^7.11.0", + "@babel/template": "^7.10.4", + "@babel/types": "^7.11.0", + "lodash": "^4.17.19" + } + }, + "@babel/helper-optimise-call-expression": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.10.4.tgz", + "integrity": "sha512-n3UGKY4VXwXThEiKrgRAoVPBMqeoPgHVqiHZOanAJCG9nQUL2pLRQirUzl0ioKclHGpGqRgIOkgcIJaIWLpygg==", + "dev": true, + "requires": { + "@babel/types": "^7.10.4" + } + }, + "@babel/helper-plugin-utils": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.10.4.tgz", + "integrity": "sha512-O4KCvQA6lLiMU9l2eawBPMf1xPP8xPfB3iEQw150hOVTqj/rfXz0ThTb4HEzqQfs2Bmo5Ay8BzxfzVtBrr9dVg==", + "dev": true + }, + "@babel/helper-replace-supers": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.10.4.tgz", + "integrity": "sha512-sPxZfFXocEymYTdVK1UNmFPBN+Hv5mJkLPsYWwGBxZAxaWfFu+xqp7b6qWD0yjNuNL2VKc6L5M18tOXUP7NU0A==", + "dev": true, + "requires": { + "@babel/helper-member-expression-to-functions": "^7.10.4", + "@babel/helper-optimise-call-expression": "^7.10.4", + "@babel/traverse": "^7.10.4", + "@babel/types": "^7.10.4" + } + }, + "@babel/helper-simple-access": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.10.4.tgz", + "integrity": "sha512-0fMy72ej/VEvF8ULmX6yb5MtHG4uH4Dbd6I/aHDb/JVg0bbivwt9Wg+h3uMvX+QSFtwr5MeItvazbrc4jtRAXw==", + "dev": true, + "requires": { + "@babel/template": "^7.10.4", + "@babel/types": "^7.10.4" + } + }, + "@babel/helper-split-export-declaration": { + "version": "7.11.0", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.11.0.tgz", + "integrity": "sha512-74Vejvp6mHkGE+m+k5vHY93FX2cAtrw1zXrZXRlG4l410Nm9PxfEiVTn1PjDPV5SnmieiueY4AFg2xqhNFuuZg==", + "dev": true, + "requires": { + "@babel/types": "^7.11.0" + } + }, + "@babel/helper-validator-identifier": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.10.4.tgz", + "integrity": "sha512-3U9y+43hz7ZM+rzG24Qe2mufW5KhvFg/NhnNph+i9mgCtdTCtMJuI1TMkrIUiK7Ix4PYlRF9I5dhqaLYA/ADXw==", + "dev": true + }, + "@babel/helpers": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.10.4.tgz", + "integrity": "sha512-L2gX/XeUONeEbI78dXSrJzGdz4GQ+ZTA/aazfUsFaWjSe95kiCuOZ5HsXvkiw3iwF+mFHSRUfJU8t6YavocdXA==", + "dev": true, + "requires": { + "@babel/template": "^7.10.4", + "@babel/traverse": "^7.10.4", + "@babel/types": "^7.10.4" + } + }, + "@babel/highlight": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.10.4.tgz", + "integrity": "sha512-i6rgnR/YgPEQzZZnbTHHuZdlE8qyoBNalD6F+q4vAFlcMEcqmkoG+mPqJYJCo63qPf74+Y1UZsl3l6f7/RIkmA==", + "dev": true, + "requires": { + "@babel/helper-validator-identifier": "^7.10.4", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "@babel/parser": { + "version": "7.11.5", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.11.5.tgz", + "integrity": "sha512-X9rD8qqm695vgmeaQ4fvz/o3+Wk4ZzQvSHkDBgpYKxpD4qTAUm88ZKtHkVqIOsYFFbIQ6wQYhC6q7pjqVK0E0Q==", + "dev": true + }, + "@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-bigint": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", + "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-class-properties": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.10.4.tgz", + "integrity": "sha512-GCSBF7iUle6rNugfURwNmCGG3Z/2+opxAMLs1nND4bhEG5PuxTIggDBoeYYSujAlLtsupzOHYJQgPS3pivwXIA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.10.4" + } + }, + "@babel/plugin-syntax-import-meta": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", + "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.10.4" + } + }, + "@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.10.4" + } + }, + "@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", + "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.10.4" + } + }, + "@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/template": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.10.4.tgz", + "integrity": "sha512-ZCjD27cGJFUB6nmCB1Enki3r+L5kJveX9pq1SvAUKoICy6CZ9yD8xO086YXdYhvNjBdnekm4ZnaP5yC8Cs/1tA==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.10.4", + "@babel/parser": "^7.10.4", + "@babel/types": "^7.10.4" + } + }, + "@babel/traverse": { + "version": "7.11.5", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.11.5.tgz", + "integrity": "sha512-EjiPXt+r7LiCZXEfRpSJd+jUMnBd4/9OUv7Nx3+0u9+eimMwJmG0Q98lw4/289JCoxSE8OolDMNZaaF/JZ69WQ==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.10.4", + "@babel/generator": "^7.11.5", + "@babel/helper-function-name": "^7.10.4", + "@babel/helper-split-export-declaration": "^7.11.0", + "@babel/parser": "^7.11.5", + "@babel/types": "^7.11.5", + "debug": "^4.1.0", + "globals": "^11.1.0", + "lodash": "^4.17.19" + } + }, + "@babel/types": { + "version": "7.11.5", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.11.5.tgz", + "integrity": "sha512-bvM7Qz6eKnJVFIn+1LPtjlBFPVN5jNDc1XmN15vWe7Q3DPBufWWsLiIvUu7xW87uTG6QoggpIDnUgLQvPheU+Q==", + "dev": true, + "requires": { + "@babel/helper-validator-identifier": "^7.10.4", + "lodash": "^4.17.19", + "to-fast-properties": "^2.0.0" + } + }, + "@bcoe/v8-coverage": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", + "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", + "dev": true + }, + "@cnakazawa/watch": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@cnakazawa/watch/-/watch-1.0.4.tgz", + "integrity": "sha512-v9kIhKwjeZThiWrLmj0y17CWoyddASLj9O2yvbZkbvw/N3rWOYy9zkV66ursAoVr0mV15bL8g0c4QZUE6cdDoQ==", + "dev": true, + "requires": { + "exec-sh": "^0.3.2", + "minimist": "^1.2.0" + } + }, + "@hapi/bourne": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@hapi/bourne/-/bourne-1.3.2.tgz", + "integrity": "sha512-1dVNHT76Uu5N3eJNTYcvxee+jzX4Z9lfciqRRHCU27ihbUcYi+iSc2iml5Ke1LXe1SyJCLA0+14Jh4tXJgOppA==" + }, + "@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dev": true, + "requires": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "dependencies": { + "camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true + }, + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true + } + } + }, + "@istanbuljs/schema": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.2.tgz", + "integrity": "sha512-tsAQNx32a8CoFhjhijUIhI4kccIAgmGhy8LZMZgGfmXcpMbPRUqn5LWmgRttILi6yeGmBJd2xsPkFMs0PzgPCw==", + "dev": true + }, + "@jest/console": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-26.3.0.tgz", + "integrity": "sha512-/5Pn6sJev0nPUcAdpJHMVIsA8sKizL2ZkcKPE5+dJrCccks7tcM7c9wbgHudBJbxXLoTbqsHkG1Dofoem4F09w==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "@types/node": "*", + "chalk": "^4.0.0", + "jest-message-util": "^26.3.0", + "jest-util": "^26.3.0", + "slash": "^3.0.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "@jest/core": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-26.4.2.tgz", + "integrity": "sha512-sDva7YkeNprxJfepOctzS8cAk9TOekldh+5FhVuXS40+94SHbiicRO1VV2tSoRtgIo+POs/Cdyf8p76vPTd6dg==", + "dev": true, + "requires": { + "@jest/console": "^26.3.0", + "@jest/reporters": "^26.4.1", + "@jest/test-result": "^26.3.0", + "@jest/transform": "^26.3.0", + "@jest/types": "^26.3.0", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.4", + "jest-changed-files": "^26.3.0", + "jest-config": "^26.4.2", + "jest-haste-map": "^26.3.0", + "jest-message-util": "^26.3.0", + "jest-regex-util": "^26.0.0", + "jest-resolve": "^26.4.0", + "jest-resolve-dependencies": "^26.4.2", + "jest-runner": "^26.4.2", + "jest-runtime": "^26.4.2", + "jest-snapshot": "^26.4.2", + "jest-util": "^26.3.0", + "jest-validate": "^26.4.2", + "jest-watcher": "^26.3.0", + "micromatch": "^4.0.2", + "p-each-series": "^2.1.0", + "rimraf": "^3.0.0", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.0" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "@jest/environment": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-26.3.0.tgz", + "integrity": "sha512-EW+MFEo0DGHahf83RAaiqQx688qpXgl99wdb8Fy67ybyzHwR1a58LHcO376xQJHfmoXTu89M09dH3J509cx2AA==", + "dev": true, + "requires": { + "@jest/fake-timers": "^26.3.0", + "@jest/types": "^26.3.0", + "@types/node": "*", + "jest-mock": "^26.3.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "@jest/fake-timers": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-26.3.0.tgz", + "integrity": "sha512-ZL9ytUiRwVP8ujfRepffokBvD2KbxbqMhrXSBhSdAhISCw3gOkuntisiSFv+A6HN0n0fF4cxzICEKZENLmW+1A==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "@sinonjs/fake-timers": "^6.0.1", + "@types/node": "*", + "jest-message-util": "^26.3.0", + "jest-mock": "^26.3.0", + "jest-util": "^26.3.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "@jest/globals": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-26.4.2.tgz", + "integrity": "sha512-Ot5ouAlehhHLRhc+sDz2/9bmNv9p5ZWZ9LE1pXGGTCXBasmi5jnYjlgYcYt03FBwLmZXCZ7GrL29c33/XRQiow==", + "dev": true, + "requires": { + "@jest/environment": "^26.3.0", + "@jest/types": "^26.3.0", + "expect": "^26.4.2" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "@jest/reporters": { + "version": "26.4.1", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-26.4.1.tgz", + "integrity": "sha512-aROTkCLU8++yiRGVxLsuDmZsQEKO6LprlrxtAuzvtpbIFl3eIjgIf3EUxDKgomkS25R9ZzwGEdB5weCcBZlrpQ==", + "dev": true, + "requires": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^26.3.0", + "@jest/test-result": "^26.3.0", + "@jest/transform": "^26.3.0", + "@jest/types": "^26.3.0", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.2", + "graceful-fs": "^4.2.4", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^4.0.3", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.0.2", + "jest-haste-map": "^26.3.0", + "jest-resolve": "^26.4.0", + "jest-util": "^26.3.0", + "jest-worker": "^26.3.0", + "node-notifier": "^8.0.0", + "slash": "^3.0.0", + "source-map": "^0.6.0", + "string-length": "^4.0.1", + "terminal-link": "^2.0.0", + "v8-to-istanbul": "^5.0.1" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "@jest/source-map": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-26.3.0.tgz", + "integrity": "sha512-hWX5IHmMDWe1kyrKl7IhFwqOuAreIwHhbe44+XH2ZRHjrKIh0LO5eLQ/vxHFeAfRwJapmxuqlGAEYLadDq6ZGQ==", + "dev": true, + "requires": { + "callsites": "^3.0.0", + "graceful-fs": "^4.2.4", + "source-map": "^0.6.0" + } + }, + "@jest/test-result": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-26.3.0.tgz", + "integrity": "sha512-a8rbLqzW/q7HWheFVMtghXV79Xk+GWwOK1FrtimpI5n1la2SY0qHri3/b0/1F0Ve0/yJmV8pEhxDfVwiUBGtgg==", + "dev": true, + "requires": { + "@jest/console": "^26.3.0", + "@jest/types": "^26.3.0", + "@types/istanbul-lib-coverage": "^2.0.0", + "collect-v8-coverage": "^1.0.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "@jest/test-sequencer": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-26.4.2.tgz", + "integrity": "sha512-83DRD8N3M0tOhz9h0bn6Kl6dSp+US6DazuVF8J9m21WAp5x7CqSMaNycMP0aemC/SH/pDQQddbsfHRTBXVUgog==", + "dev": true, + "requires": { + "@jest/test-result": "^26.3.0", + "graceful-fs": "^4.2.4", + "jest-haste-map": "^26.3.0", + "jest-runner": "^26.4.2", + "jest-runtime": "^26.4.2" + } + }, + "@jest/transform": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-26.3.0.tgz", + "integrity": "sha512-Isj6NB68QorGoFWvcOjlUhpkT56PqNIsXKR7XfvoDlCANn/IANlh8DrKAA2l2JKC3yWSMH5wS0GwuQM20w3b2A==", + "dev": true, + "requires": { + "@babel/core": "^7.1.0", + "@jest/types": "^26.3.0", + "babel-plugin-istanbul": "^6.0.0", + "chalk": "^4.0.0", + "convert-source-map": "^1.4.0", + "fast-json-stable-stringify": "^2.0.0", + "graceful-fs": "^4.2.4", + "jest-haste-map": "^26.3.0", + "jest-regex-util": "^26.0.0", + "jest-util": "^26.3.0", + "micromatch": "^4.0.2", + "pirates": "^4.0.1", + "slash": "^3.0.0", + "source-map": "^0.6.1", + "write-file-atomic": "^3.0.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "@jest/types": { + "version": "25.5.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-25.5.0.tgz", + "integrity": "sha512-OXD0RgQ86Tu3MazKo8bnrkDRaDXXMGUqd+kTtLtK1Zb7CRzQcaSRPPPV37SvYTdevXEBVxe0HXylEjs8ibkmCw==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^1.1.1", + "@types/yargs": "^15.0.0", + "chalk": "^3.0.0" + }, + "dependencies": { + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", + "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "@octokit/auth-token": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.2.tgz", + "integrity": "sha512-jE/lE/IKIz2v1+/P0u4fJqv0kYwXOTujKemJMFr6FeopsxlIK3+wKDCJGnysg81XID5TgZQbIfuJ5J0lnTiuyQ==", + "requires": { + "@octokit/types": "^5.0.0" + } + }, + "@octokit/core": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.1.2.tgz", + "integrity": "sha512-AInOFULmwOa7+NFi9F8DlDkm5qtZVmDQayi7TUgChE3yeIGPq0Y+6cAEXPexQ3Ea+uZy66hKEazR7DJyU+4wfw==", + "requires": { + "@octokit/auth-token": "^2.4.0", + "@octokit/graphql": "^4.3.1", + "@octokit/request": "^5.4.0", + "@octokit/types": "^5.0.0", + "before-after-hook": "^2.1.0", + "universal-user-agent": "^6.0.0" + } + }, + "@octokit/endpoint": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.5.tgz", + "integrity": "sha512-70K5u6zd45ItOny6aHQAsea8HHQjlQq85yqOMe+Aj8dkhN2qSJ9T+Q3YjUjEYfPRBcuUWNgMn62DQnP/4LAIiQ==", + "requires": { + "@octokit/types": "^5.0.0", + "is-plain-object": "^4.0.0", + "universal-user-agent": "^6.0.0" + } + }, + "@octokit/graphql": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.4.tgz", + "integrity": "sha512-ITpZ+dQc0cXAW1FmDkHJJM+8Lb6anUnin0VB5hLBilnYVdLC0ICFU/KIvT7OXfW9S81DE3U4Vx2EypDG1OYaPA==", + "requires": { + "@octokit/request": "^5.3.0", + "@octokit/types": "^5.0.0", + "universal-user-agent": "^6.0.0" + } + }, + "@octokit/plugin-paginate-rest": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.3.2.tgz", + "integrity": "sha512-PjHbMhKryxClCrmfvRpGaKCTxUcHIf2zirWRV9SMGf0EmxD/rFew/abSqbMiLl9uQgRZvqtTyCRMGMlUv1ZsBg==", + "requires": { + "@octokit/types": "^5.3.0" + } + }, + "@octokit/plugin-request-log": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-1.0.0.tgz", + "integrity": "sha512-ywoxP68aOT3zHCLgWZgwUJatiENeHE7xJzYjfz8WI0goynp96wETBF+d95b8g/uL4QmS6owPVlaxiz3wyMAzcw==" + }, + "@octokit/plugin-rest-endpoint-methods": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-4.1.4.tgz", + "integrity": "sha512-Y2tVpSa7HjV3DGIQrQOJcReJ2JtcN9FaGr9jDa332Flro923/h3/Iu9e7Y4GilnzfLclHEh5iCQoCkHm7tWOcg==", + "requires": { + "@octokit/types": "^5.4.1", + "deprecation": "^2.3.1" + } + }, + "@octokit/request": { + "version": "5.4.7", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.7.tgz", + "integrity": "sha512-FN22xUDP0i0uF38YMbOfx6TotpcENP5W8yJM1e/LieGXn6IoRxDMnBf7tx5RKSW4xuUZ/1P04NFZy5iY3Rax1A==", + "requires": { + "@octokit/endpoint": "^6.0.1", + "@octokit/request-error": "^2.0.0", + "@octokit/types": "^5.0.0", + "deprecation": "^2.0.0", + "is-plain-object": "^4.0.0", + "node-fetch": "^2.3.0", + "once": "^1.4.0", + "universal-user-agent": "^6.0.0" + } + }, + "@octokit/request-error": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.2.tgz", + "integrity": "sha512-2BrmnvVSV1MXQvEkrb9zwzP0wXFNbPJij922kYBTLIlIafukrGOb+ABBT2+c6wZiuyWDH1K1zmjGQ0toN/wMWw==", + "requires": { + "@octokit/types": "^5.0.1", + "deprecation": "^2.0.0", + "once": "^1.4.0" + } + }, + "@octokit/rest": { + "version": "18.0.5", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-18.0.5.tgz", + "integrity": "sha512-SPKI24tQXrr1XsnaIjv2x0rl4M5eF1+hj8+vMe3d/exZ7NnL5sTe1BuFyCyJyrc+j1HkXankvgGN9zT0rwBwtg==", + "requires": { + "@octokit/core": "^3.0.0", + "@octokit/plugin-paginate-rest": "^2.2.0", + "@octokit/plugin-request-log": "^1.0.0", + "@octokit/plugin-rest-endpoint-methods": "4.1.4" + } + }, + "@octokit/types": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-5.4.1.tgz", + "integrity": "sha512-OlMlSySBJoJ6uozkr/i03nO5dlYQyE05vmQNZhAh9MyO4DPBP88QlwsDVLmVjIMFssvIZB6WO0ctIGMRG+xsJQ==", + "requires": { + "@types/node": ">= 8" + } + }, + "@sinonjs/commons": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.1.tgz", + "integrity": "sha512-892K+kWUUi3cl+LlqEWIDrhvLgdL79tECi8JZUyq6IviKy/DNhuzCRlbHUjxK89f4ypPMMaFnFuR9Ie6DoIMsw==", + "dev": true, + "requires": { + "type-detect": "4.0.8" + } + }, + "@sinonjs/fake-timers": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-6.0.1.tgz", + "integrity": "sha512-MZPUxrmFubI36XS1DI3qmI0YdN1gks62JtFZvxR67ljjSNCeK6U08Zx4msEWOXuofgqUt6zPHSi1H9fbjR/NRA==", + "dev": true, + "requires": { + "@sinonjs/commons": "^1.7.0" + } + }, + "@types/babel__core": { + "version": "7.1.9", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.1.9.tgz", + "integrity": "sha512-sY2RsIJ5rpER1u3/aQ8OFSI7qGIy8o1NEEbgb2UaJcvOtXOMpd39ko723NBpjQFg9SIX7TXtjejZVGeIMLhoOw==", + "dev": true, + "requires": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "@types/babel__generator": { + "version": "7.6.1", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.1.tgz", + "integrity": "sha512-bBKm+2VPJcMRVwNhxKu8W+5/zT7pwNEqeokFOmbvVSqGzFneNxYcEBro9Ac7/N9tlsaPYnZLK8J1LWKkMsLAew==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0" + } + }, + "@types/babel__template": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.0.2.tgz", + "integrity": "sha512-/K6zCpeW7Imzgab2bLkLEbz0+1JlFSrUMdw7KoIIu+IUdu51GWaBZpd3y1VXGVXzynvGa4DaIaxNZHiON3GXUg==", + "dev": true, + "requires": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "@types/babel__traverse": { + "version": "7.0.14", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.0.14.tgz", + "integrity": "sha512-8w9szzKs14ZtBVuP6Wn7nMLRJ0D6dfB0VEBEyRgxrZ/Ln49aNMykrghM2FaNn4FJRzNppCSa0Rv9pBRM5Xc3wg==", + "dev": true, + "requires": { + "@babel/types": "^7.3.0" + } + }, + "@types/bson": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/bson/-/bson-4.0.2.tgz", + "integrity": "sha512-+uWmsejEHfmSjyyM/LkrP0orfE2m5Mx9Xel4tXNeqi1ldK5XMQcDsFkBmLDtuyKUbxj2jGDo0H240fbCRJZo7Q==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, + "@types/color-name": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz", + "integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==", + "dev": true + }, + "@types/events": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-3.0.0.tgz", + "integrity": "sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g==" + }, + "@types/graceful-fs": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.3.tgz", + "integrity": "sha512-AiHRaEB50LQg0pZmm659vNBb9f4SJ0qrAnteuzhSeAUcJKxoYgEnprg/83kppCnc2zvtCKbdZry1a5pVY3lOTQ==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, + "@types/invariant": { + "version": "2.2.34", + "resolved": "https://registry.npmjs.org/@types/invariant/-/invariant-2.2.34.tgz", + "integrity": "sha512-lYUtmJ9BqUN688fGY1U1HZoWT1/Jrmgigx2loq4ZcJpICECm/Om3V314BxdzypO0u5PORKGMM6x0OXaljV1YFg==" + }, + "@types/istanbul-lib-coverage": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.3.tgz", + "integrity": "sha512-sz7iLqvVUg1gIedBOvlkxPlc8/uVzyS5OwGz1cKjXzkl3FpL3al0crU8YGU1WoHkxn0Wxbw5tyi6hvzJKNzFsw==", + "dev": true + }, + "@types/istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "*" + } + }, + "@types/istanbul-reports": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-1.1.2.tgz", + "integrity": "sha512-P/W9yOX/3oPZSpaYOCQzGqgCQRXn0FFO/V8bWrCQs+wLmvVVxk6CRBXALEvNs9OHIatlnlFokfhuDo2ug01ciw==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "*", + "@types/istanbul-lib-report": "*" + } + }, + "@types/jest": { + "version": "26.0.13", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-26.0.13.tgz", + "integrity": "sha512-sCzjKow4z9LILc6DhBvn5AkIfmQzDZkgtVVKmGwVrs5tuid38ws281D4l+7x1kP487+FlKDh5kfMZ8WSPAdmdA==", + "dev": true, + "requires": { + "jest-diff": "^25.2.1", + "pretty-format": "^25.2.1" + } + }, + "@types/lodash": { + "version": "4.14.161", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.161.tgz", + "integrity": "sha512-EP6O3Jkr7bXvZZSZYlsgt5DIjiGr0dXP1/jVEwVLTFgg0d+3lWVQkRavYVQszV7dYUwvg0B8R0MBDpcmXg7XIA==", + "dev": true + }, + "@types/lodash.sortby": { + "version": "4.7.6", + "resolved": "https://registry.npmjs.org/@types/lodash.sortby/-/lodash.sortby-4.7.6.tgz", + "integrity": "sha512-EnvAOmKvEg7gdYpYrS6+fVFPw5dL9rBnJi3vcKI7wqWQcLJVF/KRXK9dH29HjGNVvFUj0s9prRP3J8jEGnGKDw==", + "dev": true, + "requires": { + "@types/lodash": "*" + } + }, + "@types/mongodb": { + "version": "3.5.27", + "resolved": "https://registry.npmjs.org/@types/mongodb/-/mongodb-3.5.27.tgz", + "integrity": "sha512-1jxKDgdfJEOO9zp+lv43p8jOqRs02xPrdUTzAZIVK9tVEySfCEmktL2jEu9A3wOBEOs18yKzpVIKUh8b8ALk3w==", + "dev": true, + "requires": { + "@types/bson": "*", + "@types/node": "*" + } + }, + "@types/node": { + "version": "14.6.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.6.4.tgz", + "integrity": "sha512-Wk7nG1JSaMfMpoMJDKUsWYugliB2Vy55pdjLpmLixeyMi7HizW2I/9QoxsPCkXl3dO+ZOVqPumKaDUv5zJu2uQ==" + }, + "@types/normalize-package-data": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.0.tgz", + "integrity": "sha512-f5j5b/Gf71L+dbqxIpQ4Z2WlmI/mPJ0fOkGGmFgtb6sAu97EPczzbS3/tJKxmcYDj55OX6ssqwDAWOHIYDRDGA==", + "dev": true + }, + "@types/pino": { + "version": "5.20.0", + "resolved": "https://registry.npmjs.org/@types/pino/-/pino-5.20.0.tgz", + "integrity": "sha512-gz3Ahvx1UDEveXViOQtYqnUkjSVQFdoJqpZTW/63spEHwOGRJRJIi3JMJSClp5Sk1x1ljn9tHWjGczmP6s/rvg==", + "requires": { + "@types/events": "*", + "@types/node": "*" + } + }, + "@types/prettier": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.1.0.tgz", + "integrity": "sha512-hiYA88aHiEIgDmeKlsyVsuQdcFn3Z2VuFd/Xm/HCnGnPD8UFU5BM128uzzRVVGEzKDKYUrRsRH9S2o+NUy/3IA==", + "dev": true + }, + "@types/stack-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-1.0.1.tgz", + "integrity": "sha512-l42BggppR6zLmpfU6fq9HEa2oGPEI8yrSPL3GITjfRInppYFahObbIQOQK3UGxEnyQpltZLaPe75046NOZQikw==", + "dev": true + }, + "@types/yargs": { + "version": "13.0.10", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-13.0.10.tgz", + "integrity": "sha512-MU10TSgzNABgdzKvQVW1nuuT+sgBMWeXNc3XOs5YXV5SDAK+PPja2eUuBNB9iqElu03xyEDqlnGw0jgl4nbqGQ==", + "requires": { + "@types/yargs-parser": "*" + } + }, + "@types/yargs-parser": { + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-15.0.0.tgz", + "integrity": "sha512-FA/BWv8t8ZWJ+gEOnLLd8ygxH/2UFbAvgEonyfN6yWGLKc7zVjbpl2Y4CTjid9h2RfgPP6SEt6uHwEOply00yw==" + }, + "@typescript-eslint/typescript-estree": { + "version": "2.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-2.34.0.tgz", + "integrity": "sha512-OMAr+nJWKdlVM9LOqCqh3pQQPwxHAN7Du8DR6dmwCrAmxtiXQnhHJ6tBNtf+cggqfo51SG/FCwnKhXCIM7hnVg==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "eslint-visitor-keys": "^1.1.0", + "glob": "^7.1.6", + "is-glob": "^4.0.1", + "lodash": "^4.17.15", + "semver": "^7.3.2", + "tsutils": "^3.17.1" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "semver": { + "version": "7.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.2.tgz", + "integrity": "sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ==", + "dev": true + } + } + }, + "@vercel/ncc": { + "version": "0.24.0", + "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.24.0.tgz", + "integrity": "sha512-crqItMcIwCkvdXY/V3/TzrHJQx6nbIaRqE1cOopJhgGX6izvNov40SmD//nS5flfEvdK54YGjwVVq+zG6crjOg==" + }, + "abab": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.4.tgz", + "integrity": "sha512-Eu9ELJWCz/c1e9gTiCY+FceWxcqzjYEbqMgtndnuSqZSUCOL73TWNK2mHfIj4Cw2E/ongOp+JISVNCmovt2KYQ==", + "dev": true + }, + "acorn": { + "version": "7.4.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.0.tgz", + "integrity": "sha512-+G7P8jJmCHr+S+cLfQxygbWhXy+8YTVGzAkpEbcLo2mLoL7tij/VG41QSHACSf5QgYRhMZYHuNc6drJaO0Da+w==", + "dev": true + }, + "acorn-globals": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-6.0.0.tgz", + "integrity": "sha512-ZQl7LOWaF5ePqqcX4hLuv/bLXYQNfNWw2c0/yX/TsPRKamzHcTGQnlCjHT3TsmkOUVEPS3crCxiPfdzE/Trlhg==", + "dev": true, + "requires": { + "acorn": "^7.1.1", + "acorn-walk": "^7.1.1" + } + }, + "acorn-walk": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-7.2.0.tgz", + "integrity": "sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==", + "dev": true + }, + "ajv": { + "version": "6.12.4", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.4.tgz", + "integrity": "sha512-eienB2c9qVQs2KWexhkrdMLVDoIQCz5KSeLxwg9Lzk4DOfBtIK9PQwwufcsn1jjGuf9WZmqPMbGxOzfcuphJCQ==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ansi-escapes": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.1.tgz", + "integrity": "sha512-JWF7ocqNrp8u9oqpgV+wH5ftbt+cfvv+PTjOvKLT3AdYly/LmORARfEVT1iyjwN+4MqE5UmVKoAdIBqeoCHgLA==", + "dev": true, + "requires": { + "type-fest": "^0.11.0" + }, + "dependencies": { + "type-fest": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.11.0.tgz", + "integrity": "sha512-OdjXJxnCN1AvyLSzeKIgXTXxV+99ZuXl3Hpo9XpJAv9MBcHrrJOQ5kV7ypXOuQie+AmWG25hLbiKdwYTifzcfQ==", + "dev": true + } + } + }, + "ansi-regex": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-0.2.1.tgz", + "integrity": "sha1-DY6UaWej2BQ/k+JOKYUl/BsiNfk=" + }, + "ansi-styles": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-1.1.0.tgz", + "integrity": "sha1-6uy/Zs1waIJ2Cy9GkVgrj1XXp94=" + }, + "anymatch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.1.tgz", + "integrity": "sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg==", + "dev": true, + "requires": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + } + }, + "app-module-path": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/app-module-path/-/app-module-path-2.2.0.tgz", + "integrity": "sha1-ZBqlXft9am8KgUHEucCqULbCTdU=", + "dev": true + }, + "arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "args": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/args/-/args-5.0.1.tgz", + "integrity": "sha512-1kqmFCFsPffavQFGt8OxJdIcETti99kySRUPMpOhaGjL6mRJn8HFU1OxKY5bMqfZKUwTQc1mZkAjmGYaVOHFtQ==", + "requires": { + "camelcase": "5.0.0", + "chalk": "2.4.2", + "leven": "2.1.0", + "mri": "1.1.4" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "leven": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-2.1.0.tgz", + "integrity": "sha1-wuep93IJTe6dNCAq6KzORoeHVYA=" + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "arr-diff": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", + "dev": true + }, + "arr-flatten": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", + "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", + "dev": true + }, + "arr-union": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", + "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", + "dev": true + }, + "array-unique": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", + "dev": true + }, + "asn1": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", + "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "dev": true, + "requires": { + "safer-buffer": "~2.1.0" + } + }, + "assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", + "dev": true + }, + "assign-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", + "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", + "dev": true + }, + "ast-module-types": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/ast-module-types/-/ast-module-types-2.6.0.tgz", + "integrity": "sha512-zXSoVaMrf2R+r+ISid5/9a8SXm1LLdkhHzh6pSRhj9jklzruOOl1hva1YmFT33wAstg/f9ZndJAlq1BSrFLSGA==", + "dev": true + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", + "dev": true + }, + "atob": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", + "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", + "dev": true + }, + "atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==" + }, + "aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", + "dev": true + }, + "aws4": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.10.1.tgz", + "integrity": "sha512-zg7Hz2k5lI8kb7U32998pRRFin7zJlkfezGJjUc2heaD4Pw2wObakCDVzkKztTm/Ln7eiVvYsjqak0Ed4LkMDA==", + "dev": true + }, + "babel-jest": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-26.3.0.tgz", + "integrity": "sha512-sxPnQGEyHAOPF8NcUsD0g7hDCnvLL2XyblRBcgrzTWBB/mAIpWow3n1bEL+VghnnZfreLhFSBsFluRoK2tRK4g==", + "dev": true, + "requires": { + "@jest/transform": "^26.3.0", + "@jest/types": "^26.3.0", + "@types/babel__core": "^7.1.7", + "babel-plugin-istanbul": "^6.0.0", + "babel-preset-jest": "^26.3.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.4", + "slash": "^3.0.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "babel-plugin-istanbul": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.0.0.tgz", + "integrity": "sha512-AF55rZXpe7trmEylbaE1Gv54wn6rwU03aptvRoVIGP8YykoSxqdVLV1TfwflBCE/QtHmqtP8SWlTENqbK8GCSQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-instrument": "^4.0.0", + "test-exclude": "^6.0.0" + } + }, + "babel-plugin-jest-hoist": { + "version": "26.2.0", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-26.2.0.tgz", + "integrity": "sha512-B/hVMRv8Nh1sQ1a3EY8I0n4Y1Wty3NrR5ebOyVT302op+DOAau+xNEImGMsUWOC3++ZlMooCytKz+NgN8aKGbA==", + "dev": true, + "requires": { + "@babel/template": "^7.3.3", + "@babel/types": "^7.3.3", + "@types/babel__core": "^7.0.0", + "@types/babel__traverse": "^7.0.6" + } + }, + "babel-preset-current-node-syntax": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-0.1.3.tgz", + "integrity": "sha512-uyexu1sVwcdFnyq9o8UQYsXwXflIh8LvrF5+cKrYam93ned1CStffB3+BEcsxGSgagoA3GEyjDqO4a/58hyPYQ==", + "dev": true, + "requires": { + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-bigint": "^7.8.3", + "@babel/plugin-syntax-class-properties": "^7.8.3", + "@babel/plugin-syntax-import-meta": "^7.8.3", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.8.3", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3" + } + }, + "babel-preset-jest": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-26.3.0.tgz", + "integrity": "sha512-5WPdf7nyYi2/eRxCbVrE1kKCWxgWY4RsPEbdJWFm7QsesFGqjdkyLeu1zRkwM1cxK6EPIlNd6d2AxLk7J+t4pw==", + "dev": true, + "requires": { + "babel-plugin-jest-hoist": "^26.2.0", + "babel-preset-current-node-syntax": "^0.1.3" + } + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "base": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", + "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", + "dev": true, + "requires": { + "cache-base": "^1.0.1", + "class-utils": "^0.3.5", + "component-emitter": "^1.2.1", + "define-property": "^1.0.0", + "isobject": "^3.0.1", + "mixin-deep": "^1.2.0", + "pascalcase": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "dev": true, + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "before-after-hook": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.1.0.tgz", + "integrity": "sha512-IWIbu7pMqyw3EAJHzzHbWa85b6oud/yfKYg5rqB5hNE8CeMi3nX+2C2sj0HswfblST86hpVEOAb9x34NZd6P7A==" + }, + "bistre": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/bistre/-/bistre-1.0.1.tgz", + "integrity": "sha1-LjT+rmSrO9LjziFwr6VrVnsf7uA=", + "requires": { + "chalk": "^0.5.1", + "split": "^0.3.0", + "stream-combiner": "^0.2.0", + "through2": "^0.5.1" + } + }, + "bl": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/bl/-/bl-2.2.1.tgz", + "integrity": "sha512-6Pesp1w0DEX1N550i/uGV/TqucVL4AM/pgThFSN/Qq9si1/DF9aIHs1BxD8V/QU0HoeHO6cQRTAuYnLPKq1e4g==", + "requires": { + "readable-stream": "^2.3.5", + "safe-buffer": "^5.1.1" + } + }, + "bole": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/bole/-/bole-3.0.2.tgz", + "integrity": "sha1-vIpIPKlASdqbg3wa0Rzf6+5uBRQ=", + "requires": { + "fast-safe-stringify": "~1.1.0", + "individual": "~3.0.0" + } + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "requires": { + "fill-range": "^7.0.1" + } + }, + "browser-process-hrtime": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz", + "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", + "dev": true + }, + "bs-logger": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", + "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", + "dev": true, + "requires": { + "fast-json-stable-stringify": "2.x" + } + }, + "bser": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", + "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", + "dev": true, + "requires": { + "node-int64": "^0.4.0" + } + }, + "bson": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/bson/-/bson-1.1.5.tgz", + "integrity": "sha512-kDuEzldR21lHciPQAIulLs1LZlCXdLziXI6Mb/TDkwXhb//UORJNPXgcRs2CuO4H0DcMkpfT3/ySsP3unoZjBg==" + }, + "bson-objectid": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-1.3.1.tgz", + "integrity": "sha512-eQBNQXsisEAXlwiSy8zRNZdW2xDBJaEVkTPbodYR9hGxxtE548Qq7ilYOd8WAQ86xF7NRUdiWSQ1pa/TkKiE2A==" + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "dev": true + }, + "cache-base": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", + "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", + "dev": true, + "requires": { + "collection-visit": "^1.0.0", + "component-emitter": "^1.2.1", + "get-value": "^2.0.6", + "has-value": "^1.0.0", + "isobject": "^3.0.1", + "set-value": "^2.0.0", + "to-object-path": "^0.3.0", + "union-value": "^1.0.0", + "unset-value": "^1.0.0" + } + }, + "callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true + }, + "camelcase": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.0.0.tgz", + "integrity": "sha512-faqwZqnWxbxn+F1d399ygeamQNy3lPp/H9H6rNrqYh4FSVCtcY+3cub1MxA8o9mDd55mM8Aghuu/kuyYA6VTsA==" + }, + "capture-exit": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/capture-exit/-/capture-exit-2.0.0.tgz", + "integrity": "sha512-PiT/hQmTonHhl/HFGN+Lx3JJUznrVYJ3+AQsnthneZbvW7x+f08Tk7yLJTLEOUvBTbduLeeBkxEaYXUOUrRq6g==", + "dev": true, + "requires": { + "rsvp": "^4.8.4" + } + }, + "caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", + "dev": true + }, + "chalk": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-0.5.1.tgz", + "integrity": "sha1-Zjs6ZItotV0EaQ1JFnqoN4WPIXQ=", + "requires": { + "ansi-styles": "^1.1.0", + "escape-string-regexp": "^1.0.0", + "has-ansi": "^0.1.0", + "strip-ansi": "^0.3.0", + "supports-color": "^0.2.0" + } + }, + "char-regex": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", + "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", + "dev": true + }, + "ci-info": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", + "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==", + "dev": true + }, + "class-utils": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", + "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "define-property": "^0.2.5", + "isobject": "^3.0.0", + "static-extend": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "requires": { + "restore-cursor": "^3.1.0" + } + }, + "cli-spinners": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.4.0.tgz", + "integrity": "sha512-sJAofoarcm76ZGpuooaO0eDy8saEy+YoZBLjC4h8srt4jeBnkYeOgqxgsJQTpyt2LjI5PTfLJHSL+41Yu4fEJA==", + "dev": true + }, + "cliui": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", + "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "requires": { + "string-width": "^3.1.0", + "strip-ansi": "^5.2.0", + "wrap-ansi": "^5.1.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "requires": { + "ansi-regex": "^4.1.0" + } + } + } + }, + "clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=", + "dev": true + }, + "co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", + "dev": true + }, + "collect-v8-coverage": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz", + "integrity": "sha512-iBPtljfCNcTKNAto0KEtDfZ3qzjJvqE3aTGZsbhjSBlorqpXJlaWWtPO35D+ZImoC3KWejX64o+yPGxhWSTzfg==", + "dev": true + }, + "collection-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", + "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", + "dev": true, + "requires": { + "map-visit": "^1.0.0", + "object-visit": "^1.0.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + }, + "combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "commander": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz", + "integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==", + "dev": true + }, + "commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", + "dev": true + }, + "component-emitter": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "convert-source-map": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", + "integrity": "sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.1" + }, + "dependencies": { + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + } + } + }, + "copy-descriptor": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", + "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", + "dev": true + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + }, + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "dev": true, + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "cssom": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.4.4.tgz", + "integrity": "sha512-p3pvU7r1MyyqbTk+WbNJIgJjG2VmTIaB10rI93LzVPrmDJKkzKYMtxxyAvQXR/NS6otuzveI7+7BBq3SjBS2mw==", + "dev": true + }, + "cssstyle": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz", + "integrity": "sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A==", + "dev": true, + "requires": { + "cssom": "~0.3.6" + }, + "dependencies": { + "cssom": { + "version": "0.3.8", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", + "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", + "dev": true + } + } + }, + "dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "data-urls": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-2.0.0.tgz", + "integrity": "sha512-X5eWTSXO/BJmpdIKCRuKUgSCgAN0OwliVK3yPKbwIWU1Tdw5BRajxlzMidvh+gwko9AfQ9zIj52pzF91Q3YAvQ==", + "dev": true, + "requires": { + "abab": "^2.0.3", + "whatwg-mimetype": "^2.3.0", + "whatwg-url": "^8.0.0" + } + }, + "dateformat": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-3.0.3.tgz", + "integrity": "sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q==" + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=" + }, + "decimal.js": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.2.0.tgz", + "integrity": "sha512-vDPw+rDgn3bZe1+F/pyEwb1oMG2XTlRVgAa6B4KccTEpYgF8w6eQllVbQcfIJnZyvzFtFpxnpGtx8dd7DJp/Rw==", + "dev": true + }, + "decode-uri-component": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", + "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", + "dev": true + }, + "decomment": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/decomment/-/decomment-0.9.3.tgz", + "integrity": "sha512-5skH5BfUL3n09RDmMVaHS1QGCiZRnl2nArUwmsE9JRY93Ueh3tihYl5wIrDdAuXnoFhxVis/DmRWREO2c6DG3w==", + "dev": true, + "requires": { + "esprima": "4.0.1" + } + }, + "deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "dev": true + }, + "defaults": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.3.tgz", + "integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", + "dev": true, + "requires": { + "clone": "^1.0.2" + } + }, + "define-property": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", + "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", + "dev": true, + "requires": { + "is-descriptor": "^1.0.2", + "isobject": "^3.0.1" + }, + "dependencies": { + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", + "dev": true + }, + "denque": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/denque/-/denque-1.4.1.tgz", + "integrity": "sha512-OfzPuSZKGcgr96rf1oODnfjqBFmr1DVoc/TrItj3Ohe0Ah1C5WX5Baquw/9U9KovnQ88EqmJbD66rKYUQYN1tQ==" + }, + "dependency-tree": { + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/dependency-tree/-/dependency-tree-7.2.1.tgz", + "integrity": "sha512-nBxnjkqDW4LqAzBazy60V4lE0mAtIQ+oers/GIIvVvGYVdCD9+RNNd4G9jjstyz7ZFVg/j/OiYCvK5MjoVqA2w==", + "dev": true, + "requires": { + "commander": "^2.19.0", + "debug": "^4.1.1", + "filing-cabinet": "^2.5.1", + "precinct": "^6.2.0", + "typescript": "^3.7.5" + }, + "dependencies": { + "commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "typescript": { + "version": "3.9.7", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.7.tgz", + "integrity": "sha512-BLbiRkiBzAwsjut4x/dsibSTB6yWpwT5qWmC2OfuCg3GgVQCSgMs4vEctYPhsaGtd0AeuuHMkjZ2h2WG8MSzRw==", + "dev": true + } + } + }, + "deprecation": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", + "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==" + }, + "detect-newline": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", + "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", + "dev": true + }, + "detective-amd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/detective-amd/-/detective-amd-3.0.0.tgz", + "integrity": "sha512-kOpKHyabdSKF9kj7PqYHLeHPw+TJT8q2u48tZYMkIcas28el1CYeLEJ42Nm+563/Fq060T5WknfwDhdX9+kkBQ==", + "dev": true, + "requires": { + "ast-module-types": "^2.3.1", + "escodegen": "^1.8.0", + "get-amd-module-type": "^3.0.0", + "node-source-walk": "^4.0.0" + } + }, + "detective-cjs": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/detective-cjs/-/detective-cjs-3.1.1.tgz", + "integrity": "sha512-JQtNTBgFY6h8uT6pgph5QpV3IyxDv+z3qPk/FZRDT9TlFfm5dnRtpH39WtQEr1khqsUxVqXzKjZHpdoQvQbllg==", + "dev": true, + "requires": { + "ast-module-types": "^2.4.0", + "node-source-walk": "^4.0.0" + } + }, + "detective-es6": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/detective-es6/-/detective-es6-2.2.0.tgz", + "integrity": "sha512-fSpNY0SLER7/sVgQZ1NxJPwmc9uCTzNgdkQDhAaj8NPYwr7Qji9QBcmbNvtMCnuuOGMuKn3O7jv0An+/WRWJZQ==", + "dev": true, + "requires": { + "node-source-walk": "^4.0.0" + } + }, + "detective-less": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/detective-less/-/detective-less-1.0.2.tgz", + "integrity": "sha512-Rps1xDkEEBSq3kLdsdnHZL1x2S4NGDcbrjmd4q+PykK5aJwDdP5MBgrJw1Xo+kyUHuv3JEzPqxr+Dj9ryeDRTA==", + "dev": true, + "requires": { + "debug": "^4.0.0", + "gonzales-pe": "^4.2.3", + "node-source-walk": "^4.0.0" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "detective-postcss": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/detective-postcss/-/detective-postcss-3.0.1.tgz", + "integrity": "sha512-tfTS2GdpUal5NY0aCqI4dpEy8Xfr88AehYKB0iBIZvo8y2g3UsrcDnrp9PR2FbzoW7xD5Rip3NJW7eCSvtqdUw==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "is-url": "^1.2.4", + "postcss": "^7.0.2", + "postcss-values-parser": "^1.5.0" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "detective-sass": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/detective-sass/-/detective-sass-3.0.1.tgz", + "integrity": "sha512-oSbrBozRjJ+QFF4WJFbjPQKeakoaY1GiR380NPqwdbWYd5wfl5cLWv0l6LsJVqrgWfFN1bjFqSeo32Nxza8Lbw==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "gonzales-pe": "^4.2.3", + "node-source-walk": "^4.0.0" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "detective-scss": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/detective-scss/-/detective-scss-2.0.1.tgz", + "integrity": "sha512-VveyXW4WQE04s05KlJ8K0bG34jtHQVgTc9InspqoQxvnelj/rdgSAy7i2DXAazyQNFKlWSWbS+Ro2DWKFOKTPQ==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "gonzales-pe": "^4.2.3", + "node-source-walk": "^4.0.0" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "detective-stylus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/detective-stylus/-/detective-stylus-1.0.0.tgz", + "integrity": "sha1-UK7n24uruZA4HwEMY/q7pbWOVM0=", + "dev": true + }, + "detective-typescript": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/detective-typescript/-/detective-typescript-5.8.0.tgz", + "integrity": "sha512-SrsUCfCaDTF64QVMHMidRal+kmkbIc5zP8cxxZPsomWx9vuEUjBlSJNhf7/ypE5cLdJJDI4qzKDmyzqQ+iz/xg==", + "dev": true, + "requires": { + "@typescript-eslint/typescript-estree": "^2.29.0", + "ast-module-types": "^2.6.0", + "node-source-walk": "^4.2.0", + "typescript": "^3.8.3" + }, + "dependencies": { + "typescript": { + "version": "3.9.7", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.7.tgz", + "integrity": "sha512-BLbiRkiBzAwsjut4x/dsibSTB6yWpwT5qWmC2OfuCg3GgVQCSgMs4vEctYPhsaGtd0AeuuHMkjZ2h2WG8MSzRw==", + "dev": true + } + } + }, + "diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "dev": true + }, + "diff-sequences": { + "version": "25.2.6", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-25.2.6.tgz", + "integrity": "sha512-Hq8o7+6GaZeoFjtpgvRBUknSXNeJiCx7V9Fr94ZMljNiCr9n9L8H8aJqgWOQiDDGdyn29fRNcDdRVJ5fdyihfg==", + "dev": true + }, + "domexception": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/domexception/-/domexception-2.0.1.tgz", + "integrity": "sha512-yxJ2mFy/sibVQlu5qHjOkf9J3K6zgmCxgJ94u2EdvDOV09H+32LtRswEcUsmUWN72pVLOEnTSRaIVVzVQgS0dg==", + "dev": true, + "requires": { + "webidl-conversions": "^5.0.0" + }, + "dependencies": { + "webidl-conversions": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-5.0.0.tgz", + "integrity": "sha512-VlZwKPCkYKxQgeSbH5EyngOmRp7Ww7I9rQLERETtf5ofd9pGeswWiOtogpEO850jziPRarreGxn5QIiTqpb2wA==", + "dev": true + } + } + }, + "dotenv": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-8.2.0.tgz", + "integrity": "sha512-8sJ78ElpbDJBHNeBzUbUVLsqKdccaa/BXF1uPTw3GrvQTBgrQrtObr2mUrE38vzYd8cEv+m/JBfDLioYcfXoaw==" + }, + "duplexer": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.2.tgz", + "integrity": "sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==" + }, + "ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", + "dev": true, + "requires": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "emittery": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.7.1.tgz", + "integrity": "sha512-d34LN4L6h18Bzz9xpoku2nPwKxCPlPMr3EEKTkoEBi+1/+b0lcRkRJ1UVyyZaKNeqGR3swcGl6s390DNO4YVgQ==", + "dev": true + }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" + }, + "end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "requires": { + "once": "^1.4.0" + } + }, + "enhanced-resolve": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.3.0.tgz", + "integrity": "sha512-3e87LvavsdxyoCfGusJnrZ5G8SLPOFeHSNpZI/ATL9a5leXo2k0w6MKnbqhdBad9qTobSfB20Ld7UmgoNbAZkQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "memory-fs": "^0.5.0", + "tapable": "^1.0.0" + } + }, + "errno": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.7.tgz", + "integrity": "sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg==", + "dev": true, + "requires": { + "prr": "~1.0.1" + } + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "escodegen": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.14.3.tgz", + "integrity": "sha512-qFcX0XJkdg+PB3xjZZG/wKSuT1PnQWx57+TVSjIMmILd2yC/6ByYElPwJnslDsuWuSAp4AwJGumarAAmJch5Kw==", + "dev": true, + "requires": { + "esprima": "^4.0.1", + "estraverse": "^4.2.0", + "esutils": "^2.0.2", + "optionator": "^0.8.1", + "source-map": "~0.6.1" + } + }, + "eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "dev": true + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" + }, + "estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true + }, + "esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true + }, + "exec-sh": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/exec-sh/-/exec-sh-0.3.4.tgz", + "integrity": "sha512-sEFIkc61v75sWeOe72qyrqg2Qg0OuLESziUDk/O/z2qgS15y2gWVFrI6f2Qn/qw/0/NCfCEsmNA4zOjkwEZT1A==", + "dev": true + }, + "execa": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", + "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", + "dev": true, + "requires": { + "cross-spawn": "^6.0.0", + "get-stream": "^4.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + } + }, + "exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", + "dev": true + }, + "expand-brackets": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", + "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", + "dev": true, + "requires": { + "debug": "^2.3.3", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "posix-character-classes": "^0.1.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + } + } + }, + "expect": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/expect/-/expect-26.4.2.tgz", + "integrity": "sha512-IlJ3X52Z0lDHm7gjEp+m76uX46ldH5VpqmU0006vqDju/285twh7zaWMRhs67VpQhBwjjMchk+p5aA0VkERCAA==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "ansi-styles": "^4.0.0", + "jest-get-type": "^26.3.0", + "jest-matcher-utils": "^26.4.2", + "jest-message-util": "^26.3.0", + "jest-regex-util": "^26.0.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "jest-get-type": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-26.3.0.tgz", + "integrity": "sha512-TpfaviN1R2pQWkIihlfEanwOXK0zcxrKEE4MlU6Tn7keoXdN6/3gK/xl0yEh8DOunn5pOVGKf8hB4R9gVh04ig==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "dev": true + }, + "extend-shallow": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", + "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", + "dev": true, + "requires": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + } + } + }, + "extglob": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", + "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", + "dev": true, + "requires": { + "array-unique": "^0.3.2", + "define-property": "^1.0.0", + "expand-brackets": "^2.1.4", + "extend-shallow": "^2.0.1", + "fragment-cache": "^0.2.1", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", + "dev": true + }, + "fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, + "fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "fast-redact": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fast-redact/-/fast-redact-2.0.0.tgz", + "integrity": "sha512-zxpkULI9W9MNTK2sJ3BpPQrTEXFNESd2X6O1tXMFpK/XM0G5c5Rll2EVYZH2TqI3xRGK/VaJ+eEOt7pnENJpeA==" + }, + "fast-safe-stringify": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-1.1.13.tgz", + "integrity": "sha1-oB6c2cnkkXFcmKdaQtXwu9EH/3Y=" + }, + "fb-watchman": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.1.tgz", + "integrity": "sha512-DkPJKQeY6kKwmuMretBhr7G6Vodr7bFwDYTXIkfG1gjvNpaxBTQV3PbXg6bR1c1UP4jPOX0jHUbbHANL9vRjVg==", + "dev": true, + "requires": { + "bser": "2.1.1" + } + }, + "file-exists-dazinatorfork": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/file-exists-dazinatorfork/-/file-exists-dazinatorfork-1.0.2.tgz", + "integrity": "sha512-r70c72ln2YHzQINNfxDp02hAhbGkt1HffZ+Du8oetWDLjDtFja/Lm10lUaSh9e+wD+7VDvPee0b0C9SAy8pWZg==", + "dev": true + }, + "filing-cabinet": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/filing-cabinet/-/filing-cabinet-2.5.1.tgz", + "integrity": "sha512-GWOdObzou2L0HrJUk8MpJa01q0ZOwuTwTssM2+P+ABJWEGlVWd6ueEatANFdin94/3rdkVSdqpH14VqCNqp3RA==", + "dev": true, + "requires": { + "app-module-path": "^2.2.0", + "commander": "^2.13.0", + "debug": "^4.1.1", + "decomment": "^0.9.2", + "enhanced-resolve": "^4.1.0", + "is-relative-path": "^1.0.2", + "module-definition": "^3.0.0", + "module-lookup-amd": "^6.1.0", + "resolve": "^1.11.1", + "resolve-dependency-path": "^2.0.0", + "sass-lookup": "^3.0.0", + "stylus-lookup": "^3.0.1", + "typescript": "^3.0.3" + }, + "dependencies": { + "commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "typescript": { + "version": "3.9.7", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.7.tgz", + "integrity": "sha512-BLbiRkiBzAwsjut4x/dsibSTB6yWpwT5qWmC2OfuCg3GgVQCSgMs4vEctYPhsaGtd0AeuuHMkjZ2h2WG8MSzRw==", + "dev": true + } + } + }, + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "find": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/find/-/find-0.3.0.tgz", + "integrity": "sha512-iSd+O4OEYV/I36Zl8MdYJO0xD82wH528SaCieTVHhclgiYNe9y+yPKSwK+A7/WsmHL1EZ+pYUJBXWTL5qofksw==", + "dev": true, + "requires": { + "traverse-chain": "~0.1.0" + } + }, + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "requires": { + "locate-path": "^3.0.0" + } + }, + "flatstr": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/flatstr/-/flatstr-1.0.12.tgz", + "integrity": "sha512-4zPxDyhCyiN2wIAtSLI6gc82/EjqZc1onI4Mz/l0pWrAlsSfYH/2ZIcU+e3oA2wDwbzIWNKwa23F8rh6+DRWkw==" + }, + "flatten": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/flatten/-/flatten-1.0.3.tgz", + "integrity": "sha512-dVsPA/UwQ8+2uoFe5GHtiBMu48dWLTdsuEd7CKGlZlD78r1TTWBvDuFaFGKCo/ZfEr95Uk56vZoX86OsHkUeIg==", + "dev": true + }, + "for-in": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", + "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", + "dev": true + }, + "forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", + "dev": true + }, + "form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "dev": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + } + }, + "fragment-cache": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", + "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", + "dev": true, + "requires": { + "map-cache": "^0.2.2" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "fsevents": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.3.tgz", + "integrity": "sha512-Auw9a4AxqWpa9GUfj370BMPzzyncfBABW8Mab7BGWBYDj4Isgq+cDKtx0i6u9jcX9pQDnswsaaOTgTmA5pEjuQ==", + "dev": true, + "optional": true + }, + "garnish": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/garnish/-/garnish-5.2.0.tgz", + "integrity": "sha1-vtQ2WTguSxmOM8eTiXvnxwHmVXc=", + "requires": { + "chalk": "^0.5.1", + "minimist": "^1.1.0", + "pad-left": "^2.0.0", + "pad-right": "^0.2.2", + "prettier-bytes": "^1.0.3", + "pretty-ms": "^2.1.0", + "right-now": "^1.0.0", + "split2": "^0.2.1", + "stdout-stream": "^1.4.0", + "url-trim": "^1.0.0" + }, + "dependencies": { + "parse-ms": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-1.0.1.tgz", + "integrity": "sha1-VjRtR0nXjyNDDKDHE4UK75GqNh0=" + }, + "pretty-ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-2.1.0.tgz", + "integrity": "sha1-QlfCVt8/sLRR1q/6qwIYhBJpgdw=", + "requires": { + "is-finite": "^1.0.1", + "parse-ms": "^1.0.0", + "plur": "^1.0.0" + } + } + } + }, + "gensync": { + "version": "1.0.0-beta.1", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.1.tgz", + "integrity": "sha512-r8EC6NO1sngH/zdD9fiRDLdcgnbayXah+mLgManTaIZJqEC1MZstmnox8KpnI2/fxQwrp5OpCOYWLp4rBl4Jcg==", + "dev": true + }, + "get-amd-module-type": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/get-amd-module-type/-/get-amd-module-type-3.0.0.tgz", + "integrity": "sha512-99Q7COuACPfVt18zH9N4VAMyb81S6TUgJm2NgV6ERtkh9VIkAaByZkW530wl3lLN5KTtSrK9jVLxYsoP5hQKsw==", + "dev": true, + "requires": { + "ast-module-types": "^2.3.2", + "node-source-walk": "^4.0.0" + } + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" + }, + "get-own-enumerable-property-symbols": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz", + "integrity": "sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g==", + "dev": true + }, + "get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "dev": true + }, + "get-stream": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", + "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", + "dev": true, + "requires": { + "pump": "^3.0.0" + } + }, + "get-value": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", + "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", + "dev": true + }, + "getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "glob": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true + }, + "gonzales-pe": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/gonzales-pe/-/gonzales-pe-4.3.0.tgz", + "integrity": "sha512-otgSPpUmdWJ43VXyiNgEYE4luzHCL2pz4wQ0OnDluC6Eg4Ko3Vexy/SrSynglw/eR+OhkzmqFCZa/OFa/RgAOQ==", + "dev": true, + "requires": { + "minimist": "^1.2.5" + } + }, + "graceful-fs": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.4.tgz", + "integrity": "sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw==", + "dev": true + }, + "graphviz": { + "version": "0.0.9", + "resolved": "https://registry.npmjs.org/graphviz/-/graphviz-0.0.9.tgz", + "integrity": "sha512-SmoY2pOtcikmMCqCSy2NO1YsRfu9OO0wpTlOYW++giGjfX1a6gax/m1Fo8IdUd0/3H15cTOfR1SMKwohj4LKsg==", + "dev": true, + "requires": { + "temp": "~0.4.0" + } + }, + "growly": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/growly/-/growly-1.3.0.tgz", + "integrity": "sha1-8QdIy+dq+WS3yWyTxrzCivEgwIE=", + "dev": true, + "optional": true + }, + "har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=", + "dev": true + }, + "har-validator": { + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", + "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", + "dev": true, + "requires": { + "ajv": "^6.12.3", + "har-schema": "^2.0.0" + } + }, + "has-ansi": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-0.1.0.tgz", + "integrity": "sha1-hPJlqujA5qiKEtcCKJS3VoiUxi4=", + "requires": { + "ansi-regex": "^0.2.0" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + }, + "has-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", + "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", + "dev": true, + "requires": { + "get-value": "^2.0.6", + "has-values": "^1.0.0", + "isobject": "^3.0.0" + } + }, + "has-values": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", + "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "kind-of": "^4.0.0" + }, + "dependencies": { + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "kind-of": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", + "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "hosted-git-info": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.8.tgz", + "integrity": "sha512-f/wzC2QaWBs7t9IYqB4T3sR1xviIViXJRJTWBlx2Gf3g0Xi5vI7Yy4koXQ1c9OYDGHN9sBy1DQ2AB8fqZBWhUg==", + "dev": true + }, + "html-encoding-sniffer": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-2.0.1.tgz", + "integrity": "sha512-D5JbOMBIR/TVZkubHT+OyT2705QvogUW4IBn6nHd756OwieSF9aDYFj4dv6HHEVGYbHaLETa3WggZYWWMyy3ZQ==", + "dev": true, + "requires": { + "whatwg-encoding": "^1.0.5" + } + }, + "html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true + }, + "http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + } + }, + "human-signals": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-1.1.1.tgz", + "integrity": "sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw==", + "dev": true + }, + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "import-local": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.0.2.tgz", + "integrity": "sha512-vjL3+w0oulAVZ0hBHnxa/Nm5TAurf9YLQJDhqRZyqb+VKGOB6LU8t9H1Nr5CIo16vh9XfJTOoHwU0B71S557gA==", + "dev": true, + "requires": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + } + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true + }, + "indexes-of": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/indexes-of/-/indexes-of-1.0.1.tgz", + "integrity": "sha1-8w9xbI4r00bHtn0985FVZqfAVgc=", + "dev": true + }, + "individual": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/individual/-/individual-3.0.0.tgz", + "integrity": "sha1-58pPhfiVewGHNPKFdQ3CLsL5hi0=" + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "ini": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", + "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", + "dev": true + }, + "invariant": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz", + "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==", + "requires": { + "loose-envify": "^1.0.0" + } + }, + "ip-regex": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-2.1.0.tgz", + "integrity": "sha1-+ni/XS5pE8kRzp+BnuUUa7bYROk=", + "dev": true + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, + "is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "dev": true + }, + "is-ci": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", + "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", + "dev": true, + "requires": { + "ci-info": "^2.0.0" + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^0.1.6", + "is-data-descriptor": "^0.1.4", + "kind-of": "^5.0.0" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "is-docker": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.1.1.tgz", + "integrity": "sha512-ZOoqiXfEwtGknTiuDEy8pN2CfE3TxMHprvNer1mXiqwkOT77Rw3YVrUQ52EqAOU3QAWDQ+bQdx7HJzrv7LS2Hw==", + "dev": true, + "optional": true + }, + "is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", + "dev": true + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true + }, + "is-finite": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.1.0.tgz", + "integrity": "sha512-cdyMtqX/BOqqNBBiKlIVkytNHm49MtMlYyn1zxzvJKWmFMlGzm+ry5BBfYyeY9YmNKbRSo/o7OX9w9ale0wg3w==" + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=" + }, + "is-generator-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", + "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", + "dev": true + }, + "is-glob": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", + "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", + "dev": true, + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-interactive": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", + "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==", + "dev": true + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true + }, + "is-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", + "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", + "dev": true + }, + "is-plain-object": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-4.1.1.tgz", + "integrity": "sha512-5Aw8LLVsDlZsETVMhoMXzqsXwQqr/0vlnBYzIXJbYo2F4yYlhLHs+Ez7Bod7IIQKWkJbJfxrWD7pA1Dw1TKrwA==" + }, + "is-potential-custom-element-name": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.0.tgz", + "integrity": "sha1-DFLlS8yjkbssSUsh6GJtczbG45c=", + "dev": true + }, + "is-regexp": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-regexp/-/is-regexp-1.0.0.tgz", + "integrity": "sha1-/S2INUXEa6xaYz57mgnof6LLUGk=", + "dev": true + }, + "is-relative-path": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-relative-path/-/is-relative-path-1.0.2.tgz", + "integrity": "sha1-CRtGoNZ8HtD+hfH4z93gBrslHUY=", + "dev": true + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", + "dev": true + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", + "dev": true + }, + "is-url": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/is-url/-/is-url-1.2.4.tgz", + "integrity": "sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==", + "dev": true + }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true + }, + "is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "optional": true, + "requires": { + "is-docker": "^2.0.0" + } + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "istanbul-lib-coverage": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.0.0.tgz", + "integrity": "sha512-UiUIqxMgRDET6eR+o5HbfRYP1l0hqkWOs7vNxC/mggutCMUIhWMm8gAHb8tHlyfD3/l6rlgNA5cKdDzEAf6hEg==", + "dev": true + }, + "istanbul-lib-instrument": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-4.0.3.tgz", + "integrity": "sha512-BXgQl9kf4WTCPCCpmFGoJkz/+uhvm7h7PFKUYxh7qarQd3ER33vHG//qaE8eN25l07YqZPpHXU9I09l/RD5aGQ==", + "dev": true, + "requires": { + "@babel/core": "^7.7.5", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.0.0", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", + "dev": true, + "requires": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^3.0.0", + "supports-color": "^7.1.0" + }, + "dependencies": { + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dev": true, + "requires": { + "semver": "^6.0.0" + } + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "istanbul-lib-source-maps": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.0.tgz", + "integrity": "sha512-c16LpFRkR8vQXyHZ5nLpY35JZtzj1PQY1iZmesUbf1FZHbIupcWfjgOXBY9YHkLEQ6puz1u4Dgj6qmU/DisrZg==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + } + }, + "istanbul-reports": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.0.2.tgz", + "integrity": "sha512-9tZvz7AiR3PEDNGiV9vIouQ/EAcqMXFmkcA1CDFTwOB98OZVDL0PH9glHotf5Ugp6GCOTypfzGWI/OqjWNCRUw==", + "dev": true, + "requires": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + } + }, + "jest": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest/-/jest-26.4.2.tgz", + "integrity": "sha512-LLCjPrUh98Ik8CzW8LLVnSCfLaiY+wbK53U7VxnFSX7Q+kWC4noVeDvGWIFw0Amfq1lq2VfGm7YHWSLBV62MJw==", + "dev": true, + "requires": { + "@jest/core": "^26.4.2", + "import-local": "^3.0.2", + "jest-cli": "^26.4.2" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "dev": true, + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "jest-cli": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-26.4.2.tgz", + "integrity": "sha512-zb+lGd/SfrPvoRSC/0LWdaWCnscXc1mGYW//NP4/tmBvRPT3VntZ2jtKUONsRi59zc5JqmsSajA9ewJKFYp8Cw==", + "dev": true, + "requires": { + "@jest/core": "^26.4.2", + "@jest/test-result": "^26.3.0", + "@jest/types": "^26.3.0", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.4", + "import-local": "^3.0.2", + "is-ci": "^2.0.0", + "jest-config": "^26.4.2", + "jest-util": "^26.3.0", + "jest-validate": "^26.4.2", + "prompts": "^2.0.1", + "yargs": "^15.3.1" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "string-width": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + } + }, + "strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.0" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + }, + "wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + } + }, + "yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "dev": true, + "requires": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + } + }, + "yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + } + } + }, + "jest-changed-files": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-26.3.0.tgz", + "integrity": "sha512-1C4R4nijgPltX6fugKxM4oQ18zimS7LqQ+zTTY8lMCMFPrxqBFb7KJH0Z2fRQJvw2Slbaipsqq7s1mgX5Iot+g==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "execa": "^4.0.0", + "throat": "^5.0.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "execa": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.3.tgz", + "integrity": "sha512-WFDXGHckXPWZX19t1kCsXzOpqX9LWYNqn4C+HqZlk/V0imTkzJZqf87ZBhvpHaftERYknpk0fjSylnXVlVgI0A==", + "dev": true, + "requires": { + "cross-spawn": "^7.0.0", + "get-stream": "^5.0.0", + "human-signals": "^1.1.1", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.0", + "onetime": "^5.1.0", + "signal-exit": "^3.0.2", + "strip-final-newline": "^2.0.0" + } + }, + "get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "dev": true, + "requires": { + "pump": "^3.0.0" + } + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "is-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", + "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==", + "dev": true + }, + "npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "requires": { + "path-key": "^3.0.0" + } + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "jest-config": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-26.4.2.tgz", + "integrity": "sha512-QBf7YGLuToiM8PmTnJEdRxyYy3mHWLh24LJZKVdXZ2PNdizSe1B/E8bVm+HYcjbEzGuVXDv/di+EzdO/6Gq80A==", + "dev": true, + "requires": { + "@babel/core": "^7.1.0", + "@jest/test-sequencer": "^26.4.2", + "@jest/types": "^26.3.0", + "babel-jest": "^26.3.0", + "chalk": "^4.0.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.1", + "graceful-fs": "^4.2.4", + "jest-environment-jsdom": "^26.3.0", + "jest-environment-node": "^26.3.0", + "jest-get-type": "^26.3.0", + "jest-jasmine2": "^26.4.2", + "jest-regex-util": "^26.0.0", + "jest-resolve": "^26.4.0", + "jest-util": "^26.3.0", + "jest-validate": "^26.4.2", + "micromatch": "^4.0.2", + "pretty-format": "^26.4.2" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "jest-get-type": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-26.3.0.tgz", + "integrity": "sha512-TpfaviN1R2pQWkIihlfEanwOXK0zcxrKEE4MlU6Tn7keoXdN6/3gK/xl0yEh8DOunn5pOVGKf8hB4R9gVh04ig==", + "dev": true + }, + "pretty-format": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-26.4.2.tgz", + "integrity": "sha512-zK6Gd8zDsEiVydOCGLkoBoZuqv8VTiHyAbKznXe/gaph/DAeZOmit9yMfgIz5adIgAMMs5XfoYSwAX3jcCO1tA==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "ansi-regex": "^5.0.0", + "ansi-styles": "^4.0.0", + "react-is": "^16.12.0" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-diff": { + "version": "25.5.0", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-25.5.0.tgz", + "integrity": "sha512-z1kygetuPiREYdNIumRpAHY6RXiGmp70YHptjdaxTWGmA085W3iCnXNx0DhflK3vwrKmrRWyY1wUpkPMVxMK7A==", + "dev": true, + "requires": { + "chalk": "^3.0.0", + "diff-sequences": "^25.2.6", + "jest-get-type": "^25.2.6", + "pretty-format": "^25.5.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", + "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-docblock": { + "version": "26.0.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-26.0.0.tgz", + "integrity": "sha512-RDZ4Iz3QbtRWycd8bUEPxQsTlYazfYn/h5R65Fc6gOfwozFhoImx+affzky/FFBuqISPTqjXomoIGJVKBWoo0w==", + "dev": true, + "requires": { + "detect-newline": "^3.0.0" + } + }, + "jest-each": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-26.4.2.tgz", + "integrity": "sha512-p15rt8r8cUcRY0Mvo1fpkOGYm7iI8S6ySxgIdfh3oOIv+gHwrHTy5VWCGOecWUhDsit4Nz8avJWdT07WLpbwDA==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "chalk": "^4.0.0", + "jest-get-type": "^26.3.0", + "jest-util": "^26.3.0", + "pretty-format": "^26.4.2" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "jest-get-type": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-26.3.0.tgz", + "integrity": "sha512-TpfaviN1R2pQWkIihlfEanwOXK0zcxrKEE4MlU6Tn7keoXdN6/3gK/xl0yEh8DOunn5pOVGKf8hB4R9gVh04ig==", + "dev": true + }, + "pretty-format": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-26.4.2.tgz", + "integrity": "sha512-zK6Gd8zDsEiVydOCGLkoBoZuqv8VTiHyAbKznXe/gaph/DAeZOmit9yMfgIz5adIgAMMs5XfoYSwAX3jcCO1tA==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "ansi-regex": "^5.0.0", + "ansi-styles": "^4.0.0", + "react-is": "^16.12.0" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-environment-jsdom": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-26.3.0.tgz", + "integrity": "sha512-zra8He2btIMJkAzvLaiZ9QwEPGEetbxqmjEBQwhH3CA+Hhhu0jSiEJxnJMbX28TGUvPLxBt/zyaTLrOPF4yMJA==", + "dev": true, + "requires": { + "@jest/environment": "^26.3.0", + "@jest/fake-timers": "^26.3.0", + "@jest/types": "^26.3.0", + "@types/node": "*", + "jest-mock": "^26.3.0", + "jest-util": "^26.3.0", + "jsdom": "^16.2.2" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-environment-node": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-26.3.0.tgz", + "integrity": "sha512-c9BvYoo+FGcMj5FunbBgtBnbR5qk3uky8PKyRVpSfe2/8+LrNQMiXX53z6q2kY+j15SkjQCOSL/6LHnCPLVHNw==", + "dev": true, + "requires": { + "@jest/environment": "^26.3.0", + "@jest/fake-timers": "^26.3.0", + "@jest/types": "^26.3.0", + "@types/node": "*", + "jest-mock": "^26.3.0", + "jest-util": "^26.3.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-get-type": { + "version": "25.2.6", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-25.2.6.tgz", + "integrity": "sha512-DxjtyzOHjObRM+sM1knti6or+eOgcGU4xVSb2HNP1TqO4ahsT+rqZg+nyqHWJSvWgKC5cG3QjGFBqxLghiF/Ig==", + "dev": true + }, + "jest-haste-map": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-26.3.0.tgz", + "integrity": "sha512-DHWBpTJgJhLLGwE5Z1ZaqLTYqeODQIZpby0zMBsCU9iRFHYyhklYqP4EiG73j5dkbaAdSZhgB938mL51Q5LeZA==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "@types/graceful-fs": "^4.1.2", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "fsevents": "^2.1.2", + "graceful-fs": "^4.2.4", + "jest-regex-util": "^26.0.0", + "jest-serializer": "^26.3.0", + "jest-util": "^26.3.0", + "jest-worker": "^26.3.0", + "micromatch": "^4.0.2", + "sane": "^4.0.3", + "walker": "^1.0.7" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-jasmine2": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-jasmine2/-/jest-jasmine2-26.4.2.tgz", + "integrity": "sha512-z7H4EpCldHN1J8fNgsja58QftxBSL+JcwZmaXIvV9WKIM+x49F4GLHu/+BQh2kzRKHAgaN/E82od+8rTOBPyPA==", + "dev": true, + "requires": { + "@babel/traverse": "^7.1.0", + "@jest/environment": "^26.3.0", + "@jest/source-map": "^26.3.0", + "@jest/test-result": "^26.3.0", + "@jest/types": "^26.3.0", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "expect": "^26.4.2", + "is-generator-fn": "^2.0.0", + "jest-each": "^26.4.2", + "jest-matcher-utils": "^26.4.2", + "jest-message-util": "^26.3.0", + "jest-runtime": "^26.4.2", + "jest-snapshot": "^26.4.2", + "jest-util": "^26.3.0", + "pretty-format": "^26.4.2", + "throat": "^5.0.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "pretty-format": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-26.4.2.tgz", + "integrity": "sha512-zK6Gd8zDsEiVydOCGLkoBoZuqv8VTiHyAbKznXe/gaph/DAeZOmit9yMfgIz5adIgAMMs5XfoYSwAX3jcCO1tA==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "ansi-regex": "^5.0.0", + "ansi-styles": "^4.0.0", + "react-is": "^16.12.0" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-leak-detector": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-26.4.2.tgz", + "integrity": "sha512-akzGcxwxtE+9ZJZRW+M2o+nTNnmQZxrHJxX/HjgDaU5+PLmY1qnQPnMjgADPGCRPhB+Yawe1iij0REe+k/aHoA==", + "dev": true, + "requires": { + "jest-get-type": "^26.3.0", + "pretty-format": "^26.4.2" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "jest-get-type": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-26.3.0.tgz", + "integrity": "sha512-TpfaviN1R2pQWkIihlfEanwOXK0zcxrKEE4MlU6Tn7keoXdN6/3gK/xl0yEh8DOunn5pOVGKf8hB4R9gVh04ig==", + "dev": true + }, + "pretty-format": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-26.4.2.tgz", + "integrity": "sha512-zK6Gd8zDsEiVydOCGLkoBoZuqv8VTiHyAbKznXe/gaph/DAeZOmit9yMfgIz5adIgAMMs5XfoYSwAX3jcCO1tA==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "ansi-regex": "^5.0.0", + "ansi-styles": "^4.0.0", + "react-is": "^16.12.0" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-matcher-utils": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-26.4.2.tgz", + "integrity": "sha512-KcbNqWfWUG24R7tu9WcAOKKdiXiXCbMvQYT6iodZ9k1f7065k0keUOW6XpJMMvah+hTfqkhJhRXmA3r3zMAg0Q==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "jest-diff": "^26.4.2", + "jest-get-type": "^26.3.0", + "pretty-format": "^26.4.2" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "diff-sequences": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-26.3.0.tgz", + "integrity": "sha512-5j5vdRcw3CNctePNYN0Wy2e/JbWT6cAYnXv5OuqPhDpyCGc0uLu2TK0zOCJWNB9kOIfYMSpIulRaDgIi4HJ6Ig==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "jest-diff": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-26.4.2.tgz", + "integrity": "sha512-6T1XQY8U28WH0Z5rGpQ+VqZSZz8EN8rZcBtfvXaOkbwxIEeRre6qnuZQlbY1AJ4MKDxQF8EkrCvK+hL/VkyYLQ==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "diff-sequences": "^26.3.0", + "jest-get-type": "^26.3.0", + "pretty-format": "^26.4.2" + } + }, + "jest-get-type": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-26.3.0.tgz", + "integrity": "sha512-TpfaviN1R2pQWkIihlfEanwOXK0zcxrKEE4MlU6Tn7keoXdN6/3gK/xl0yEh8DOunn5pOVGKf8hB4R9gVh04ig==", + "dev": true + }, + "pretty-format": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-26.4.2.tgz", + "integrity": "sha512-zK6Gd8zDsEiVydOCGLkoBoZuqv8VTiHyAbKznXe/gaph/DAeZOmit9yMfgIz5adIgAMMs5XfoYSwAX3jcCO1tA==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "ansi-regex": "^5.0.0", + "ansi-styles": "^4.0.0", + "react-is": "^16.12.0" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-message-util": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-26.3.0.tgz", + "integrity": "sha512-xIavRYqr4/otGOiLxLZGj3ieMmjcNE73Ui+LdSW/Y790j5acqCsAdDiLIbzHCZMpN07JOENRWX5DcU+OQ+TjTA==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "@jest/types": "^26.3.0", + "@types/stack-utils": "^1.0.1", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.4", + "micromatch": "^4.0.2", + "slash": "^3.0.0", + "stack-utils": "^2.0.2" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-mock": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-26.3.0.tgz", + "integrity": "sha512-PeaRrg8Dc6mnS35gOo/CbZovoDPKAeB1FICZiuagAgGvbWdNNyjQjkOaGUa/3N3JtpQ/Mh9P4A2D4Fv51NnP8Q==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "@types/node": "*" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-pnp-resolver": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz", + "integrity": "sha512-olV41bKSMm8BdnuMsewT4jqlZ8+3TCARAXjZGT9jcoSnrfUnRCqnMoF9XEeoWjbzObpqF9dRhHQj0Xb9QdF6/w==", + "dev": true + }, + "jest-regex-util": { + "version": "26.0.0", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-26.0.0.tgz", + "integrity": "sha512-Gv3ZIs/nA48/Zvjrl34bf+oD76JHiGDUxNOVgUjh3j890sblXryjY4rss71fPtD/njchl6PSE2hIhvyWa1eT0A==", + "dev": true + }, + "jest-resolve": { + "version": "26.4.0", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-26.4.0.tgz", + "integrity": "sha512-bn/JoZTEXRSlEx3+SfgZcJAVuTMOksYq9xe9O6s4Ekg84aKBObEaVXKOEilULRqviSLAYJldnoWV9c07kwtiCg==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.4", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^26.3.0", + "read-pkg-up": "^7.0.1", + "resolve": "^1.17.0", + "slash": "^3.0.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-resolve-dependencies": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-26.4.2.tgz", + "integrity": "sha512-ADHaOwqEcVc71uTfySzSowA/RdxUpCxhxa2FNLiin9vWLB1uLPad3we+JSSROq5+SrL9iYPdZZF8bdKM7XABTQ==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "jest-regex-util": "^26.0.0", + "jest-snapshot": "^26.4.2" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-runner": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-26.4.2.tgz", + "integrity": "sha512-FgjDHeVknDjw1gRAYaoUoShe1K3XUuFMkIaXbdhEys+1O4bEJS8Avmn4lBwoMfL8O5oFTdWYKcf3tEJyyYyk8g==", + "dev": true, + "requires": { + "@jest/console": "^26.3.0", + "@jest/environment": "^26.3.0", + "@jest/test-result": "^26.3.0", + "@jest/types": "^26.3.0", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.7.1", + "exit": "^0.1.2", + "graceful-fs": "^4.2.4", + "jest-config": "^26.4.2", + "jest-docblock": "^26.0.0", + "jest-haste-map": "^26.3.0", + "jest-leak-detector": "^26.4.2", + "jest-message-util": "^26.3.0", + "jest-resolve": "^26.4.0", + "jest-runtime": "^26.4.2", + "jest-util": "^26.3.0", + "jest-worker": "^26.3.0", + "source-map-support": "^0.5.6", + "throat": "^5.0.0" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-runtime": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-26.4.2.tgz", + "integrity": "sha512-4Pe7Uk5a80FnbHwSOk7ojNCJvz3Ks2CNQWT5Z7MJo4tX0jb3V/LThKvD9tKPNVNyeMH98J/nzGlcwc00R2dSHQ==", + "dev": true, + "requires": { + "@jest/console": "^26.3.0", + "@jest/environment": "^26.3.0", + "@jest/fake-timers": "^26.3.0", + "@jest/globals": "^26.4.2", + "@jest/source-map": "^26.3.0", + "@jest/test-result": "^26.3.0", + "@jest/transform": "^26.3.0", + "@jest/types": "^26.3.0", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.4", + "jest-config": "^26.4.2", + "jest-haste-map": "^26.3.0", + "jest-message-util": "^26.3.0", + "jest-mock": "^26.3.0", + "jest-regex-util": "^26.0.0", + "jest-resolve": "^26.4.0", + "jest-snapshot": "^26.4.2", + "jest-util": "^26.3.0", + "jest-validate": "^26.4.2", + "slash": "^3.0.0", + "strip-bom": "^4.0.0", + "yargs": "^15.3.1" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "dev": true, + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "string-width": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + } + }, + "strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.0" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + }, + "wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + } + }, + "yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "dev": true, + "requires": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + } + }, + "yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + } + } + }, + "jest-serializer": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-serializer/-/jest-serializer-26.3.0.tgz", + "integrity": "sha512-IDRBQBLPlKa4flg77fqg0n/pH87tcRKwe8zxOVTWISxGpPHYkRZ1dXKyh04JOja7gppc60+soKVZ791mruVdow==", + "dev": true, + "requires": { + "@types/node": "*", + "graceful-fs": "^4.2.4" + } + }, + "jest-snapshot": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-26.4.2.tgz", + "integrity": "sha512-N6Uub8FccKlf5SBFnL2Ri/xofbaA68Cc3MGjP/NuwgnsvWh+9hLIR/DhrxbSiKXMY9vUW5dI6EW1eHaDHqe9sg==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0", + "@jest/types": "^26.3.0", + "@types/prettier": "^2.0.0", + "chalk": "^4.0.0", + "expect": "^26.4.2", + "graceful-fs": "^4.2.4", + "jest-diff": "^26.4.2", + "jest-get-type": "^26.3.0", + "jest-haste-map": "^26.3.0", + "jest-matcher-utils": "^26.4.2", + "jest-message-util": "^26.3.0", + "jest-resolve": "^26.4.0", + "natural-compare": "^1.4.0", + "pretty-format": "^26.4.2", + "semver": "^7.3.2" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "diff-sequences": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-26.3.0.tgz", + "integrity": "sha512-5j5vdRcw3CNctePNYN0Wy2e/JbWT6cAYnXv5OuqPhDpyCGc0uLu2TK0zOCJWNB9kOIfYMSpIulRaDgIi4HJ6Ig==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "jest-diff": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-26.4.2.tgz", + "integrity": "sha512-6T1XQY8U28WH0Z5rGpQ+VqZSZz8EN8rZcBtfvXaOkbwxIEeRre6qnuZQlbY1AJ4MKDxQF8EkrCvK+hL/VkyYLQ==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "diff-sequences": "^26.3.0", + "jest-get-type": "^26.3.0", + "pretty-format": "^26.4.2" + } + }, + "jest-get-type": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-26.3.0.tgz", + "integrity": "sha512-TpfaviN1R2pQWkIihlfEanwOXK0zcxrKEE4MlU6Tn7keoXdN6/3gK/xl0yEh8DOunn5pOVGKf8hB4R9gVh04ig==", + "dev": true + }, + "pretty-format": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-26.4.2.tgz", + "integrity": "sha512-zK6Gd8zDsEiVydOCGLkoBoZuqv8VTiHyAbKznXe/gaph/DAeZOmit9yMfgIz5adIgAMMs5XfoYSwAX3jcCO1tA==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "ansi-regex": "^5.0.0", + "ansi-styles": "^4.0.0", + "react-is": "^16.12.0" + } + }, + "semver": { + "version": "7.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.2.tgz", + "integrity": "sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-util": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-26.3.0.tgz", + "integrity": "sha512-4zpn6bwV0+AMFN0IYhH/wnzIQzRaYVrz1A8sYnRnj4UXDXbOVtWmlaZkO9mipFqZ13okIfN87aDoJWB7VH6hcw==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "@types/node": "*", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.4", + "is-ci": "^2.0.0", + "micromatch": "^4.0.2" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-validate": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-26.4.2.tgz", + "integrity": "sha512-blft+xDX7XXghfhY0mrsBCYhX365n8K5wNDC4XAcNKqqjEzsRUSXP44m6PL0QJEW2crxQFLLztVnJ4j7oPlQrQ==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "camelcase": "^6.0.0", + "chalk": "^4.0.0", + "jest-get-type": "^26.3.0", + "leven": "^3.1.0", + "pretty-format": "^26.4.2" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "camelcase": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.0.0.tgz", + "integrity": "sha512-8KMDF1Vz2gzOq54ONPJS65IvTUaB1cHJ2DMM7MbPmLZljDH1qpzzLsWdiN9pHh6qvkRVDTi/07+eNGch/oLU4w==", + "dev": true + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "jest-get-type": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-26.3.0.tgz", + "integrity": "sha512-TpfaviN1R2pQWkIihlfEanwOXK0zcxrKEE4MlU6Tn7keoXdN6/3gK/xl0yEh8DOunn5pOVGKf8hB4R9gVh04ig==", + "dev": true + }, + "pretty-format": { + "version": "26.4.2", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-26.4.2.tgz", + "integrity": "sha512-zK6Gd8zDsEiVydOCGLkoBoZuqv8VTiHyAbKznXe/gaph/DAeZOmit9yMfgIz5adIgAMMs5XfoYSwAX3jcCO1tA==", + "dev": true, + "requires": { + "@jest/types": "^26.3.0", + "ansi-regex": "^5.0.0", + "ansi-styles": "^4.0.0", + "react-is": "^16.12.0" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-watcher": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-26.3.0.tgz", + "integrity": "sha512-XnLdKmyCGJ3VoF6G/p5ohbJ04q/vv5aH9ENI+i6BL0uu9WWB6Z7Z2lhQQk0d2AVZcRGp1yW+/TsoToMhBFPRdQ==", + "dev": true, + "requires": { + "@jest/test-result": "^26.3.0", + "@jest/types": "^26.3.0", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "jest-util": "^26.3.0", + "string-length": "^4.0.1" + }, + "dependencies": { + "@jest/types": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.3.0.tgz", + "integrity": "sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^15.0.0", + "chalk": "^4.0.0" + } + }, + "@types/istanbul-reports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/yargs": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", + "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jest-worker": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-26.3.0.tgz", + "integrity": "sha512-Vmpn2F6IASefL+DVBhPzI2J9/GJUsqzomdeN+P+dK8/jKxbh8R3BtFnx3FIta7wYlPU62cpJMJQo4kuOowcMnw==", + "dev": true, + "requires": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^7.0.0" + }, + "dependencies": { + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "jmespath": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/jmespath/-/jmespath-0.15.0.tgz", + "integrity": "sha1-o/Iiqarp+Wb10nx5ZRDigJF2Qhc=" + }, + "joycon": { + "version": "2.2.5", + "resolved": "https://registry.npmjs.org/joycon/-/joycon-2.2.5.tgz", + "integrity": "sha512-YqvUxoOcVPnCp0VU1/56f+iKSdvIRJYPznH22BdXV3xMk75SFXhWeJkZ8C9XxUWt1b5x2X1SxuFygW1U0FmkEQ==" + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "js-yaml": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.0.tgz", + "integrity": "sha512-/4IbIeHcD9VMHFqDR/gQ7EdZdLimOvW2DdcxFjdyyZ9NsbS+ccrXqVWDtab/lRl5AlUqmpBx8EhPaWR+OtY17A==", + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", + "dev": true + }, + "jsdom": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-16.4.0.tgz", + "integrity": "sha512-lYMm3wYdgPhrl7pDcRmvzPhhrGVBeVhPIqeHjzeiHN3DFmD1RBpbExbi8vU7BJdH8VAZYovR8DMt0PNNDM7k8w==", + "dev": true, + "requires": { + "abab": "^2.0.3", + "acorn": "^7.1.1", + "acorn-globals": "^6.0.0", + "cssom": "^0.4.4", + "cssstyle": "^2.2.0", + "data-urls": "^2.0.0", + "decimal.js": "^10.2.0", + "domexception": "^2.0.1", + "escodegen": "^1.14.1", + "html-encoding-sniffer": "^2.0.1", + "is-potential-custom-element-name": "^1.0.0", + "nwsapi": "^2.2.0", + "parse5": "5.1.1", + "request": "^2.88.2", + "request-promise-native": "^1.0.8", + "saxes": "^5.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^3.0.1", + "w3c-hr-time": "^1.0.2", + "w3c-xmlserializer": "^2.0.0", + "webidl-conversions": "^6.1.0", + "whatwg-encoding": "^1.0.5", + "whatwg-mimetype": "^2.3.0", + "whatwg-url": "^8.0.0", + "ws": "^7.2.3", + "xml-name-validator": "^3.0.0" + } + }, + "jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true + }, + "json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true + }, + "json-schema": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", + "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", + "dev": true + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", + "dev": true + }, + "json5": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.3.tgz", + "integrity": "sha512-KXPvOm8K9IJKFM0bmdn8QXh7udDh1g/giieX0NLCaMnb4hEiVFqnop2ImTXCc5e0/oHz3LTqmHGtExn5hfMkOA==", + "dev": true, + "requires": { + "minimist": "^1.2.5" + } + }, + "jsprim": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", + "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "dev": true, + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.2.3", + "verror": "1.10.0" + } + }, + "kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "dev": true + }, + "kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true + }, + "leven": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", + "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", + "dev": true + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + } + }, + "lines-and-columns": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz", + "integrity": "sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA=", + "dev": true + }, + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "lodash": { + "version": "4.17.20", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz", + "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==", + "dev": true + }, + "lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha1-vMbEmkKihA7Zl/Mj6tpezRguC/4=", + "dev": true + }, + "lodash.sortby": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz", + "integrity": "sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=" + }, + "log-symbols": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-3.0.0.tgz", + "integrity": "sha512-dSkNGuI7iG3mfvDzUuYZyvk5dD9ocYCYzNU6CYDE6+Xqd+gwme6Z00NS3dUh8mq/73HaEtT7m6W+yUPtU6BZnQ==", + "dev": true, + "requires": { + "chalk": "^2.4.2" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "requires": { + "js-tokens": "^3.0.0 || ^4.0.0" + } + }, + "madge": { + "version": "3.9.2", + "resolved": "https://registry.npmjs.org/madge/-/madge-3.9.2.tgz", + "integrity": "sha512-6ZvyKinAOOzcRpvpm1iyOuds+LvWIq3o3GmUYAHMJdIpDAgVY3mphxVzeWNo3agIOv0X0T/zbLycXQm9Rn19nA==", + "dev": true, + "requires": { + "chalk": "^4.1.0", + "commander": "^5.1.0", + "commondir": "^1.0.1", + "debug": "^4.0.1", + "dependency-tree": "^7.2.1", + "detective-amd": "^3.0.0", + "detective-cjs": "^3.1.1", + "detective-es6": "^2.1.0", + "detective-less": "^1.0.2", + "detective-postcss": "^3.0.1", + "detective-sass": "^3.0.1", + "detective-scss": "^2.0.1", + "detective-stylus": "^1.0.0", + "detective-typescript": "^5.8.0", + "graphviz": "0.0.9", + "ora": "^4.0.4", + "pify": "^5.0.0", + "pluralize": "^8.0.0", + "precinct": "^6.3.1", + "pretty-ms": "^7.0.0", + "rc": "^1.2.7", + "typescript": "^3.9.5", + "walkdir": "^0.4.1" + }, + "dependencies": { + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "pify": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-5.0.0.tgz", + "integrity": "sha512-eW/gHNMlxdSP6dmG6uJip6FXN0EQBwm2clYYd8Wul42Cwu/DK8HEftzsapcNdYe2MfLiIwZqsDk2RDEsTE79hA==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + }, + "typescript": { + "version": "3.9.7", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.7.tgz", + "integrity": "sha512-BLbiRkiBzAwsjut4x/dsibSTB6yWpwT5qWmC2OfuCg3GgVQCSgMs4vEctYPhsaGtd0AeuuHMkjZ2h2WG8MSzRw==", + "dev": true + } + } + }, + "make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "requires": { + "pify": "^4.0.1", + "semver": "^5.6.0" + }, + "dependencies": { + "pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "dev": true + } + } + }, + "make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true + }, + "makeerror": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.11.tgz", + "integrity": "sha1-4BpckQnyr3lmDk6LlYd5AYT1qWw=", + "dev": true, + "requires": { + "tmpl": "1.0.x" + } + }, + "map-cache": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", + "dev": true + }, + "map-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", + "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", + "dev": true, + "requires": { + "object-visit": "^1.0.0" + } + }, + "memory-fs": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/memory-fs/-/memory-fs-0.5.0.tgz", + "integrity": "sha512-jA0rdU5KoQMC0e6ppoNRtpp6vjFq6+NY7r8hywnC7V+1Xj/MtHwGIbB1QaK/dunyjWteJzmkpd7ooeWg10T7GA==", + "dev": true, + "requires": { + "errno": "^0.1.3", + "readable-stream": "^2.0.1" + } + }, + "memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "optional": true + }, + "merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "micromatch": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz", + "integrity": "sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==", + "dev": true, + "requires": { + "braces": "^3.0.1", + "picomatch": "^2.0.5" + } + }, + "mime-db": { + "version": "1.44.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.44.0.tgz", + "integrity": "sha512-/NOTfLrsPBVeH7YtFPgsVWveuL+4SjjYxaQ1xtM1KMFj7HdxlBlxeyNLzhyJVx7r4rZGJAZ/6lkKCitSc/Nmpg==", + "dev": true + }, + "mime-types": { + "version": "2.1.27", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.27.tgz", + "integrity": "sha512-JIhqnCasI9yD+SsmkquHBxTSEuZdQX5BuQnS2Vc7puQQQ+8yiP5AY5uWhpdv4YL4VM5c6iliiYWPgJ/nJQLp7w==", + "dev": true, + "requires": { + "mime-db": "1.44.0" + } + }, + "mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" + }, + "mixin-deep": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.2.tgz", + "integrity": "sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==", + "dev": true, + "requires": { + "for-in": "^1.0.2", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + } + } + }, + "mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "dev": true + }, + "module-definition": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/module-definition/-/module-definition-3.3.0.tgz", + "integrity": "sha512-HTplA9xwDzH67XJFC1YvZMUElWJD28DV0dUq7lhTs+JKJamUOWA/CcYWSlhW5amJO66uWtY7XdltT+LfX0wIVg==", + "dev": true, + "requires": { + "ast-module-types": "^2.6.0", + "node-source-walk": "^4.0.0" + } + }, + "module-lookup-amd": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/module-lookup-amd/-/module-lookup-amd-6.2.0.tgz", + "integrity": "sha512-uxHCj5Pw9psZiC1znjU2qPsubt6haCSsN9m7xmIdoTciEgfxUkE1vhtDvjHPuOXEZrVJhjKgkmkP+w73rRuelQ==", + "dev": true, + "requires": { + "commander": "^2.8.1", + "debug": "^4.1.0", + "file-exists-dazinatorfork": "^1.0.2", + "find": "^0.3.0", + "requirejs": "^2.3.5", + "requirejs-config-file": "^3.1.1" + }, + "dependencies": { + "commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "mongodb": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.6.1.tgz", + "integrity": "sha512-uH76Zzr5wPptnjEKJRQnwTsomtFOU/kQEU8a9hKHr2M7y9qVk7Q4Pkv0EQVp88742z9+RwvsdTw6dRjDZCNu1g==", + "requires": { + "bl": "^2.2.0", + "bson": "^1.1.4", + "denque": "^1.4.1", + "require_optional": "^1.0.1", + "safe-buffer": "^5.1.2", + "saslprep": "^1.0.0" + } + }, + "mri": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.1.4.tgz", + "integrity": "sha512-6y7IjGPm8AzlvoUrwAaw1tLnUBudaS3752vcd8JtrpGGQn+rXIe63LFVHm/YMwtqAuh+LJPCFdlLYPWM1nYn6w==" + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "dev": true + }, + "nanomatch": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", + "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "fragment-cache": "^0.2.1", + "is-windows": "^1.0.2", + "kind-of": "^6.0.2", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + } + }, + "natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", + "dev": true + }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "dev": true + }, + "node-fetch": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", + "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==" + }, + "node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha1-h6kGXNs1XTGC2PlM4RGIuCXGijs=", + "dev": true + }, + "node-modules-regexp": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-modules-regexp/-/node-modules-regexp-1.0.0.tgz", + "integrity": "sha1-jZ2+KJZKSsVxLpExZCEHxx6Q7EA=", + "dev": true + }, + "node-notifier": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/node-notifier/-/node-notifier-8.0.0.tgz", + "integrity": "sha512-46z7DUmcjoYdaWyXouuFNNfUo6eFa94t23c53c+lG/9Cvauk4a98rAUp9672X5dxGdQmLpPzTxzu8f/OeEPaFA==", + "dev": true, + "optional": true, + "requires": { + "growly": "^1.3.0", + "is-wsl": "^2.2.0", + "semver": "^7.3.2", + "shellwords": "^0.1.1", + "uuid": "^8.3.0", + "which": "^2.0.2" + }, + "dependencies": { + "semver": { + "version": "7.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.2.tgz", + "integrity": "sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ==", + "dev": true, + "optional": true + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "optional": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "node-source-walk": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/node-source-walk/-/node-source-walk-4.2.0.tgz", + "integrity": "sha512-hPs/QMe6zS94f5+jG3kk9E7TNm4P2SulrKiLWMzKszBfNZvL/V6wseHlTd7IvfW0NZWqPtK3+9yYNr+3USGteA==", + "dev": true, + "requires": { + "@babel/parser": "^7.0.0" + } + }, + "normalize-package-data": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "dev": true, + "requires": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true + }, + "npm-run-path": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", + "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", + "dev": true, + "requires": { + "path-key": "^2.0.0" + } + }, + "nwsapi": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.0.tgz", + "integrity": "sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ==", + "dev": true + }, + "oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", + "dev": true + }, + "object-copy": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", + "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", + "dev": true, + "requires": { + "copy-descriptor": "^0.1.0", + "define-property": "^0.2.5", + "kind-of": "^3.0.3" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "object-visit": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", + "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", + "dev": true, + "requires": { + "isobject": "^3.0.0" + } + }, + "object.pick": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "requires": { + "mimic-fn": "^2.1.0" + } + }, + "optionator": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", + "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "dev": true, + "requires": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.6", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "word-wrap": "~1.2.3" + } + }, + "ora": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-4.1.1.tgz", + "integrity": "sha512-sjYP8QyVWBpBZWD6Vr1M/KwknSw6kJOz41tvGMlwWeClHBtYKTbHMki1PsLZnxKpXMPbTKv9b3pjQu3REib96A==", + "dev": true, + "requires": { + "chalk": "^3.0.0", + "cli-cursor": "^3.1.0", + "cli-spinners": "^2.2.0", + "is-interactive": "^1.0.0", + "log-symbols": "^3.0.0", + "mute-stream": "0.0.8", + "strip-ansi": "^6.0.0", + "wcwidth": "^1.0.1" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", + "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.0" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "p-each-series": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/p-each-series/-/p-each-series-2.1.0.tgz", + "integrity": "sha512-ZuRs1miPT4HrjFa+9fRfOFXxGJfORgelKV9f9nNOWw2gl6gVsRaVDOQP0+MI0G0wGKns1Yacsu0GjOFbTK0JFQ==", + "dev": true + }, + "p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", + "dev": true + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==" + }, + "pad-left": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/pad-left/-/pad-left-2.1.0.tgz", + "integrity": "sha1-FuajstRKjhOMsIOMx8tAOk/J6ZQ=", + "requires": { + "repeat-string": "^1.5.4" + } + }, + "pad-right": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/pad-right/-/pad-right-0.2.2.tgz", + "integrity": "sha1-b7ySQEXSRPKiokRQMGDTv8YAl3Q=", + "requires": { + "repeat-string": "^1.5.2" + } + }, + "parse-json": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.1.0.tgz", + "integrity": "sha512-+mi/lmVVNKFNVyLXV31ERiy2CY5E1/F6QtJFEzoChPRwwngMNXRDQ9GJ5WdE2Z2P4AujsOi0/+2qHID68KwfIQ==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + } + }, + "parse-ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-2.1.0.tgz", + "integrity": "sha512-kHt7kzLoS9VBZfUsiKjv43mr91ea+U05EyKkEtqp7vNbHxmaVuEqN7XxeEVnGrMtYOAxGrDElSi96K7EgO1zCA==", + "dev": true + }, + "parse5": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-5.1.1.tgz", + "integrity": "sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug==", + "dev": true + }, + "pascalcase": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", + "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", + "dev": true + }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=" + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true + }, + "path-parse": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", + "dev": true + }, + "performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=", + "dev": true + }, + "picomatch": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", + "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==", + "dev": true + }, + "pino": { + "version": "5.17.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-5.17.0.tgz", + "integrity": "sha512-LqrqmRcJz8etUjyV0ddqB6OTUutCgQULPFg2b4dtijRHUsucaAdBgSUW58vY6RFSX+NT8963F+q0tM6lNwGShA==", + "requires": { + "fast-redact": "^2.0.0", + "fast-safe-stringify": "^2.0.7", + "flatstr": "^1.0.12", + "pino-std-serializers": "^2.4.2", + "quick-format-unescaped": "^3.0.3", + "sonic-boom": "^0.7.5" + }, + "dependencies": { + "fast-safe-stringify": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.0.7.tgz", + "integrity": "sha512-Utm6CdzT+6xsDk2m8S6uL8VHxNwI6Jub+e9NYTcAms28T84pTa25GJQV9j0CY0N1rM8hK4x6grpF2BQf+2qwVA==" + } + } + }, + "pino-pretty": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-3.6.1.tgz", + "integrity": "sha512-S3bal+Yd313OEaPijbf7V+jPxVaTaRO5RQX8S/Mwdtb/8+JOgo1KolDeJTfMDTU2/k6+MHvEbxv+T1ZRfGlnjA==", + "requires": { + "@hapi/bourne": "^1.3.2", + "args": "^5.0.1", + "chalk": "^2.4.2", + "dateformat": "^3.0.3", + "fast-safe-stringify": "^2.0.7", + "jmespath": "^0.15.0", + "joycon": "^2.2.5", + "pump": "^3.0.0", + "readable-stream": "^3.4.0", + "split2": "^3.1.1", + "strip-json-comments": "^3.0.1" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "fast-safe-stringify": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.0.7.tgz", + "integrity": "sha512-Utm6CdzT+6xsDk2m8S6uL8VHxNwI6Jub+e9NYTcAms28T84pTa25GJQV9j0CY0N1rM8hK4x6grpF2BQf+2qwVA==" + }, + "readable-stream": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + }, + "split2": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/split2/-/split2-3.2.2.tgz", + "integrity": "sha512-9NThjpgZnifTkJpzTZ7Eue85S49QwpNhZTq6GRJwObb6jnLFNGB7Qm73V5HewTROPyxD0C29xqmaI68bQtV+hg==", + "requires": { + "readable-stream": "^3.0.0" + } + }, + "strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==" + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "pino-std-serializers": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-2.5.0.tgz", + "integrity": "sha512-wXqbqSrIhE58TdrxxlfLwU9eDhrzppQDvGhBEr1gYbzzM4KKo3Y63gSjiDXRKLVS2UOXdPNR2v+KnQgNrs+xUg==" + }, + "pirates": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.1.tgz", + "integrity": "sha512-WuNqLTbMI3tmfef2TKxlQmAiLHKtFhlsCZnPIpuv2Ow0RDVO8lfy1Opf4NUzlMXLjPl+Men7AuVdX6TA+s+uGA==", + "dev": true, + "requires": { + "node-modules-regexp": "^1.0.0" + } + }, + "pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "requires": { + "find-up": "^4.0.0" + }, + "dependencies": { + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + } + } + }, + "plur": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/plur/-/plur-1.0.0.tgz", + "integrity": "sha1-24XGgU9eXlo7Se/CjWBP7GKXUVY=" + }, + "pluralize": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz", + "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==", + "dev": true + }, + "posix-character-classes": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", + "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", + "dev": true + }, + "postcss": { + "version": "7.0.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-7.0.32.tgz", + "integrity": "sha512-03eXong5NLnNCD05xscnGKGDZ98CyzoqPSMjOe6SuoQY7Z2hIj0Ld1g/O/UQRuOle2aRtiIRDg9tDcTGAkLfKw==", + "dev": true, + "requires": { + "chalk": "^2.4.2", + "source-map": "^0.6.1", + "supports-color": "^6.1.0" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "dependencies": { + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "postcss-values-parser": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/postcss-values-parser/-/postcss-values-parser-1.5.0.tgz", + "integrity": "sha512-3M3p+2gMp0AH3da530TlX8kiO1nxdTnc3C6vr8dMxRLIlh8UYkz0/wcwptSXjhtx2Fr0TySI7a+BHDQ8NL7LaQ==", + "dev": true, + "requires": { + "flatten": "^1.0.2", + "indexes-of": "^1.0.1", + "uniq": "^1.0.1" + } + }, + "precinct": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/precinct/-/precinct-6.3.1.tgz", + "integrity": "sha512-JAwyLCgTylWminoD7V0VJwMElWmwrVSR6r9HaPWCoswkB4iFzX7aNtO7VBfAVPy+NhmjKb8IF8UmlWJXzUkOIQ==", + "dev": true, + "requires": { + "commander": "^2.20.3", + "debug": "^4.1.1", + "detective-amd": "^3.0.0", + "detective-cjs": "^3.1.1", + "detective-es6": "^2.1.0", + "detective-less": "^1.0.2", + "detective-postcss": "^3.0.1", + "detective-sass": "^3.0.1", + "detective-scss": "^2.0.1", + "detective-stylus": "^1.0.0", + "detective-typescript": "^5.8.0", + "module-definition": "^3.3.0", + "node-source-walk": "^4.2.0" + }, + "dependencies": { + "commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "prettier-bytes": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/prettier-bytes/-/prettier-bytes-1.0.4.tgz", + "integrity": "sha1-mUsCqkb2mcULYle1+qp/4lV+YtY=" + }, + "pretty-format": { + "version": "25.5.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-25.5.0.tgz", + "integrity": "sha512-kbo/kq2LQ/A/is0PQwsEHM7Ca6//bGPPvU6UnsdDRSKTWxT/ru/xb88v4BJf6a69H+uTytOEsTusT9ksd/1iWQ==", + "dev": true, + "requires": { + "@jest/types": "^25.5.0", + "ansi-regex": "^5.0.0", + "ansi-styles": "^4.0.0", + "react-is": "^16.12.0" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + } + } + }, + "pretty-ms": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-7.0.0.tgz", + "integrity": "sha512-J3aPWiC5e9ZeZFuSeBraGxSkGMOvulSWsxDByOcbD1Pr75YL3LSNIKIb52WXbCLE1sS5s4inBBbryjF4Y05Ceg==", + "dev": true, + "requires": { + "parse-ms": "^2.1.0" + } + }, + "process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, + "prompts": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.3.2.tgz", + "integrity": "sha512-Q06uKs2CkNYVID0VqwfAl9mipo99zkBv/n2JtWY89Yxa3ZabWSrs0e2KTudKVa3peLUvYXMefDqIleLPVUBZMA==", + "dev": true, + "requires": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.4" + } + }, + "prr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", + "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=", + "dev": true + }, + "psl": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", + "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", + "dev": true + }, + "pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true + }, + "qs": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", + "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==", + "dev": true + }, + "quick-format-unescaped": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-3.0.3.tgz", + "integrity": "sha512-dy1yjycmn9blucmJLXOfZDx1ikZJUi6E8bBZLnhPG5gBrVhHXx2xVyqqgKBubVNEXmx51dBACMHpoMQK/N/AXQ==" + }, + "rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dev": true, + "requires": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + } + }, + "react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "dev": true + }, + "read-pkg": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-5.2.0.tgz", + "integrity": "sha512-Ug69mNOpfvKDAc2Q8DRpMjjzdtrnv9HcSMX+4VsZxD1aZ6ZzrIE7rlzXBtWTyhULSMKg076AW6WR5iZpD0JiOg==", + "dev": true, + "requires": { + "@types/normalize-package-data": "^2.4.0", + "normalize-package-data": "^2.5.0", + "parse-json": "^5.0.0", + "type-fest": "^0.6.0" + }, + "dependencies": { + "type-fest": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.6.0.tgz", + "integrity": "sha512-q+MB8nYR1KDLrgr4G5yemftpMC7/QLqVndBmEEdqzmNj5dcFOO4Oo8qlwZE3ULT3+Zim1F8Kq4cBnikNhlCMlg==", + "dev": true + } + } + }, + "read-pkg-up": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-7.0.1.tgz", + "integrity": "sha512-zK0TB7Xd6JpCLmlLmufqykGE+/TlOePD6qKClNW7hHDKFh/J7/7gCWGR7joEQEW1bKq3a3yUZSObOoWLFQ4ohg==", + "dev": true, + "requires": { + "find-up": "^4.1.0", + "read-pkg": "^5.2.0", + "type-fest": "^0.8.1" + }, + "dependencies": { + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + } + } + }, + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + }, + "dependencies": { + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + } + } + }, + "regex-not": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", + "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.2", + "safe-regex": "^1.1.0" + } + }, + "remove-trailing-separator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", + "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", + "dev": true + }, + "repeat-element": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.3.tgz", + "integrity": "sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g==", + "dev": true + }, + "repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=" + }, + "request": { + "version": "2.88.2", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", + "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", + "dev": true, + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.3", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.5.0", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + }, + "dependencies": { + "tough-cookie": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", + "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "dev": true, + "requires": { + "psl": "^1.1.28", + "punycode": "^2.1.1" + } + }, + "uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "dev": true + } + } + }, + "request-promise-core": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/request-promise-core/-/request-promise-core-1.1.4.tgz", + "integrity": "sha512-TTbAfBBRdWD7aNNOoVOBH4pN/KigV6LyapYNNlAPA8JwbovRti1E88m3sYAwsLi5ryhPKsE9APwnjFTgdUjTpw==", + "dev": true, + "requires": { + "lodash": "^4.17.19" + } + }, + "request-promise-native": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/request-promise-native/-/request-promise-native-1.0.9.tgz", + "integrity": "sha512-wcW+sIUiWnKgNY0dqCpOZkUbF/I+YPi+f09JZIDa39Ec+q82CpSYniDp+ISgTTbKmnpJWASeJBPZmoxH84wt3g==", + "dev": true, + "requires": { + "request-promise-core": "1.1.4", + "stealthy-require": "^1.1.1", + "tough-cookie": "^2.3.3" + }, + "dependencies": { + "tough-cookie": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", + "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "dev": true, + "requires": { + "psl": "^1.1.28", + "punycode": "^2.1.1" + } + } + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=" + }, + "require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" + }, + "require_optional": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", + "integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", + "requires": { + "resolve-from": "^2.0.0", + "semver": "^5.1.0" + } + }, + "requirejs": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/requirejs/-/requirejs-2.3.6.tgz", + "integrity": "sha512-ipEzlWQe6RK3jkzikgCupiTbTvm4S0/CAU5GlgptkN5SO6F3u0UD0K18wy6ErDqiCyP4J4YYe1HuAShvsxePLg==", + "dev": true + }, + "requirejs-config-file": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/requirejs-config-file/-/requirejs-config-file-3.1.2.tgz", + "integrity": "sha512-sdLWywcDuNz7EIOhenSbRfT4YF84nItDv90coN2htbokjmU2QeyQuSBZILQUKNksepl8UPVU+hgYySFaDxbJPQ==", + "dev": true, + "requires": { + "esprima": "^4.0.0", + "make-dir": "^2.1.0", + "stringify-object": "^3.2.1" + } + }, + "resolve": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz", + "integrity": "sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w==", + "dev": true, + "requires": { + "path-parse": "^1.0.6" + } + }, + "resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dev": true, + "requires": { + "resolve-from": "^5.0.0" + }, + "dependencies": { + "resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true + } + } + }, + "resolve-dependency-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve-dependency-path/-/resolve-dependency-path-2.0.0.tgz", + "integrity": "sha512-DIgu+0Dv+6v2XwRaNWnumKu7GPufBBOr5I1gRPJHkvghrfCGOooJODFvgFimX/KRxk9j0whD2MnKHzM1jYvk9w==", + "dev": true + }, + "resolve-from": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", + "integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=" + }, + "resolve-url": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", + "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", + "dev": true + }, + "restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "requires": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + } + }, + "ret": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", + "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", + "dev": true + }, + "right-now": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/right-now/-/right-now-1.0.0.tgz", + "integrity": "sha1-bolgne69fc2vja7Mmuo5z1haCRg=" + }, + "rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "rsvp": { + "version": "4.8.5", + "resolved": "https://registry.npmjs.org/rsvp/-/rsvp-4.8.5.tgz", + "integrity": "sha512-nfMOlASu9OnRJo1mbEk2cz0D56a1MBNrJ7orjRZQG10XDyuvwksKbuXNp6qa+kbn839HwjwhBzhFmdsaEAfauA==", + "dev": true + }, + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" + }, + "safe-regex": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", + "dev": true, + "requires": { + "ret": "~0.1.10" + } + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "sane": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/sane/-/sane-4.1.0.tgz", + "integrity": "sha512-hhbzAgTIX8O7SHfp2c8/kREfEn4qO/9q8C9beyY6+tvZ87EpoZ3i1RIEvp27YBswnNbY9mWd6paKVmKbAgLfZA==", + "dev": true, + "requires": { + "@cnakazawa/watch": "^1.0.3", + "anymatch": "^2.0.0", + "capture-exit": "^2.0.0", + "exec-sh": "^0.3.2", + "execa": "^1.0.0", + "fb-watchman": "^2.0.0", + "micromatch": "^3.1.4", + "minimist": "^1.1.1", + "walker": "~1.0.5" + }, + "dependencies": { + "anymatch": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz", + "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==", + "dev": true, + "requires": { + "micromatch": "^3.1.4", + "normalize-path": "^2.1.1" + } + }, + "braces": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", + "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", + "dev": true, + "requires": { + "arr-flatten": "^1.1.0", + "array-unique": "^0.3.2", + "extend-shallow": "^2.0.1", + "fill-range": "^4.0.0", + "isobject": "^3.0.1", + "repeat-element": "^1.1.2", + "snapdragon": "^0.8.1", + "snapdragon-node": "^2.0.1", + "split-string": "^3.0.2", + "to-regex": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "fill-range": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", + "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-number": "^3.0.0", + "repeat-string": "^1.6.1", + "to-regex-range": "^2.1.0" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "micromatch": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", + "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "braces": "^2.3.1", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "extglob": "^2.0.4", + "fragment-cache": "^0.2.1", + "kind-of": "^6.0.2", + "nanomatch": "^1.2.9", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.2" + } + }, + "normalize-path": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "dev": true, + "requires": { + "remove-trailing-separator": "^1.0.1" + } + }, + "to-regex-range": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", + "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "repeat-string": "^1.6.1" + } + } + } + }, + "saslprep": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", + "integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", + "optional": true, + "requires": { + "sparse-bitfield": "^3.0.3" + } + }, + "sass-lookup": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/sass-lookup/-/sass-lookup-3.0.0.tgz", + "integrity": "sha512-TTsus8CfFRn1N44bvdEai1no6PqdmDiQUiqW5DlpmtT+tYnIt1tXtDIph5KA1efC+LmioJXSnCtUVpcK9gaKIg==", + "dev": true, + "requires": { + "commander": "^2.16.0" + }, + "dependencies": { + "commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + } + } + }, + "saxes": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz", + "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==", + "dev": true, + "requires": { + "xmlchars": "^2.2.0" + } + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, + "set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=" + }, + "set-value": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz", + "integrity": "sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.3", + "split-string": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + } + } + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true + }, + "shellwords": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/shellwords/-/shellwords-0.1.1.tgz", + "integrity": "sha512-vFwSUfQvqybiICwZY5+DAWIPLKsWO31Q91JSKl3UYv+K5c2QRPzn0qzec6QPu1Qc9eHYItiP3NdJqNVqetYAww==", + "dev": true, + "optional": true + }, + "signal-exit": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", + "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==", + "dev": true + }, + "sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true + }, + "slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true + }, + "snapdragon": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", + "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", + "dev": true, + "requires": { + "base": "^0.11.1", + "debug": "^2.2.0", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "map-cache": "^0.2.2", + "source-map": "^0.5.6", + "source-map-resolve": "^0.5.0", + "use": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + } + } + }, + "snapdragon-node": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", + "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", + "dev": true, + "requires": { + "define-property": "^1.0.0", + "isobject": "^3.0.0", + "snapdragon-util": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "snapdragon-util": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", + "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", + "dev": true, + "requires": { + "kind-of": "^3.2.0" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "sonic-boom": { + "version": "0.7.7", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-0.7.7.tgz", + "integrity": "sha512-Ei5YOo5J64GKClHIL/5evJPgASXFVpfVYbJV9PILZQytTK6/LCwHvsZJW2Ig4p9FMC2OrBrMnXKgRN/OEoAWfg==", + "requires": { + "atomic-sleep": "^1.0.0", + "flatstr": "^1.0.12" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "source-map-resolve": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.3.tgz", + "integrity": "sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw==", + "dev": true, + "requires": { + "atob": "^2.1.2", + "decode-uri-component": "^0.2.0", + "resolve-url": "^0.2.1", + "source-map-url": "^0.4.0", + "urix": "^0.1.0" + } + }, + "source-map-support": { + "version": "0.5.19", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz", + "integrity": "sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "source-map-url": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", + "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=", + "dev": true + }, + "sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", + "optional": true, + "requires": { + "memory-pager": "^1.0.2" + } + }, + "spdx-correct": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.1.tgz", + "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", + "dev": true, + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", + "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==", + "dev": true + }, + "spdx-expression-parse": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "dev": true, + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.5.tgz", + "integrity": "sha512-J+FWzZoynJEXGphVIS+XEh3kFSjZX/1i9gFBaWQcB+/tmpe2qUsSBABpcxqxnAxFdiUFEgAX1bjYGQvIZmoz9Q==", + "dev": true + }, + "split": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/split/-/split-0.3.3.tgz", + "integrity": "sha1-zQ7qXmOiEd//frDwkcQTPi0N0o8=", + "requires": { + "through": "2" + } + }, + "split-string": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", + "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.0" + } + }, + "split2": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/split2/-/split2-0.2.1.tgz", + "integrity": "sha1-At2smtwD7Au3jBKC7Aecpuha6QA=", + "requires": { + "through2": "~0.6.1" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=" + }, + "readable-stream": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", + "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=" + }, + "through2": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-0.6.5.tgz", + "integrity": "sha1-QaucZ7KdVyCQcUEOHXp6lozTrUg=", + "requires": { + "readable-stream": ">=1.0.33-1 <1.1.0-0", + "xtend": ">=4.0.0 <4.1.0-0" + } + }, + "xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==" + } + } + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" + }, + "sshpk": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", + "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", + "dev": true, + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + } + }, + "stack-utils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.2.tgz", + "integrity": "sha512-0H7QK2ECz3fyZMzQ8rH0j2ykpfbnd20BFtfg/SqVC2+sCTtcw0aDTGB7dk+de4U4uUeuz6nOtJcrkFFLG1B0Rg==", + "dev": true, + "requires": { + "escape-string-regexp": "^2.0.0" + }, + "dependencies": { + "escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true + } + } + }, + "static-extend": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", + "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", + "dev": true, + "requires": { + "define-property": "^0.2.5", + "object-copy": "^0.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "stdout-stream": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/stdout-stream/-/stdout-stream-1.4.1.tgz", + "integrity": "sha512-j4emi03KXqJWcIeF8eIXkjMFN1Cmb8gUlDYGeBALLPo5qdyTfA9bOtl8m33lRoC+vFMkP3gl0WsDr6+gzxbbTA==", + "requires": { + "readable-stream": "^2.0.1" + } + }, + "stealthy-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/stealthy-require/-/stealthy-require-1.1.1.tgz", + "integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=", + "dev": true + }, + "stream-combiner": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/stream-combiner/-/stream-combiner-0.2.2.tgz", + "integrity": "sha1-rsjLrBd7Vrb0+kec7YwZEs7lKFg=", + "requires": { + "duplexer": "~0.1.1", + "through": "~2.3.4" + } + }, + "string-length": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.1.tgz", + "integrity": "sha512-PKyXUd0LK0ePjSOnWn34V2uD6acUWev9uy0Ft05k0E8xRW+SKcA0F7eMr7h5xlzfn+4O3N+55rduYyet3Jk+jw==", + "dev": true, + "requires": { + "char-regex": "^1.0.2", + "strip-ansi": "^6.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.0" + } + } + } + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "requires": { + "ansi-regex": "^4.1.0" + } + } + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "requires": { + "safe-buffer": "~5.1.0" + }, + "dependencies": { + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + } + } + }, + "stringify-object": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-3.3.0.tgz", + "integrity": "sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==", + "dev": true, + "requires": { + "get-own-enumerable-property-symbols": "^3.0.0", + "is-obj": "^1.0.1", + "is-regexp": "^1.0.0" + } + }, + "strip-ansi": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-0.3.0.tgz", + "integrity": "sha1-JfSOoiynkYfzF0pNuHWTR7sSYiA=", + "requires": { + "ansi-regex": "^0.2.1" + } + }, + "strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "dev": true + }, + "strip-eof": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", + "dev": true + }, + "strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true + }, + "strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", + "dev": true + }, + "stylus-lookup": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/stylus-lookup/-/stylus-lookup-3.0.2.tgz", + "integrity": "sha512-oEQGHSjg/AMaWlKe7gqsnYzan8DLcGIHe0dUaFkucZZ14z4zjENRlQMCHT4FNsiWnJf17YN9OvrCfCoi7VvOyg==", + "dev": true, + "requires": { + "commander": "^2.8.1", + "debug": "^4.1.0" + }, + "dependencies": { + "commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "supports-color": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-0.2.0.tgz", + "integrity": "sha1-2S3iaU6z9nMjlz1649i1W0wiGQo=" + }, + "supports-hyperlinks": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-2.1.0.tgz", + "integrity": "sha512-zoE5/e+dnEijk6ASB6/qrK+oYdm2do1hjoLWrqUC/8WEIW1gbxFcKuBof7sW8ArN6e+AYvsE8HBGiVRWL/F5CA==", + "dev": true, + "requires": { + "has-flag": "^4.0.0", + "supports-color": "^7.0.0" + }, + "dependencies": { + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true + }, + "tapable": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-1.1.3.tgz", + "integrity": "sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA==", + "dev": true + }, + "temp": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/temp/-/temp-0.4.0.tgz", + "integrity": "sha1-ZxrWPVe+D+nXKUZks/xABjZnimA=", + "dev": true + }, + "terminal-link": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/terminal-link/-/terminal-link-2.1.1.tgz", + "integrity": "sha512-un0FmiRUQNr5PJqy9kP7c40F5BOfpGlYTrxonDChEZB7pzZxRNp/bt+ymiy9/npwXya9KH99nJ/GXFIiUkYGFQ==", + "dev": true, + "requires": { + "ansi-escapes": "^4.2.1", + "supports-hyperlinks": "^2.0.0" + } + }, + "test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dev": true, + "requires": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + } + }, + "throat": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/throat/-/throat-5.0.0.tgz", + "integrity": "sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA==", + "dev": true + }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=" + }, + "through2": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/through2/-/through2-0.5.1.tgz", + "integrity": "sha1-390BLrnHAOIyP9M084rGIqs3Lac=", + "requires": { + "readable-stream": "~1.0.17", + "xtend": "~3.0.0" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=" + }, + "readable-stream": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", + "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=" + } + } + }, + "tkt": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tkt/-/tkt-2.0.0.tgz", + "integrity": "sha512-ExJIsw7poRNmU+BGYBL1v7fX2WOpxy8Ugd196NlhRgyl5shwLjFDZBCLtW+vg0p7pOT5GtvSUEGjKyzO4CyRTg==", + "requires": { + "@types/invariant": "^2.2.30", + "@types/node": "^12.6.1", + "@types/pino": "^5.8.8", + "@types/yargs": "^13.0.0", + "bistre": "^1.0.1", + "bole": "^3.0.2", + "bson-objectid": "^1.3.0", + "garnish": "^5.2.0", + "invariant": "^2.2.4", + "pino": "^5.13.0", + "pino-pretty": "^3.2.0", + "yargs": "^13.2.4" + }, + "dependencies": { + "@types/node": { + "version": "12.12.56", + "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.56.tgz", + "integrity": "sha512-8OdIupOIZtmObR13fvGyTvpcuzKmMugkATeVcfNwCjGtHxhjEKmOvLqXwR8U9VOtNnZ4EXaSfNiLVsPinaCXkQ==" + } + } + }, + "tmpl": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.4.tgz", + "integrity": "sha1-I2QN17QtAEM5ERQIIOXPRA5SHdE=", + "dev": true + }, + "to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", + "dev": true + }, + "to-object-path": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", + "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "to-regex": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.2.tgz", + "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", + "dev": true, + "requires": { + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "regex-not": "^1.0.2", + "safe-regex": "^1.1.0" + } + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "requires": { + "is-number": "^7.0.0" + } + }, + "tough-cookie": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-3.0.1.tgz", + "integrity": "sha512-yQyJ0u4pZsv9D4clxO69OEjLWYw+jbgspjTue4lTQZLfV0c5l1VmK2y1JK8E9ahdpltPOaAThPcp5nKPUgSnsg==", + "dev": true, + "requires": { + "ip-regex": "^2.1.0", + "psl": "^1.1.28", + "punycode": "^2.1.1" + } + }, + "tr46": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-2.0.2.tgz", + "integrity": "sha512-3n1qG+/5kg+jrbTzwAykB5yRYtQCTqOGKq5U5PE3b0a1/mzo6snDhjGS0zJVJunO0NrT3Dg1MLy5TjWP/UJppg==", + "dev": true, + "requires": { + "punycode": "^2.1.1" + } + }, + "traverse-chain": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/traverse-chain/-/traverse-chain-0.1.0.tgz", + "integrity": "sha1-YdvC1Ttp/2CRoSoWj9fUMxB+QPE=", + "dev": true + }, + "ts-jest": { + "version": "26.3.0", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-26.3.0.tgz", + "integrity": "sha512-Jq2uKfx6bPd9+JDpZNMBJMdMQUC3sJ08acISj8NXlVgR2d5OqslEHOR2KHMgwymu8h50+lKIm0m0xj/ioYdW2Q==", + "dev": true, + "requires": { + "@types/jest": "26.x", + "bs-logger": "0.x", + "buffer-from": "1.x", + "fast-json-stable-stringify": "2.x", + "jest-util": "26.x", + "json5": "2.x", + "lodash.memoize": "4.x", + "make-error": "1.x", + "mkdirp": "1.x", + "semver": "7.x", + "yargs-parser": "18.x" + }, + "dependencies": { + "semver": { + "version": "7.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.2.tgz", + "integrity": "sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ==", + "dev": true + }, + "yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + } + } + }, + "ts-node": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-9.0.0.tgz", + "integrity": "sha512-/TqB4SnererCDR/vb4S/QvSZvzQMJN8daAslg7MeaiHvD8rDZsSfXmNeNumyZZzMned72Xoq/isQljYSt8Ynfg==", + "dev": true, + "requires": { + "arg": "^4.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "source-map-support": "^0.5.17", + "yn": "3.1.1" + } + }, + "tslib": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.13.0.tgz", + "integrity": "sha512-i/6DQjL8Xf3be4K/E6Wgpekn5Qasl1usyw++dAA35Ue5orEn65VIxOA+YvNNl9HV3qv70T7CNwjODHZrLwvd1Q==", + "dev": true + }, + "tsutils": { + "version": "3.17.1", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.17.1.tgz", + "integrity": "sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g==", + "dev": true, + "requires": { + "tslib": "^1.8.1" + } + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "dev": true, + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2" + } + }, + "type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true + }, + "type-fest": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", + "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", + "dev": true + }, + "typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "dev": true, + "requires": { + "is-typedarray": "^1.0.0" + } + }, + "typescript": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.0.2.tgz", + "integrity": "sha512-e4ERvRV2wb+rRZ/IQeb3jm2VxBsirQLpQhdxplZ2MEzGvDkkMmPglecnNDfSUBivMjP93vRbngYYDQqQ/78bcQ==", + "dev": true + }, + "union-value": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz", + "integrity": "sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "get-value": "^2.0.6", + "is-extendable": "^0.1.1", + "set-value": "^2.0.1" + } + }, + "uniq": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/uniq/-/uniq-1.0.1.tgz", + "integrity": "sha1-sxxa6CVIRKOoKBVBzisEuGWnNP8=", + "dev": true + }, + "universal-user-agent": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", + "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" + }, + "unset-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", + "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", + "dev": true, + "requires": { + "has-value": "^0.3.1", + "isobject": "^3.0.0" + }, + "dependencies": { + "has-value": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", + "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", + "dev": true, + "requires": { + "get-value": "^2.0.3", + "has-values": "^0.1.4", + "isobject": "^2.0.0" + }, + "dependencies": { + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "requires": { + "isarray": "1.0.0" + } + } + } + }, + "has-values": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", + "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", + "dev": true + } + } + }, + "uri-js": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.0.tgz", + "integrity": "sha512-B0yRTzYdUCCn9n+F4+Gh4yIDtMQcaJsmYBDsTSG8g/OejKBodLQ2IHfN3bM7jUsRXndopT7OIXWdYqc1fjmV6g==", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, + "urix": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", + "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", + "dev": true + }, + "url-trim": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/url-trim/-/url-trim-1.0.0.tgz", + "integrity": "sha1-QAV+LxZLiOXaynJp2kfm0d2Detw=" + }, + "use": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", + "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==", + "dev": true + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + }, + "uuid": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.0.tgz", + "integrity": "sha512-fX6Z5o4m6XsXBdli9g7DtWgAx+osMsRRZFKma1mIUsLCz6vRvv+pz5VNbyu9UEDzpMWulZfvpgb/cmDXVulYFQ==", + "dev": true, + "optional": true + }, + "v8-to-istanbul": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-5.0.1.tgz", + "integrity": "sha512-mbDNjuDajqYe3TXFk5qxcQy8L1msXNE37WTlLoqqpBfRsimbNcrlhQlDPntmECEcUvdC+AQ8CyMMf6EUx1r74Q==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.1", + "convert-source-map": "^1.6.0", + "source-map": "^0.7.3" + }, + "dependencies": { + "source-map": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", + "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", + "dev": true + } + } + }, + "validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "w3c-hr-time": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz", + "integrity": "sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ==", + "dev": true, + "requires": { + "browser-process-hrtime": "^1.0.0" + } + }, + "w3c-xmlserializer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-2.0.0.tgz", + "integrity": "sha512-4tzD0mF8iSiMiNs30BiLO3EpfGLZUT2MSX/G+o7ZywDzliWQ3OPtTZ0PTC3B3ca1UAf4cJMHB+2Bf56EriJuRA==", + "dev": true, + "requires": { + "xml-name-validator": "^3.0.0" + } + }, + "walkdir": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/walkdir/-/walkdir-0.4.1.tgz", + "integrity": "sha512-3eBwRyEln6E1MSzcxcVpQIhRG8Q1jLvEqRmCZqS3dsfXEDR/AhOF4d+jHg1qvDCpYaVRZjENPQyrVxAkQqxPgQ==", + "dev": true + }, + "walker": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.7.tgz", + "integrity": "sha1-L3+bj9ENZ3JisYqITijRlhjgKPs=", + "dev": true, + "requires": { + "makeerror": "1.0.x" + } + }, + "wcwidth": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", + "integrity": "sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g=", + "dev": true, + "requires": { + "defaults": "^1.0.3" + } + }, + "webidl-conversions": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-6.1.0.tgz", + "integrity": "sha512-qBIvFLGiBpLjfwmYAaHPXsn+ho5xZnGvyGvsarywGNc8VyQJUMHJ8OBKGGrPER0okBeMDaan4mNBlgBROxuI8w==", + "dev": true + }, + "whatwg-encoding": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz", + "integrity": "sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw==", + "dev": true, + "requires": { + "iconv-lite": "0.4.24" + } + }, + "whatwg-mimetype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz", + "integrity": "sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==", + "dev": true + }, + "whatwg-url": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-8.2.2.tgz", + "integrity": "sha512-PcVnO6NiewhkmzV0qn7A+UZ9Xx4maNTI+O+TShmfE4pqjoCMwUMjkvoNhNHPTvgR7QH9Xt3R13iHuWy2sToFxQ==", + "dev": true, + "requires": { + "lodash.sortby": "^4.7.0", + "tr46": "^2.0.2", + "webidl-conversions": "^6.1.0" + } + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=" + }, + "word-wrap": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", + "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", + "dev": true + }, + "wrap-ansi": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "requires": { + "ansi-styles": "^3.2.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "requires": { + "ansi-regex": "^4.1.0" + } + } + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "write-file-atomic": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", + "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", + "dev": true, + "requires": { + "imurmurhash": "^0.1.4", + "is-typedarray": "^1.0.0", + "signal-exit": "^3.0.2", + "typedarray-to-buffer": "^3.1.5" + } + }, + "ws": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.3.1.tgz", + "integrity": "sha512-D3RuNkynyHmEJIpD2qrgVkc9DQ23OrN/moAwZX4L8DfvszsJxpjQuUq3LMx6HoYji9fbIOBY18XWBsAux1ZZUA==", + "dev": true + }, + "xml-name-validator": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-3.0.0.tgz", + "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", + "dev": true + }, + "xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true + }, + "xtend": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-3.0.0.tgz", + "integrity": "sha1-XM50B7r2Qsunvs2laBEcST9ZZlo=" + }, + "y18n": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", + "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==" + }, + "yargs": { + "version": "13.3.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.2.tgz", + "integrity": "sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==", + "requires": { + "cliui": "^5.0.0", + "find-up": "^3.0.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^3.0.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^13.1.2" + } + }, + "yargs-parser": { + "version": "13.1.2", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.2.tgz", + "integrity": "sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==", + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + }, + "yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true + } + } +} diff --git a/package.json b/package.json index cf796ae..8d4b035 100644 --- a/package.json +++ b/package.json @@ -1,26 +1,33 @@ { "devDependencies": { - "@types/jest": "^24.0.15", + "@types/jest": "^26.0.13", "@types/lodash.sortby": "^4.7.6", - "@types/mongodb": "^3.1.28", - "@types/node": "^12.0.12", - "jest": "^24.8.0", - "madge": "^3.4.4", - "ts-jest": "^24.0.2", - "ts-node": "^8.3.0", - "typescript": "^3.5.2" + "@types/mongodb": "^3.5.27", + "@types/node": "^14.6.4", + "jest": "^26.4.2", + "madge": "^3.9.2", + "ts-jest": "^26.3.0", + "ts-node": "^9.0.0", + "typescript": "^4.0.2" }, + "main": "lib/CLIEntrypoint.js", "scripts": { "test": "jest", "build": "rm -rf lib && tsc", - "dev": "ts-node -r dotenv/config src/CLIEntrypoint.ts" + "package": "ncc build --source-map --license licenses.txt", + "dev": "ts-node -r dotenv/config src/CLIEntrypoint.ts", + "all": "npm run build && npm run package && npm test" }, "dependencies": { - "@octokit/graphql": "^3.0.1", - "@octokit/rest": "^16.28.4", - "dotenv": "^8.0.0", + "@actions/core": "^1.2.5", + "@actions/github": "^4.0.0", + "@octokit/graphql": "^4.5.4", + "@octokit/rest": "^18.0.5", + "@vercel/ncc": "^0.24.0", + "dotenv": "^8.2.0", + "js-yaml": "^3.14.0", "lodash.sortby": "^4.7.0", - "mongodb": "^3.2.7", - "tkt": "1.1.0" + "mongodb": "^3.6.1", + "tkt": "2.0.0" } } diff --git a/src/CodeRepository.ts b/src/CodeRepository.ts index ac90cef..bd31477 100644 --- a/src/CodeRepository.ts +++ b/src/CodeRepository.ts @@ -1,3 +1,5 @@ +import { getInput } from '@actions/core' +import { context } from '@actions/github' import { existsSync, readFileSync } from 'fs' import { logger, invariant } from 'tkt' import { execSync, execFileSync } from 'child_process' @@ -45,7 +47,7 @@ export const repoContext = { type CodeRepositoryState = { files: IFile[] - saveChanges(commitMessage: string): Promise + saveChanges(commitMessage: string, commitBody: string): Promise } export async function scanCodeRepository(): Promise { @@ -63,7 +65,7 @@ export async function scanCodeRepository(): Promise { } return { files, - async saveChanges(commitMessage) { + async saveChanges(commitMessage, commitBody) { const changedFiles = files.filter(file => file.contents.changed) log.info('Files changed: %s', changedFiles.length) if (changedFiles.length === 0) { @@ -72,17 +74,24 @@ export async function scanCodeRepository(): Promise { for (const file of changedFiles) { file.save() } + log.info(`"${commitMessage}"`, `"${commitBody}"`) + + process.env.GIT_COMMITTER_NAME = 'todo-actions' + process.env.GIT_AUTHOR_NAME = 'todo-actions' + process.env.GIT_AUTHOR_EMAIL = 'todo-actions[bot]@users.noreply.github.com' + execFileSync('git', ['add', ...changedFiles.map(file => file.fileName)]) - execFileSync('git', ['commit', '-m', commitMessage], { - stdio: 'inherit', + execFileSync('git', ['commit', '-m', commitMessage, '-m', commitBody], { + stdio: 'inherit' }) if (!process.env.GITHUB_TOKEN) { throw `Maybe you forgot to enable the GITHUB_TOKEN secret?` } - execSync( - 'git push "https://x-access-token:$GITHUB_TOKEN@github.com/$GITHUB_REPOSITORY.git" HEAD:"$GITHUB_REF"', - { stdio: 'inherit' }, - ) + + const ref = getInput('branch') || "$GITHUB_REF" + execSync(`git push "https://x-access-token:${process.env.GITHUB_TOKEN}@github.com/${context.repo.owner}/${context.repo.repo}.git" HEAD:${ref}`,{ + stdio: 'inherit' + }) }, } } diff --git a/src/TaskInformationGenerator.ts b/src/TaskInformationGenerator.ts index fe5563a..b4b1b31 100644 --- a/src/TaskInformationGenerator.ts +++ b/src/TaskInformationGenerator.ts @@ -1,6 +1,9 @@ +import { getInput } from '@actions/core' import { ITodo, ITaskState } from './types' import { createHash } from 'crypto' import { repoContext } from './CodeRepository' +import { invariant, logger } from 'tkt' +import { graphql } from '@octokit/graphql' type TaskInformation = { state: ITaskState @@ -8,18 +11,67 @@ type TaskInformation = { body: string } -export function generateTaskInformationFromTodo(todo: ITodo): TaskInformation { +const owner = repoContext.repositoryOwner +const repo = repoContext.repositoryName +const branch = getInput('branch') || repoContext.defaultBranch + +const log = logger('TaskInformationGenerator') + +let cache = 'meh' +async function fetchCommit(): Promise { + if (cache !== 'meh') { + return cache + } + + // Some random check to filter out tests + if (!('GITHUB_TOKEN' in process.env)) { + log.info(`Skipping local testing env`) + return '' + } + + cache = '' + + log.info('Fetching commit') + try { + const { repository: { ref: { target: { history: { nodes: [{ oid }] } } } } } = await graphql(`{ + repository(name: "${repo}", owner: "${owner}") { + ref(qualifiedName: "${branch}") { + target { + ... on Commit { + history(first: 1) { + nodes { + oid + } + } + } + } + } + } + }`, { + headers: { + authorization: `token ${process.env.GITHUB_TOKEN || + invariant(false, 'Required GITHUB_TOKEN variable.')}`, + }, + }) + + cache = oid + } catch (err) { + console.error(err) + } + + return cache +} + +export async function generateTaskInformationFromTodo(todo: ITodo): Promise { const title = todo.title const file = todo.file.fileName // TODO [#31]: Also link to end line in addition to just the starting line. // This requires changing `IFile` interface and `File` class to also keep track of where the TODO comment ends. const line = todo.startLine - const owner = repoContext.repositoryOwner - const repo = repoContext.repositoryName - const defaultBranch = repoContext.defaultBranch + const commit = await fetchCommit() - const url = `https://github.com/${owner}/${repo}/blob/${defaultBranch}/${file}#L${line}` + const url = `https://github.com/${owner}/${repo}/blob/${commit || branch}/${file}#L${line}` const link = `[${file}:${line}](${url})` const body = [ todo.body, @@ -27,7 +79,7 @@ export function generateTaskInformationFromTodo(todo: ITodo): TaskInformation { '---', `_` + `This issue has been automatically created by [todo-actions](https://github.com/apps/todo-actions) based on a TODO comment found in ${link}. ` + - `It will automatically be closed when the TODO comment is removed from the default branch (${defaultBranch}).` + + `It will automatically be closed when the TODO comment is removed from ${branch}.` + `_`, ].join('\n') diff --git a/src/TaskManagementSystem.ts b/src/TaskManagementSystem.ts index 8a553c4..193564d 100644 --- a/src/TaskManagementSystem.ts +++ b/src/TaskManagementSystem.ts @@ -1,4 +1,6 @@ import { invariant, logger } from 'tkt' +import { Octokit } from '@octokit/rest' +import { graphql } from '@octokit/graphql' import * as CodeRepository from './CodeRepository' @@ -12,13 +14,7 @@ type TaskInformation = { export async function createTask( information: TaskInformation, ): Promise { - const graphql = require('@octokit/graphql').defaults({ - headers: { - authorization: `token ${process.env.GITHUB_TOKEN || - invariant(false, 'Required GITHUB_TOKEN variable.')}`, - }, - }) - const result = await graphql( + const { createIssue } = await graphql( ` mutation CreateIssue($input: CreateIssueInput!) { createIssue(input: $input) { @@ -34,11 +30,14 @@ export async function createTask( title: information.title, body: information.body, }, + headers: { + authorization: `token ${process.env.GITHUB_TOKEN || invariant(false, 'Required GITHUB_TOKEN variable.')}`, + }, }, ) - log.debug('Create issue result:', result) - return result.createIssue.issue.number - ? `#${result.createIssue.issue.number}` + log.debug('Create issue result:', createIssue) + return createIssue.issue.number + ? `#${createIssue.issue.number}` : invariant( false, 'Failed to get issue number out of createIssue API call.', @@ -46,7 +45,6 @@ export async function createTask( } export async function completeTask(taskReference: string): Promise { - const Octokit = (await import('@octokit/rest')).default const octokit = new Octokit({ auth: `token ${process.env.GITHUB_TOKEN || invariant(false, 'Required GITHUB_TOKEN variable.')}`, @@ -64,7 +62,6 @@ export async function updateTask( taskReference: string, information: TaskInformation, ): Promise { - const Octokit = (await import('@octokit/rest')).default const octokit = new Octokit({ auth: `token ${process.env.GITHUB_TOKEN || invariant(false, 'Required GITHUB_TOKEN variable.')}`, diff --git a/src/TaskUpdater.ts b/src/TaskUpdater.ts index 13a51ce..6ff5ff7 100644 --- a/src/TaskUpdater.ts +++ b/src/TaskUpdater.ts @@ -62,7 +62,7 @@ export async function reconcileTasks(todos: ITodo[]) { title, body, state, - } = TaskInformationGenerator.generateTaskInformationFromTodo(todo) + } = await TaskInformationGenerator.generateTaskInformationFromTodo(todo) if (task.state.hash !== state.hash) { log.info( 'Hash for "%s" changed: "%s" => "%s" -- must update task.', @@ -114,7 +114,7 @@ export async function resolveTask( title, body, state, - } = TaskInformationGenerator.generateTaskInformationFromTodo(todo) + } = await TaskInformationGenerator.generateTaskInformationFromTodo(todo) const taskReference = await TaskManagementSystem.createTask({ title, body }) taskCreationLock.finish(taskReference, state) return taskReference diff --git a/src/TodoActionsMain.ts b/src/TodoActionsMain.ts index 23546ed..94c3e7a 100644 --- a/src/TodoActionsMain.ts +++ b/src/TodoActionsMain.ts @@ -1,3 +1,4 @@ +import { getInput } from '@actions/core' import { invariant } from 'tkt' import { logger } from 'tkt' import { ObjectId } from 'bson' @@ -30,7 +31,7 @@ export async function runMain() { for (const todo of todosWithoutReference) { todo.reference = `$${new ObjectId().toHexString()}` } - await saveChanges('Collect TODO comments') + await saveChanges(getInput('collect_commit_msg'), getInput('collect_commit_body')) } // Every TODO must have a reference by now. @@ -45,7 +46,11 @@ export async function runMain() { // Update all the tasks according to the TODO state. const associated = await TaskUpdater.ensureAllTodosAreAssociated(todoComments) - await saveChanges('Update TODO references: ' + associated.join(', ')) + + await saveChanges( + getInput('reference_commit_msg').replace(/%s/, associated.join(', ')), + getInput('reference_commit_body').replace(/%s/, associated.join(', ')) + ) // Reconcile all tasks await TaskUpdater.reconcileTasks(todoComments) diff --git a/src/__mocks__/CodeRepository.ts b/src/__mocks__/CodeRepository.ts index 464f793..ae3aa48 100644 --- a/src/__mocks__/CodeRepository.ts +++ b/src/__mocks__/CodeRepository.ts @@ -13,11 +13,11 @@ export const scanCodeRepository: Real['scanCodeRepository'] = async () => { const files = [...mockWorld.files.values()] return { files: files, - async saveChanges(commitMessage) { + async saveChanges(commitMessage, commitBody) { if (!files.some(f => f.contents.changed)) return files.forEach(f => f.save()) mockWorld.commits.push({ - message: commitMessage, + message: `${commitMessage}\n\n${commitBody}`, files: new Map(files.map(f => [f.fileName, f.contents.toString()])), }) }, diff --git a/tsconfig.json b/tsconfig.json index 5ea6dfe..5a9c72c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,12 +1,11 @@ { "compilerOptions": { "module": "commonjs", - "target": "es2016", + "target": "es6", "strict": true, "skipLibCheck": true, "rootDir": "src", "outDir": "lib", - "sourceMap": true, "esModuleInterop": true }, "include": ["src"], diff --git a/yarn.lock b/yarn.lock index c3f36ce..b58d3ea 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,351 +2,614 @@ # yarn lockfile v1 -"@babel/code-frame@^7.0.0": - version "7.0.0" - resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.0.0.tgz#06e2ab19bdb535385559aabb5ba59729482800f8" - integrity sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA== - dependencies: - "@babel/highlight" "^7.0.0" +"@actions/core@^1.2.5": + version "1.2.5" + resolved "https://registry.yarnpkg.com/@actions/core/-/core-1.2.5.tgz#fa57bf8c07a38191e243beb9ea9d8368c1cb02c8" + integrity sha512-mwpoNjHSWWh0IiALdDEQi3tru124JKn0yVNziIBzTME8QRv7thwoghVuT1jBRjFvdtoHsqD58IRHy1nf86paRg== -"@babel/core@^7.1.0": - version "7.5.0" - resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.5.0.tgz#6ed6a2881ad48a732c5433096d96d1b0ee5eb734" - integrity sha512-6Isr4X98pwXqHvtigw71CKgmhL1etZjPs5A67jL/w0TkLM9eqmFR40YrnJvEc1WnMZFsskjsmid8bHZyxKEAnw== +"@actions/github@^4.0.0": + version "4.0.0" + resolved "https://registry.yarnpkg.com/@actions/github/-/github-4.0.0.tgz#d520483151a2bf5d2dc9cd0f20f9ac3a2e458816" + integrity sha512-Ej/Y2E+VV6sR9X7pWL5F3VgEWrABaT292DRqRU6R4hnQjPtC/zD3nagxVdXWiRQvYDh8kHXo7IDmG42eJ/dOMA== dependencies: - "@babel/code-frame" "^7.0.0" - "@babel/generator" "^7.5.0" - "@babel/helpers" "^7.5.0" - "@babel/parser" "^7.5.0" - "@babel/template" "^7.4.4" - "@babel/traverse" "^7.5.0" - "@babel/types" "^7.5.0" - convert-source-map "^1.1.0" + "@actions/http-client" "^1.0.8" + "@octokit/core" "^3.0.0" + "@octokit/plugin-paginate-rest" "^2.2.3" + "@octokit/plugin-rest-endpoint-methods" "^4.0.0" + +"@actions/http-client@^1.0.8": + version "1.0.8" + resolved "https://registry.yarnpkg.com/@actions/http-client/-/http-client-1.0.8.tgz#8bd76e8eca89dc8bcf619aa128eba85f7a39af45" + integrity sha512-G4JjJ6f9Hb3Zvejj+ewLLKLf99ZC+9v+yCxoYf9vSyH+WkzPLB2LuUtRMGNkooMqdugGBFStIKXOuvH1W+EctA== + dependencies: + tunnel "0.0.6" + +"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.10.4.tgz#168da1a36e90da68ae8d49c0f1b48c7c6249213a" + integrity sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg== + dependencies: + "@babel/highlight" "^7.10.4" + +"@babel/core@^7.1.0", "@babel/core@^7.7.5": + version "7.11.6" + resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.11.6.tgz#3a9455dc7387ff1bac45770650bc13ba04a15651" + integrity sha512-Wpcv03AGnmkgm6uS6k8iwhIwTrcP0m17TL1n1sy7qD0qelDu4XNeW0dN0mHfa+Gei211yDaLoEe/VlbXQzM4Bg== + dependencies: + "@babel/code-frame" "^7.10.4" + "@babel/generator" "^7.11.6" + "@babel/helper-module-transforms" "^7.11.0" + "@babel/helpers" "^7.10.4" + "@babel/parser" "^7.11.5" + "@babel/template" "^7.10.4" + "@babel/traverse" "^7.11.5" + "@babel/types" "^7.11.5" + convert-source-map "^1.7.0" debug "^4.1.0" - json5 "^2.1.0" - lodash "^4.17.11" + gensync "^1.0.0-beta.1" + json5 "^2.1.2" + lodash "^4.17.19" resolve "^1.3.2" semver "^5.4.1" source-map "^0.5.0" -"@babel/generator@^7.4.0", "@babel/generator@^7.5.0": - version "7.5.0" - resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.5.0.tgz#f20e4b7a91750ee8b63656073d843d2a736dca4a" - integrity sha512-1TTVrt7J9rcG5PMjvO7VEG3FrEoEJNHxumRq66GemPmzboLWtIjjcJgk8rokuAS7IiRSpgVSu5Vb9lc99iJkOA== +"@babel/generator@^7.11.5", "@babel/generator@^7.11.6": + version "7.11.6" + resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.11.6.tgz#b868900f81b163b4d464ea24545c61cbac4dc620" + integrity sha512-DWtQ1PV3r+cLbySoHrwn9RWEgKMBLLma4OBQloPRyDYvc5msJM9kvTLo1YnlJd1P/ZuKbdli3ijr5q3FvAF3uA== dependencies: - "@babel/types" "^7.5.0" + "@babel/types" "^7.11.5" jsesc "^2.5.1" - lodash "^4.17.11" source-map "^0.5.0" - trim-right "^1.0.1" -"@babel/helper-function-name@^7.1.0": - version "7.1.0" - resolved "https://registry.yarnpkg.com/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz#a0ceb01685f73355d4360c1247f582bfafc8ff53" - integrity sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw== +"@babel/helper-function-name@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/helper-function-name/-/helper-function-name-7.10.4.tgz#d2d3b20c59ad8c47112fa7d2a94bc09d5ef82f1a" + integrity sha512-YdaSyz1n8gY44EmN7x44zBn9zQ1Ry2Y+3GTA+3vH6Mizke1Vw0aWDM66FOYEPw8//qKkmqOckrGgTYa+6sceqQ== + dependencies: + "@babel/helper-get-function-arity" "^7.10.4" + "@babel/template" "^7.10.4" + "@babel/types" "^7.10.4" + +"@babel/helper-get-function-arity@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/helper-get-function-arity/-/helper-get-function-arity-7.10.4.tgz#98c1cbea0e2332f33f9a4661b8ce1505b2c19ba2" + integrity sha512-EkN3YDB+SRDgiIUnNgcmiD361ti+AVbL3f3Henf6dqqUyr5dMsorno0lJWJuLhDhkI5sYEpgj6y9kB8AOU1I2A== + dependencies: + "@babel/types" "^7.10.4" + +"@babel/helper-member-expression-to-functions@^7.10.4": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.11.0.tgz#ae69c83d84ee82f4b42f96e2a09410935a8f26df" + integrity sha512-JbFlKHFntRV5qKw3YC0CvQnDZ4XMwgzzBbld7Ly4Mj4cbFy3KywcR8NtNctRToMWJOVvLINJv525Gd6wwVEx/Q== + dependencies: + "@babel/types" "^7.11.0" + +"@babel/helper-module-imports@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/helper-module-imports/-/helper-module-imports-7.10.4.tgz#4c5c54be04bd31670a7382797d75b9fa2e5b5620" + integrity sha512-nEQJHqYavI217oD9+s5MUBzk6x1IlvoS9WTPfgG43CbMEeStE0v+r+TucWdx8KFGowPGvyOkDT9+7DHedIDnVw== + dependencies: + "@babel/types" "^7.10.4" + +"@babel/helper-module-transforms@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.11.0.tgz#b16f250229e47211abdd84b34b64737c2ab2d359" + integrity sha512-02EVu8COMuTRO1TAzdMtpBPbe6aQ1w/8fePD2YgQmxZU4gpNWaL9gK3Jp7dxlkUlUCJOTaSeA+Hrm1BRQwqIhg== + dependencies: + "@babel/helper-module-imports" "^7.10.4" + "@babel/helper-replace-supers" "^7.10.4" + "@babel/helper-simple-access" "^7.10.4" + "@babel/helper-split-export-declaration" "^7.11.0" + "@babel/template" "^7.10.4" + "@babel/types" "^7.11.0" + lodash "^4.17.19" + +"@babel/helper-optimise-call-expression@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.10.4.tgz#50dc96413d594f995a77905905b05893cd779673" + integrity sha512-n3UGKY4VXwXThEiKrgRAoVPBMqeoPgHVqiHZOanAJCG9nQUL2pLRQirUzl0ioKclHGpGqRgIOkgcIJaIWLpygg== + dependencies: + "@babel/types" "^7.10.4" + +"@babel/helper-plugin-utils@^7.0.0", "@babel/helper-plugin-utils@^7.10.4", "@babel/helper-plugin-utils@^7.8.0": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.10.4.tgz#2f75a831269d4f677de49986dff59927533cf375" + integrity sha512-O4KCvQA6lLiMU9l2eawBPMf1xPP8xPfB3iEQw150hOVTqj/rfXz0ThTb4HEzqQfs2Bmo5Ay8BzxfzVtBrr9dVg== + +"@babel/helper-replace-supers@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/helper-replace-supers/-/helper-replace-supers-7.10.4.tgz#d585cd9388ea06e6031e4cd44b6713cbead9e6cf" + integrity sha512-sPxZfFXocEymYTdVK1UNmFPBN+Hv5mJkLPsYWwGBxZAxaWfFu+xqp7b6qWD0yjNuNL2VKc6L5M18tOXUP7NU0A== + dependencies: + "@babel/helper-member-expression-to-functions" "^7.10.4" + "@babel/helper-optimise-call-expression" "^7.10.4" + "@babel/traverse" "^7.10.4" + "@babel/types" "^7.10.4" + +"@babel/helper-simple-access@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/helper-simple-access/-/helper-simple-access-7.10.4.tgz#0f5ccda2945277a2a7a2d3a821e15395edcf3461" + integrity sha512-0fMy72ej/VEvF8ULmX6yb5MtHG4uH4Dbd6I/aHDb/JVg0bbivwt9Wg+h3uMvX+QSFtwr5MeItvazbrc4jtRAXw== + dependencies: + "@babel/template" "^7.10.4" + "@babel/types" "^7.10.4" + +"@babel/helper-split-export-declaration@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.11.0.tgz#f8a491244acf6a676158ac42072911ba83ad099f" + integrity sha512-74Vejvp6mHkGE+m+k5vHY93FX2cAtrw1zXrZXRlG4l410Nm9PxfEiVTn1PjDPV5SnmieiueY4AFg2xqhNFuuZg== + dependencies: + "@babel/types" "^7.11.0" + +"@babel/helper-validator-identifier@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.10.4.tgz#a78c7a7251e01f616512d31b10adcf52ada5e0d2" + integrity sha512-3U9y+43hz7ZM+rzG24Qe2mufW5KhvFg/NhnNph+i9mgCtdTCtMJuI1TMkrIUiK7Ix4PYlRF9I5dhqaLYA/ADXw== + +"@babel/helpers@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.10.4.tgz#2abeb0d721aff7c0a97376b9e1f6f65d7a475044" + integrity sha512-L2gX/XeUONeEbI78dXSrJzGdz4GQ+ZTA/aazfUsFaWjSe95kiCuOZ5HsXvkiw3iwF+mFHSRUfJU8t6YavocdXA== + dependencies: + "@babel/template" "^7.10.4" + "@babel/traverse" "^7.10.4" + "@babel/types" "^7.10.4" + +"@babel/highlight@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.10.4.tgz#7d1bdfd65753538fabe6c38596cdb76d9ac60143" + integrity sha512-i6rgnR/YgPEQzZZnbTHHuZdlE8qyoBNalD6F+q4vAFlcMEcqmkoG+mPqJYJCo63qPf74+Y1UZsl3l6f7/RIkmA== + dependencies: + "@babel/helper-validator-identifier" "^7.10.4" + chalk "^2.0.0" + js-tokens "^4.0.0" + +"@babel/parser@^7.0.0", "@babel/parser@^7.1.0", "@babel/parser@^7.10.4", "@babel/parser@^7.11.5": + version "7.11.5" + resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.11.5.tgz#c7ff6303df71080ec7a4f5b8c003c58f1cf51037" + integrity sha512-X9rD8qqm695vgmeaQ4fvz/o3+Wk4ZzQvSHkDBgpYKxpD4qTAUm88ZKtHkVqIOsYFFbIQ6wQYhC6q7pjqVK0E0Q== + +"@babel/plugin-syntax-async-generators@^7.8.4": + version "7.8.4" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz#a983fb1aeb2ec3f6ed042a210f640e90e786fe0d" + integrity sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw== dependencies: - "@babel/helper-get-function-arity" "^7.0.0" - "@babel/template" "^7.1.0" - "@babel/types" "^7.0.0" + "@babel/helper-plugin-utils" "^7.8.0" -"@babel/helper-get-function-arity@^7.0.0": - version "7.0.0" - resolved "https://registry.yarnpkg.com/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz#83572d4320e2a4657263734113c42868b64e49c3" - integrity sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ== +"@babel/plugin-syntax-bigint@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz#4c9a6f669f5d0cdf1b90a1671e9a146be5300cea" + integrity sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg== dependencies: - "@babel/types" "^7.0.0" + "@babel/helper-plugin-utils" "^7.8.0" -"@babel/helper-plugin-utils@^7.0.0": - version "7.0.0" - resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz#bbb3fbee98661c569034237cc03967ba99b4f250" - integrity sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA== +"@babel/plugin-syntax-class-properties@^7.8.3": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.10.4.tgz#6644e6a0baa55a61f9e3231f6c9eeb6ee46c124c" + integrity sha512-GCSBF7iUle6rNugfURwNmCGG3Z/2+opxAMLs1nND4bhEG5PuxTIggDBoeYYSujAlLtsupzOHYJQgPS3pivwXIA== + dependencies: + "@babel/helper-plugin-utils" "^7.10.4" -"@babel/helper-split-export-declaration@^7.4.4": - version "7.4.4" - resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.4.4.tgz#ff94894a340be78f53f06af038b205c49d993677" - integrity sha512-Ro/XkzLf3JFITkW6b+hNxzZ1n5OQ80NvIUdmHspih1XAhtN3vPTuUFT4eQnela+2MaZ5ulH+iyP513KJrxbN7Q== +"@babel/plugin-syntax-import-meta@^7.8.3": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz#ee601348c370fa334d2207be158777496521fd51" + integrity sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g== dependencies: - "@babel/types" "^7.4.4" + "@babel/helper-plugin-utils" "^7.10.4" -"@babel/helpers@^7.5.0": - version "7.5.1" - resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.5.1.tgz#65407c741a56ddd59dd86346cd112da3de912db3" - integrity sha512-rVOTDv8sH8kNI72Unenusxw6u+1vEepZgLxeV+jHkhsQlYhzVhzL1EpfoWT7Ub3zpWSv2WV03V853dqsnyoQzA== +"@babel/plugin-syntax-json-strings@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz#01ca21b668cd8218c9e640cb6dd88c5412b2c96a" + integrity sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA== dependencies: - "@babel/template" "^7.4.4" - "@babel/traverse" "^7.5.0" - "@babel/types" "^7.5.0" + "@babel/helper-plugin-utils" "^7.8.0" -"@babel/highlight@^7.0.0": - version "7.5.0" - resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.5.0.tgz#56d11312bd9248fa619591d02472be6e8cb32540" - integrity sha512-7dV4eu9gBxoM0dAnj/BCFDW9LFU0zvTrkq0ugM7pnHEgguOEeOz1so2ZghEdzviYzQEED0r4EAgpsBChKy1TRQ== +"@babel/plugin-syntax-logical-assignment-operators@^7.8.3": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz#ca91ef46303530448b906652bac2e9fe9941f699" + integrity sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig== dependencies: - chalk "^2.0.0" - esutils "^2.0.2" - js-tokens "^4.0.0" + "@babel/helper-plugin-utils" "^7.10.4" -"@babel/parser@^7.0.0", "@babel/parser@^7.1.0", "@babel/parser@^7.4.3", "@babel/parser@^7.4.4", "@babel/parser@^7.5.0": - version "7.5.0" - resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.5.0.tgz#3e0713dff89ad6ae37faec3b29dcfc5c979770b7" - integrity sha512-I5nW8AhGpOXGCCNYGc+p7ExQIBxRFnS2fd/d862bNOKvmoEPjYPcfIjsfdy0ujagYOIYPczKgD9l3FsgTkAzKA== +"@babel/plugin-syntax-nullish-coalescing-operator@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz#167ed70368886081f74b5c36c65a88c03b66d1a9" + integrity sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ== + dependencies: + "@babel/helper-plugin-utils" "^7.8.0" -"@babel/plugin-syntax-object-rest-spread@^7.0.0": - version "7.2.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.2.0.tgz#3b7a3e733510c57e820b9142a6579ac8b0dfad2e" - integrity sha512-t0JKGgqk2We+9may3t0xDdmneaXmyxq0xieYcKHxIsrJO64n1OiMWNUtc5gQK1PA0NpdCRrtZp4z+IUaKugrSA== +"@babel/plugin-syntax-numeric-separator@^7.8.3": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz#b9b070b3e33570cd9fd07ba7fa91c0dd37b9af97" + integrity sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug== dependencies: - "@babel/helper-plugin-utils" "^7.0.0" + "@babel/helper-plugin-utils" "^7.10.4" -"@babel/template@^7.1.0", "@babel/template@^7.4.0", "@babel/template@^7.4.4": - version "7.4.4" - resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.4.4.tgz#f4b88d1225689a08f5bc3a17483545be9e4ed237" - integrity sha512-CiGzLN9KgAvgZsnivND7rkA+AeJ9JB0ciPOD4U59GKbQP2iQl+olF1l76kJOupqidozfZ32ghwBEJDhnk9MEcw== +"@babel/plugin-syntax-object-rest-spread@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz#60e225edcbd98a640332a2e72dd3e66f1af55871" + integrity sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA== dependencies: - "@babel/code-frame" "^7.0.0" - "@babel/parser" "^7.4.4" - "@babel/types" "^7.4.4" + "@babel/helper-plugin-utils" "^7.8.0" -"@babel/traverse@^7.1.0", "@babel/traverse@^7.4.3", "@babel/traverse@^7.5.0": - version "7.5.0" - resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.5.0.tgz#4216d6586854ef5c3c4592dab56ec7eb78485485" - integrity sha512-SnA9aLbyOCcnnbQEGwdfBggnc142h/rbqqsXcaATj2hZcegCl903pUD/lfpsNBlBSuWow/YDfRyJuWi2EPR5cg== +"@babel/plugin-syntax-optional-catch-binding@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz#6111a265bcfb020eb9efd0fdfd7d26402b9ed6c1" + integrity sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q== dependencies: - "@babel/code-frame" "^7.0.0" - "@babel/generator" "^7.5.0" - "@babel/helper-function-name" "^7.1.0" - "@babel/helper-split-export-declaration" "^7.4.4" - "@babel/parser" "^7.5.0" - "@babel/types" "^7.5.0" + "@babel/helper-plugin-utils" "^7.8.0" + +"@babel/plugin-syntax-optional-chaining@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz#4f69c2ab95167e0180cd5336613f8c5788f7d48a" + integrity sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg== + dependencies: + "@babel/helper-plugin-utils" "^7.8.0" + +"@babel/template@^7.10.4", "@babel/template@^7.3.3": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.10.4.tgz#3251996c4200ebc71d1a8fc405fba940f36ba278" + integrity sha512-ZCjD27cGJFUB6nmCB1Enki3r+L5kJveX9pq1SvAUKoICy6CZ9yD8xO086YXdYhvNjBdnekm4ZnaP5yC8Cs/1tA== + dependencies: + "@babel/code-frame" "^7.10.4" + "@babel/parser" "^7.10.4" + "@babel/types" "^7.10.4" + +"@babel/traverse@^7.1.0", "@babel/traverse@^7.10.4", "@babel/traverse@^7.11.5": + version "7.11.5" + resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.11.5.tgz#be777b93b518eb6d76ee2e1ea1d143daa11e61c3" + integrity sha512-EjiPXt+r7LiCZXEfRpSJd+jUMnBd4/9OUv7Nx3+0u9+eimMwJmG0Q98lw4/289JCoxSE8OolDMNZaaF/JZ69WQ== + dependencies: + "@babel/code-frame" "^7.10.4" + "@babel/generator" "^7.11.5" + "@babel/helper-function-name" "^7.10.4" + "@babel/helper-split-export-declaration" "^7.11.0" + "@babel/parser" "^7.11.5" + "@babel/types" "^7.11.5" debug "^4.1.0" globals "^11.1.0" - lodash "^4.17.11" + lodash "^4.17.19" -"@babel/types@^7.0.0", "@babel/types@^7.3.0", "@babel/types@^7.4.0", "@babel/types@^7.4.4", "@babel/types@^7.5.0": - version "7.5.0" - resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.5.0.tgz#e47d43840c2e7f9105bc4d3a2c371b4d0c7832ab" - integrity sha512-UFpDVqRABKsW01bvw7/wSUe56uy6RXM5+VJibVVAybDGxEW25jdwiFJEf7ASvSaC7sN7rbE/l3cLp2izav+CtQ== +"@babel/types@^7.0.0", "@babel/types@^7.10.4", "@babel/types@^7.11.0", "@babel/types@^7.11.5", "@babel/types@^7.3.0", "@babel/types@^7.3.3": + version "7.11.5" + resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.11.5.tgz#d9de577d01252d77c6800cee039ee64faf75662d" + integrity sha512-bvM7Qz6eKnJVFIn+1LPtjlBFPVN5jNDc1XmN15vWe7Q3DPBufWWsLiIvUu7xW87uTG6QoggpIDnUgLQvPheU+Q== dependencies: - esutils "^2.0.2" - lodash "^4.17.11" + "@babel/helper-validator-identifier" "^7.10.4" + lodash "^4.17.19" to-fast-properties "^2.0.0" +"@bcoe/v8-coverage@^0.2.3": + version "0.2.3" + resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" + integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw== + "@cnakazawa/watch@^1.0.3": - version "1.0.3" - resolved "https://registry.yarnpkg.com/@cnakazawa/watch/-/watch-1.0.3.tgz#099139eaec7ebf07a27c1786a3ff64f39464d2ef" - integrity sha512-r5160ogAvGyHsal38Kux7YYtodEKOj89RGb28ht1jh3SJb08VwRwAKKJL0bGb04Zd/3r9FL3BFIc3bBidYffCA== + version "1.0.4" + resolved "https://registry.yarnpkg.com/@cnakazawa/watch/-/watch-1.0.4.tgz#f864ae85004d0fcab6f50be9141c4da368d1656a" + integrity sha512-v9kIhKwjeZThiWrLmj0y17CWoyddASLj9O2yvbZkbvw/N3rWOYy9zkV66ursAoVr0mV15bL8g0c4QZUE6cdDoQ== dependencies: exec-sh "^0.3.2" minimist "^1.2.0" -"@jest/console@^24.7.1": - version "24.7.1" - resolved "https://registry.yarnpkg.com/@jest/console/-/console-24.7.1.tgz#32a9e42535a97aedfe037e725bd67e954b459545" - integrity sha512-iNhtIy2M8bXlAOULWVTUxmnelTLFneTNEkHCgPmgd+zNwy9zVddJ6oS5rZ9iwoscNdT5mMwUd0C51v/fSlzItg== - dependencies: - "@jest/source-map" "^24.3.0" - chalk "^2.0.1" - slash "^2.0.0" - -"@jest/core@^24.8.0": - version "24.8.0" - resolved "https://registry.yarnpkg.com/@jest/core/-/core-24.8.0.tgz#fbbdcd42a41d0d39cddbc9f520c8bab0c33eed5b" - integrity sha512-R9rhAJwCBQzaRnrRgAdVfnglUuATXdwTRsYqs6NMdVcAl5euG8LtWDe+fVkN27YfKVBW61IojVsXKaOmSnqd/A== - dependencies: - "@jest/console" "^24.7.1" - "@jest/reporters" "^24.8.0" - "@jest/test-result" "^24.8.0" - "@jest/transform" "^24.8.0" - "@jest/types" "^24.8.0" - ansi-escapes "^3.0.0" - chalk "^2.0.1" +"@hapi/bourne@^1.3.2": + version "1.3.2" + resolved "https://registry.yarnpkg.com/@hapi/bourne/-/bourne-1.3.2.tgz#0a7095adea067243ce3283e1b56b8a8f453b242a" + integrity sha512-1dVNHT76Uu5N3eJNTYcvxee+jzX4Z9lfciqRRHCU27ihbUcYi+iSc2iml5Ke1LXe1SyJCLA0+14Jh4tXJgOppA== + +"@istanbuljs/load-nyc-config@^1.0.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz#fd3db1d59ecf7cf121e80650bb86712f9b55eced" + integrity sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ== + dependencies: + camelcase "^5.3.1" + find-up "^4.1.0" + get-package-type "^0.1.0" + js-yaml "^3.13.1" + resolve-from "^5.0.0" + +"@istanbuljs/schema@^0.1.2": + version "0.1.2" + resolved "https://registry.yarnpkg.com/@istanbuljs/schema/-/schema-0.1.2.tgz#26520bf09abe4a5644cd5414e37125a8954241dd" + integrity sha512-tsAQNx32a8CoFhjhijUIhI4kccIAgmGhy8LZMZgGfmXcpMbPRUqn5LWmgRttILi6yeGmBJd2xsPkFMs0PzgPCw== + +"@jest/console@^26.3.0": + version "26.3.0" + resolved "https://registry.yarnpkg.com/@jest/console/-/console-26.3.0.tgz#ed04063efb280c88ba87388b6f16427c0a85c856" + integrity sha512-/5Pn6sJev0nPUcAdpJHMVIsA8sKizL2ZkcKPE5+dJrCccks7tcM7c9wbgHudBJbxXLoTbqsHkG1Dofoem4F09w== + dependencies: + "@jest/types" "^26.3.0" + "@types/node" "*" + chalk "^4.0.0" + jest-message-util "^26.3.0" + jest-util "^26.3.0" + slash "^3.0.0" + +"@jest/core@^26.4.2": + version "26.4.2" + resolved "https://registry.yarnpkg.com/@jest/core/-/core-26.4.2.tgz#85d0894f31ac29b5bab07aa86806d03dd3d33edc" + integrity sha512-sDva7YkeNprxJfepOctzS8cAk9TOekldh+5FhVuXS40+94SHbiicRO1VV2tSoRtgIo+POs/Cdyf8p76vPTd6dg== + dependencies: + "@jest/console" "^26.3.0" + "@jest/reporters" "^26.4.1" + "@jest/test-result" "^26.3.0" + "@jest/transform" "^26.3.0" + "@jest/types" "^26.3.0" + "@types/node" "*" + ansi-escapes "^4.2.1" + chalk "^4.0.0" exit "^0.1.2" - graceful-fs "^4.1.15" - jest-changed-files "^24.8.0" - jest-config "^24.8.0" - jest-haste-map "^24.8.0" - jest-message-util "^24.8.0" - jest-regex-util "^24.3.0" - jest-resolve-dependencies "^24.8.0" - jest-runner "^24.8.0" - jest-runtime "^24.8.0" - jest-snapshot "^24.8.0" - jest-util "^24.8.0" - jest-validate "^24.8.0" - jest-watcher "^24.8.0" - micromatch "^3.1.10" - p-each-series "^1.0.0" - pirates "^4.0.1" - realpath-native "^1.1.0" - rimraf "^2.5.4" - strip-ansi "^5.0.0" + graceful-fs "^4.2.4" + jest-changed-files "^26.3.0" + jest-config "^26.4.2" + jest-haste-map "^26.3.0" + jest-message-util "^26.3.0" + jest-regex-util "^26.0.0" + jest-resolve "^26.4.0" + jest-resolve-dependencies "^26.4.2" + jest-runner "^26.4.2" + jest-runtime "^26.4.2" + jest-snapshot "^26.4.2" + jest-util "^26.3.0" + jest-validate "^26.4.2" + jest-watcher "^26.3.0" + micromatch "^4.0.2" + p-each-series "^2.1.0" + rimraf "^3.0.0" + slash "^3.0.0" + strip-ansi "^6.0.0" + +"@jest/environment@^26.3.0": + version "26.3.0" + resolved "https://registry.yarnpkg.com/@jest/environment/-/environment-26.3.0.tgz#e6953ab711ae3e44754a025f838bde1a7fd236a0" + integrity sha512-EW+MFEo0DGHahf83RAaiqQx688qpXgl99wdb8Fy67ybyzHwR1a58LHcO376xQJHfmoXTu89M09dH3J509cx2AA== + dependencies: + "@jest/fake-timers" "^26.3.0" + "@jest/types" "^26.3.0" + "@types/node" "*" + jest-mock "^26.3.0" -"@jest/environment@^24.8.0": - version "24.8.0" - resolved "https://registry.yarnpkg.com/@jest/environment/-/environment-24.8.0.tgz#0342261383c776bdd652168f68065ef144af0eac" - integrity sha512-vlGt2HLg7qM+vtBrSkjDxk9K0YtRBi7HfRFaDxoRtyi+DyVChzhF20duvpdAnKVBV6W5tym8jm0U9EfXbDk1tw== - dependencies: - "@jest/fake-timers" "^24.8.0" - "@jest/transform" "^24.8.0" - "@jest/types" "^24.8.0" - jest-mock "^24.8.0" - -"@jest/fake-timers@^24.8.0": - version "24.8.0" - resolved "https://registry.yarnpkg.com/@jest/fake-timers/-/fake-timers-24.8.0.tgz#2e5b80a4f78f284bcb4bd5714b8e10dd36a8d3d1" - integrity sha512-2M4d5MufVXwi6VzZhJ9f5S/wU4ud2ck0kxPof1Iz3zWx6Y+V2eJrES9jEktB6O3o/oEyk+il/uNu9PvASjWXQw== - dependencies: - "@jest/types" "^24.8.0" - jest-message-util "^24.8.0" - jest-mock "^24.8.0" - -"@jest/reporters@^24.8.0": - version "24.8.0" - resolved "https://registry.yarnpkg.com/@jest/reporters/-/reporters-24.8.0.tgz#075169cd029bddec54b8f2c0fc489fd0b9e05729" - integrity sha512-eZ9TyUYpyIIXfYCrw0UHUWUvE35vx5I92HGMgS93Pv7du+GHIzl+/vh8Qj9MCWFK/4TqyttVBPakWMOfZRIfxw== - dependencies: - "@jest/environment" "^24.8.0" - "@jest/test-result" "^24.8.0" - "@jest/transform" "^24.8.0" - "@jest/types" "^24.8.0" - chalk "^2.0.1" +"@jest/fake-timers@^26.3.0": + version "26.3.0" + resolved "https://registry.yarnpkg.com/@jest/fake-timers/-/fake-timers-26.3.0.tgz#f515d4667a6770f60ae06ae050f4e001126c666a" + integrity sha512-ZL9ytUiRwVP8ujfRepffokBvD2KbxbqMhrXSBhSdAhISCw3gOkuntisiSFv+A6HN0n0fF4cxzICEKZENLmW+1A== + dependencies: + "@jest/types" "^26.3.0" + "@sinonjs/fake-timers" "^6.0.1" + "@types/node" "*" + jest-message-util "^26.3.0" + jest-mock "^26.3.0" + jest-util "^26.3.0" + +"@jest/globals@^26.4.2": + version "26.4.2" + resolved "https://registry.yarnpkg.com/@jest/globals/-/globals-26.4.2.tgz#73c2a862ac691d998889a241beb3dc9cada40d4a" + integrity sha512-Ot5ouAlehhHLRhc+sDz2/9bmNv9p5ZWZ9LE1pXGGTCXBasmi5jnYjlgYcYt03FBwLmZXCZ7GrL29c33/XRQiow== + dependencies: + "@jest/environment" "^26.3.0" + "@jest/types" "^26.3.0" + expect "^26.4.2" + +"@jest/reporters@^26.4.1": + version "26.4.1" + resolved "https://registry.yarnpkg.com/@jest/reporters/-/reporters-26.4.1.tgz#3b4d6faf28650f3965f8b97bc3d114077fb71795" + integrity sha512-aROTkCLU8++yiRGVxLsuDmZsQEKO6LprlrxtAuzvtpbIFl3eIjgIf3EUxDKgomkS25R9ZzwGEdB5weCcBZlrpQ== + dependencies: + "@bcoe/v8-coverage" "^0.2.3" + "@jest/console" "^26.3.0" + "@jest/test-result" "^26.3.0" + "@jest/transform" "^26.3.0" + "@jest/types" "^26.3.0" + chalk "^4.0.0" + collect-v8-coverage "^1.0.0" exit "^0.1.2" glob "^7.1.2" - istanbul-lib-coverage "^2.0.2" - istanbul-lib-instrument "^3.0.1" - istanbul-lib-report "^2.0.4" - istanbul-lib-source-maps "^3.0.1" - istanbul-reports "^2.1.1" - jest-haste-map "^24.8.0" - jest-resolve "^24.8.0" - jest-runtime "^24.8.0" - jest-util "^24.8.0" - jest-worker "^24.6.0" - node-notifier "^5.2.1" - slash "^2.0.0" + graceful-fs "^4.2.4" + istanbul-lib-coverage "^3.0.0" + istanbul-lib-instrument "^4.0.3" + istanbul-lib-report "^3.0.0" + istanbul-lib-source-maps "^4.0.0" + istanbul-reports "^3.0.2" + jest-haste-map "^26.3.0" + jest-resolve "^26.4.0" + jest-util "^26.3.0" + jest-worker "^26.3.0" + slash "^3.0.0" source-map "^0.6.0" - string-length "^2.0.0" + string-length "^4.0.1" + terminal-link "^2.0.0" + v8-to-istanbul "^5.0.1" + optionalDependencies: + node-notifier "^8.0.0" -"@jest/source-map@^24.3.0": - version "24.3.0" - resolved "https://registry.yarnpkg.com/@jest/source-map/-/source-map-24.3.0.tgz#563be3aa4d224caf65ff77edc95cd1ca4da67f28" - integrity sha512-zALZt1t2ou8le/crCeeiRYzvdnTzaIlpOWaet45lNSqNJUnXbppUUFR4ZUAlzgDmKee4Q5P/tKXypI1RiHwgag== +"@jest/source-map@^26.3.0": + version "26.3.0" + resolved "https://registry.yarnpkg.com/@jest/source-map/-/source-map-26.3.0.tgz#0e646e519883c14c551f7b5ae4ff5f1bfe4fc3d9" + integrity sha512-hWX5IHmMDWe1kyrKl7IhFwqOuAreIwHhbe44+XH2ZRHjrKIh0LO5eLQ/vxHFeAfRwJapmxuqlGAEYLadDq6ZGQ== dependencies: callsites "^3.0.0" - graceful-fs "^4.1.15" + graceful-fs "^4.2.4" source-map "^0.6.0" -"@jest/test-result@^24.8.0": - version "24.8.0" - resolved "https://registry.yarnpkg.com/@jest/test-result/-/test-result-24.8.0.tgz#7675d0aaf9d2484caa65e048d9b467d160f8e9d3" - integrity sha512-+YdLlxwizlfqkFDh7Mc7ONPQAhA4YylU1s529vVM1rsf67vGZH/2GGm5uO8QzPeVyaVMobCQ7FTxl38QrKRlng== +"@jest/test-result@^26.3.0": + version "26.3.0" + resolved "https://registry.yarnpkg.com/@jest/test-result/-/test-result-26.3.0.tgz#46cde01fa10c0aaeb7431bf71e4a20d885bc7fdb" + integrity sha512-a8rbLqzW/q7HWheFVMtghXV79Xk+GWwOK1FrtimpI5n1la2SY0qHri3/b0/1F0Ve0/yJmV8pEhxDfVwiUBGtgg== dependencies: - "@jest/console" "^24.7.1" - "@jest/types" "^24.8.0" + "@jest/console" "^26.3.0" + "@jest/types" "^26.3.0" "@types/istanbul-lib-coverage" "^2.0.0" + collect-v8-coverage "^1.0.0" -"@jest/test-sequencer@^24.8.0": - version "24.8.0" - resolved "https://registry.yarnpkg.com/@jest/test-sequencer/-/test-sequencer-24.8.0.tgz#2f993bcf6ef5eb4e65e8233a95a3320248cf994b" - integrity sha512-OzL/2yHyPdCHXEzhoBuq37CE99nkme15eHkAzXRVqthreWZamEMA0WoetwstsQBCXABhczpK03JNbc4L01vvLg== +"@jest/test-sequencer@^26.4.2": + version "26.4.2" + resolved "https://registry.yarnpkg.com/@jest/test-sequencer/-/test-sequencer-26.4.2.tgz#58a3760a61eec758a2ce6080201424580d97cbba" + integrity sha512-83DRD8N3M0tOhz9h0bn6Kl6dSp+US6DazuVF8J9m21WAp5x7CqSMaNycMP0aemC/SH/pDQQddbsfHRTBXVUgog== dependencies: - "@jest/test-result" "^24.8.0" - jest-haste-map "^24.8.0" - jest-runner "^24.8.0" - jest-runtime "^24.8.0" + "@jest/test-result" "^26.3.0" + graceful-fs "^4.2.4" + jest-haste-map "^26.3.0" + jest-runner "^26.4.2" + jest-runtime "^26.4.2" -"@jest/transform@^24.8.0": - version "24.8.0" - resolved "https://registry.yarnpkg.com/@jest/transform/-/transform-24.8.0.tgz#628fb99dce4f9d254c6fd9341e3eea262e06fef5" - integrity sha512-xBMfFUP7TortCs0O+Xtez2W7Zu1PLH9bvJgtraN1CDST6LBM/eTOZ9SfwS/lvV8yOfcDpFmwf9bq5cYbXvqsvA== +"@jest/transform@^26.3.0": + version "26.3.0" + resolved "https://registry.yarnpkg.com/@jest/transform/-/transform-26.3.0.tgz#c393e0e01459da8a8bfc6d2a7c2ece1a13e8ba55" + integrity sha512-Isj6NB68QorGoFWvcOjlUhpkT56PqNIsXKR7XfvoDlCANn/IANlh8DrKAA2l2JKC3yWSMH5wS0GwuQM20w3b2A== dependencies: "@babel/core" "^7.1.0" - "@jest/types" "^24.8.0" - babel-plugin-istanbul "^5.1.0" - chalk "^2.0.1" + "@jest/types" "^26.3.0" + babel-plugin-istanbul "^6.0.0" + chalk "^4.0.0" convert-source-map "^1.4.0" fast-json-stable-stringify "^2.0.0" - graceful-fs "^4.1.15" - jest-haste-map "^24.8.0" - jest-regex-util "^24.3.0" - jest-util "^24.8.0" - micromatch "^3.1.10" - realpath-native "^1.1.0" - slash "^2.0.0" + graceful-fs "^4.2.4" + jest-haste-map "^26.3.0" + jest-regex-util "^26.0.0" + jest-util "^26.3.0" + micromatch "^4.0.2" + pirates "^4.0.1" + slash "^3.0.0" source-map "^0.6.1" - write-file-atomic "2.4.1" + write-file-atomic "^3.0.0" -"@jest/types@^24.8.0": - version "24.8.0" - resolved "https://registry.yarnpkg.com/@jest/types/-/types-24.8.0.tgz#f31e25948c58f0abd8c845ae26fcea1491dea7ad" - integrity sha512-g17UxVr2YfBtaMUxn9u/4+siG1ptg9IGYAYwvpwn61nBg779RXnjE/m7CxYcIzEt0AbHZZAHSEZNhkE2WxURVg== +"@jest/types@^25.5.0": + version "25.5.0" + resolved "https://registry.yarnpkg.com/@jest/types/-/types-25.5.0.tgz#4d6a4793f7b9599fc3680877b856a97dbccf2a9d" + integrity sha512-OXD0RgQ86Tu3MazKo8bnrkDRaDXXMGUqd+kTtLtK1Zb7CRzQcaSRPPPV37SvYTdevXEBVxe0HXylEjs8ibkmCw== dependencies: "@types/istanbul-lib-coverage" "^2.0.0" "@types/istanbul-reports" "^1.1.1" - "@types/yargs" "^12.0.9" + "@types/yargs" "^15.0.0" + chalk "^3.0.0" -"@octokit/endpoint@^5.1.0": - version "5.2.2" - resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-5.2.2.tgz#8fbb2e99ae0d8e6b30099f73063801e64467e761" - integrity sha512-VhKxM4CQanIUZDffExqpdpgqu3heF51qbY1wazoNtvIKXAAVoFjqLq2BOhesXkTqxXMO1Ze1XbS8DkIjUxAB+g== +"@jest/types@^26.3.0": + version "26.3.0" + resolved "https://registry.yarnpkg.com/@jest/types/-/types-26.3.0.tgz#97627bf4bdb72c55346eef98e3b3f7ddc4941f71" + integrity sha512-BDPG23U0qDeAvU4f99haztXwdAg3hz4El95LkAM+tHAqqhiVzRpEGHHU8EDxT/AnxOrA65YjLBwDahdJ9pTLJQ== dependencies: - deepmerge "4.0.0" - is-plain-object "^3.0.0" - universal-user-agent "^3.0.0" - url-template "^2.0.8" + "@types/istanbul-lib-coverage" "^2.0.0" + "@types/istanbul-reports" "^3.0.0" + "@types/node" "*" + "@types/yargs" "^15.0.0" + chalk "^4.0.0" -"@octokit/graphql@^3.0.1": - version "3.0.1" - resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-3.0.1.tgz#7559c3bb606a2aab7ba91e82633c044642b354c0" - integrity sha512-TiegCo0jueDPlkpcYlx8KSYa3ybs13ePBteoJutEHou0hu8sJHHhvIaQWvDH5jj4mHfJwZwD4r6/Xbl33UHLUw== +"@octokit/auth-token@^2.4.0": + version "2.4.2" + resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-2.4.2.tgz#10d0ae979b100fa6b72fa0e8e63e27e6d0dbff8a" + integrity sha512-jE/lE/IKIz2v1+/P0u4fJqv0kYwXOTujKemJMFr6FeopsxlIK3+wKDCJGnysg81XID5TgZQbIfuJ5J0lnTiuyQ== dependencies: - "@octokit/request" "^5.0.0" - universal-user-agent "^3.0.0" + "@octokit/types" "^5.0.0" -"@octokit/request-error@^1.0.1", "@octokit/request-error@^1.0.2": - version "1.0.4" - resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-1.0.4.tgz#15e1dc22123ba4a9a4391914d80ec1e5303a23be" - integrity sha512-L4JaJDXn8SGT+5G0uX79rZLv0MNJmfGa4vb4vy1NnpjSnWDLJRy6m90udGwvMmavwsStgbv2QNkPzzTCMmL+ig== +"@octokit/core@^3.0.0": + version "3.1.2" + resolved "https://registry.yarnpkg.com/@octokit/core/-/core-3.1.2.tgz#c937d5f9621b764573068fcd2e5defcc872fd9cc" + integrity sha512-AInOFULmwOa7+NFi9F8DlDkm5qtZVmDQayi7TUgChE3yeIGPq0Y+6cAEXPexQ3Ea+uZy66hKEazR7DJyU+4wfw== + dependencies: + "@octokit/auth-token" "^2.4.0" + "@octokit/graphql" "^4.3.1" + "@octokit/request" "^5.4.0" + "@octokit/types" "^5.0.0" + before-after-hook "^2.1.0" + universal-user-agent "^6.0.0" + +"@octokit/endpoint@^6.0.1": + version "6.0.6" + resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-6.0.6.tgz#4f09f2b468976b444742a1d5069f6fa45826d999" + integrity sha512-7Cc8olaCoL/mtquB7j/HTbPM+sY6Ebr4k2X2y4JoXpVKQ7r5xB4iGQE0IoO58wIPsUk4AzoT65AMEpymSbWTgQ== + dependencies: + "@octokit/types" "^5.0.0" + is-plain-object "^5.0.0" + universal-user-agent "^6.0.0" + +"@octokit/graphql@^4.3.1", "@octokit/graphql@^4.5.4": + version "4.5.6" + resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-4.5.6.tgz#708143ba15cf7c1879ed6188266e7f270be805d4" + integrity sha512-Rry+unqKTa3svswT2ZAuqenpLrzJd+JTv89LTeVa5UM/5OX8o4KTkPL7/1ABq4f/ZkELb0XEK/2IEoYwykcLXg== + dependencies: + "@octokit/request" "^5.3.0" + "@octokit/types" "^5.0.0" + universal-user-agent "^6.0.0" + +"@octokit/plugin-paginate-rest@^2.2.0", "@octokit/plugin-paginate-rest@^2.2.3": + version "2.3.3" + resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.3.3.tgz#ceaa9f77bdce4b468d8aeaf5eb8f9a23ee4f97b5" + integrity sha512-pYU1sHau3CzcYIC6K5tvxsGjVfxBWcG9fcDPj7k8lUCzwXD2YJFoIPCrbsxWd/rc1lnyNVKgCkwdk3Kbm36z9Q== + dependencies: + "@octokit/types" "^5.3.0" + +"@octokit/plugin-request-log@^1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@octokit/plugin-request-log/-/plugin-request-log-1.0.0.tgz#eef87a431300f6148c39a7f75f8cfeb218b2547e" + integrity sha512-ywoxP68aOT3zHCLgWZgwUJatiENeHE7xJzYjfz8WI0goynp96wETBF+d95b8g/uL4QmS6owPVlaxiz3wyMAzcw== + +"@octokit/plugin-rest-endpoint-methods@4.1.4", "@octokit/plugin-rest-endpoint-methods@^4.0.0": + version "4.1.4" + resolved "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-4.1.4.tgz#ca60736d761b304fec02a2608caaec2d822e9835" + integrity sha512-Y2tVpSa7HjV3DGIQrQOJcReJ2JtcN9FaGr9jDa332Flro923/h3/Iu9e7Y4GilnzfLclHEh5iCQoCkHm7tWOcg== dependencies: + "@octokit/types" "^5.4.1" + deprecation "^2.3.1" + +"@octokit/request-error@^2.0.0": + version "2.0.2" + resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-2.0.2.tgz#0e76b83f5d8fdda1db99027ea5f617c2e6ba9ed0" + integrity sha512-2BrmnvVSV1MXQvEkrb9zwzP0wXFNbPJij922kYBTLIlIafukrGOb+ABBT2+c6wZiuyWDH1K1zmjGQ0toN/wMWw== + dependencies: + "@octokit/types" "^5.0.1" deprecation "^2.0.0" once "^1.4.0" -"@octokit/request@^5.0.0": - version "5.0.1" - resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.0.1.tgz#6705c9a883db0ac0f58cee717e806b6575d4a199" - integrity sha512-SHOk/APYpfrzV1RNf7Ux8SZi+vZXhMIB2dBr4TQR6ExMX8R4jcy/0gHw26HLe1dWV7Wxe9WzYyDSEC0XwnoCSQ== +"@octokit/request@^5.3.0", "@octokit/request@^5.4.0": + version "5.4.8" + resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.4.8.tgz#13ad36e172bb57e78bacf02cd86210d1f7412f04" + integrity sha512-mWbxjsARJzAq5xp+ZrQfotc+MHFz3/Am2qATJwflv4PZ1TjhgIJnr60PCVdZT9Z/tl+uPXooaVgeviy1KkDlLQ== dependencies: - "@octokit/endpoint" "^5.1.0" - "@octokit/request-error" "^1.0.1" + "@octokit/endpoint" "^6.0.1" + "@octokit/request-error" "^2.0.0" + "@octokit/types" "^5.0.0" deprecation "^2.0.0" - is-plain-object "^3.0.0" + is-plain-object "^5.0.0" node-fetch "^2.3.0" once "^1.4.0" - universal-user-agent "^3.0.0" - -"@octokit/rest@^16.28.4": - version "16.28.4" - resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-16.28.4.tgz#2f8ef08305033bc91256530d6a3c98eada700660" - integrity sha512-ZBsfD46t3VNkwealxm5zloVgQta8d8o4KYBR/hMAZ582IgjmSDKZdkjyv5w37IUCM3tcPZWKUT+kml9pEIC2GA== - dependencies: - "@octokit/request" "^5.0.0" - "@octokit/request-error" "^1.0.2" - atob-lite "^2.0.0" - before-after-hook "^2.0.0" - btoa-lite "^1.0.0" - deprecation "^2.0.0" - lodash.get "^4.4.2" - lodash.set "^4.3.2" - lodash.uniq "^4.5.0" - octokit-pagination-methods "^1.1.0" - once "^1.4.0" - universal-user-agent "^3.0.0" - url-template "^2.0.8" + universal-user-agent "^6.0.0" + +"@octokit/rest@^18.0.5": + version "18.0.5" + resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-18.0.5.tgz#1f1498dcdc2d85d0f86b8168e4ff5779842b2742" + integrity sha512-SPKI24tQXrr1XsnaIjv2x0rl4M5eF1+hj8+vMe3d/exZ7NnL5sTe1BuFyCyJyrc+j1HkXankvgGN9zT0rwBwtg== + dependencies: + "@octokit/core" "^3.0.0" + "@octokit/plugin-paginate-rest" "^2.2.0" + "@octokit/plugin-request-log" "^1.0.0" + "@octokit/plugin-rest-endpoint-methods" "4.1.4" + +"@octokit/types@^5.0.0", "@octokit/types@^5.0.1", "@octokit/types@^5.3.0", "@octokit/types@^5.4.1": + version "5.4.1" + resolved "https://registry.yarnpkg.com/@octokit/types/-/types-5.4.1.tgz#d5d5f2b70ffc0e3f89467c3db749fa87fc3b7031" + integrity sha512-OlMlSySBJoJ6uozkr/i03nO5dlYQyE05vmQNZhAh9MyO4DPBP88QlwsDVLmVjIMFssvIZB6WO0ctIGMRG+xsJQ== + dependencies: + "@types/node" ">= 8" -"@types/babel__core@^7.1.0": - version "7.1.2" - resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.2.tgz#608c74f55928033fce18b99b213c16be4b3d114f" - integrity sha512-cfCCrFmiGY/yq0NuKNxIQvZFy9kY/1immpSpTngOnyIbD4+eJOG5mxphhHDv3CHL9GltO4GcKr54kGBg3RNdbg== +"@sinonjs/commons@^1.7.0": + version "1.8.1" + resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-1.8.1.tgz#e7df00f98a203324f6dc7cc606cad9d4a8ab2217" + integrity sha512-892K+kWUUi3cl+LlqEWIDrhvLgdL79tECi8JZUyq6IviKy/DNhuzCRlbHUjxK89f4ypPMMaFnFuR9Ie6DoIMsw== + dependencies: + type-detect "4.0.8" + +"@sinonjs/fake-timers@^6.0.1": + version "6.0.1" + resolved "https://registry.yarnpkg.com/@sinonjs/fake-timers/-/fake-timers-6.0.1.tgz#293674fccb3262ac782c7aadfdeca86b10c75c40" + integrity sha512-MZPUxrmFubI36XS1DI3qmI0YdN1gks62JtFZvxR67ljjSNCeK6U08Zx4msEWOXuofgqUt6zPHSi1H9fbjR/NRA== + dependencies: + "@sinonjs/commons" "^1.7.0" + +"@types/babel__core@^7.0.0", "@types/babel__core@^7.1.7": + version "7.1.9" + resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.9.tgz#77e59d438522a6fb898fa43dc3455c6e72f3963d" + integrity sha512-sY2RsIJ5rpER1u3/aQ8OFSI7qGIy8o1NEEbgb2UaJcvOtXOMpd39ko723NBpjQFg9SIX7TXtjejZVGeIMLhoOw== dependencies: "@babel/parser" "^7.1.0" "@babel/types" "^7.0.0" @@ -355,9 +618,9 @@ "@types/babel__traverse" "*" "@types/babel__generator@*": - version "7.0.2" - resolved "https://registry.yarnpkg.com/@types/babel__generator/-/babel__generator-7.0.2.tgz#d2112a6b21fad600d7674274293c85dce0cb47fc" - integrity sha512-NHcOfab3Zw4q5sEE2COkpfXjoE7o+PmqD9DQW4koUT3roNxwziUdXGnRndMat/LJNUtePwn1TlP4do3uoe3KZQ== + version "7.6.1" + resolved "https://registry.yarnpkg.com/@types/babel__generator/-/babel__generator-7.6.1.tgz#4901767b397e8711aeb99df8d396d7ba7b7f0e04" + integrity sha512-bBKm+2VPJcMRVwNhxKu8W+5/zT7pwNEqeokFOmbvVSqGzFneNxYcEBro9Ac7/N9tlsaPYnZLK8J1LWKkMsLAew== dependencies: "@babel/types" "^7.0.0" @@ -370,55 +633,75 @@ "@babel/types" "^7.0.0" "@types/babel__traverse@*", "@types/babel__traverse@^7.0.6": - version "7.0.7" - resolved "https://registry.yarnpkg.com/@types/babel__traverse/-/babel__traverse-7.0.7.tgz#2496e9ff56196cc1429c72034e07eab6121b6f3f" - integrity sha512-CeBpmX1J8kWLcDEnI3Cl2Eo6RfbGvzUctA+CjZUhOKDFbLfcr7fc4usEqLNWetrlJd7RhAkyYe2czXop4fICpw== + version "7.0.14" + resolved "https://registry.yarnpkg.com/@types/babel__traverse/-/babel__traverse-7.0.14.tgz#e99da8c075d4fb098c774ba65dabf7dc9954bd13" + integrity sha512-8w9szzKs14ZtBVuP6Wn7nMLRJ0D6dfB0VEBEyRgxrZ/Ln49aNMykrghM2FaNn4FJRzNppCSa0Rv9pBRM5Xc3wg== dependencies: "@babel/types" "^7.3.0" "@types/bson@*": - version "4.0.0" - resolved "https://registry.yarnpkg.com/@types/bson/-/bson-4.0.0.tgz#9073772679d749116eb1dfca56f8eaac6d59cc7a" - integrity sha512-pq/rqJwJWkbS10crsG5bgnrisL8pML79KlMKQMoQwLUjlPAkrUHMvHJ3oGwE7WHR61Lv/nadMwXVAD2b+fpD8Q== + version "4.0.2" + resolved "https://registry.yarnpkg.com/@types/bson/-/bson-4.0.2.tgz#7accb85942fc39bbdb7515d4de437c04f698115f" + integrity sha512-+uWmsejEHfmSjyyM/LkrP0orfE2m5Mx9Xel4tXNeqi1ldK5XMQcDsFkBmLDtuyKUbxj2jGDo0H240fbCRJZo7Q== + dependencies: + "@types/node" "*" + +"@types/color-name@^1.1.1": + version "1.1.1" + resolved "https://registry.yarnpkg.com/@types/color-name/-/color-name-1.1.1.tgz#1c1261bbeaa10a8055bbc5d8ab84b7b2afc846a0" + integrity sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ== + +"@types/events@*": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@types/events/-/events-3.0.0.tgz#2862f3f58a9a7f7c3e78d79f130dd4d71c25c2a7" + integrity sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g== + +"@types/graceful-fs@^4.1.2": + version "4.1.3" + resolved "https://registry.yarnpkg.com/@types/graceful-fs/-/graceful-fs-4.1.3.tgz#039af35fe26bec35003e8d86d2ee9c586354348f" + integrity sha512-AiHRaEB50LQg0pZmm659vNBb9f4SJ0qrAnteuzhSeAUcJKxoYgEnprg/83kppCnc2zvtCKbdZry1a5pVY3lOTQ== dependencies: "@types/node" "*" "@types/invariant@^2.2.30": - version "2.2.30" - resolved "https://registry.yarnpkg.com/@types/invariant/-/invariant-2.2.30.tgz#20efa342807606ada5483731a8137cb1561e5fe9" - integrity sha512-98fB+yo7imSD2F7PF7GIpELNgtLNgo5wjivu0W5V4jx+KVVJxo6p/qN4zdzSTBWy4/sN3pPyXwnhRSD28QX+ag== + version "2.2.34" + resolved "https://registry.yarnpkg.com/@types/invariant/-/invariant-2.2.34.tgz#05e4f79f465c2007884374d4795452f995720bbe" + integrity sha512-lYUtmJ9BqUN688fGY1U1HZoWT1/Jrmgigx2loq4ZcJpICECm/Om3V314BxdzypO0u5PORKGMM6x0OXaljV1YFg== -"@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0": - version "2.0.1" - resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.1.tgz#42995b446db9a48a11a07ec083499a860e9138ff" - integrity sha512-hRJD2ahnnpLgsj6KWMYSrmXkM3rm2Dl1qkx6IOFD5FnuNPXJIG5L0dhgKXCYTRMGzU4n0wImQ/xfmRc4POUFlg== +"@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0", "@types/istanbul-lib-coverage@^2.0.1": + version "2.0.3" + resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.3.tgz#4ba8ddb720221f432e443bd5f9117fd22cfd4762" + integrity sha512-sz7iLqvVUg1gIedBOvlkxPlc8/uVzyS5OwGz1cKjXzkl3FpL3al0crU8YGU1WoHkxn0Wxbw5tyi6hvzJKNzFsw== "@types/istanbul-lib-report@*": - version "1.1.1" - resolved "https://registry.yarnpkg.com/@types/istanbul-lib-report/-/istanbul-lib-report-1.1.1.tgz#e5471e7fa33c61358dd38426189c037a58433b8c" - integrity sha512-3BUTyMzbZa2DtDI2BkERNC6jJw2Mr2Y0oGI7mRxYNBPxppbtEK1F66u3bKwU2g+wxwWI7PAoRpJnOY1grJqzHg== + version "3.0.0" + resolved "https://registry.yarnpkg.com/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz#c14c24f18ea8190c118ee7562b7ff99a36552686" + integrity sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg== dependencies: "@types/istanbul-lib-coverage" "*" "@types/istanbul-reports@^1.1.1": - version "1.1.1" - resolved "https://registry.yarnpkg.com/@types/istanbul-reports/-/istanbul-reports-1.1.1.tgz#7a8cbf6a406f36c8add871625b278eaf0b0d255a" - integrity sha512-UpYjBi8xefVChsCoBpKShdxTllC9pwISirfoZsUa2AAdQg/Jd2KQGtSbw+ya7GPo7x/wAPlH6JBhKhAsXUEZNA== + version "1.1.2" + resolved "https://registry.yarnpkg.com/@types/istanbul-reports/-/istanbul-reports-1.1.2.tgz#e875cc689e47bce549ec81f3df5e6f6f11cfaeb2" + integrity sha512-P/W9yOX/3oPZSpaYOCQzGqgCQRXn0FFO/V8bWrCQs+wLmvVVxk6CRBXALEvNs9OHIatlnlFokfhuDo2ug01ciw== dependencies: "@types/istanbul-lib-coverage" "*" "@types/istanbul-lib-report" "*" -"@types/jest-diff@*": - version "20.0.1" - resolved "https://registry.yarnpkg.com/@types/jest-diff/-/jest-diff-20.0.1.tgz#35cc15b9c4f30a18ef21852e255fdb02f6d59b89" - integrity sha512-yALhelO3i0hqZwhjtcr6dYyaLoCHbAMshwtj6cGxTvHZAKXHsYGdff6E8EPw3xLKY0ELUTQ69Q1rQiJENnccMA== +"@types/istanbul-reports@^3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@types/istanbul-reports/-/istanbul-reports-3.0.0.tgz#508b13aa344fa4976234e75dddcc34925737d821" + integrity sha512-nwKNbvnwJ2/mndE9ItP/zc2TCzw6uuodnF4EHYWD+gCQDVBuRQL5UzbZD0/ezy1iKsFU2ZQiDqg4M9dN4+wZgA== + dependencies: + "@types/istanbul-lib-report" "*" -"@types/jest@^24.0.15": - version "24.0.15" - resolved "https://registry.yarnpkg.com/@types/jest/-/jest-24.0.15.tgz#6c42d5af7fe3b44ffff7cc65de7bf741e8fa427f" - integrity sha512-MU1HIvWUme74stAoc3mgAi+aMlgKOudgEvQDIm1v4RkrDudBh1T+NFp5sftpBAdXdx1J0PbdpJ+M2EsSOi1djA== +"@types/jest@26.x", "@types/jest@^26.0.13": + version "26.0.13" + resolved "https://registry.yarnpkg.com/@types/jest/-/jest-26.0.13.tgz#5a7b9d5312f5dd521a38329c38ee9d3802a0b85e" + integrity sha512-sCzjKow4z9LILc6DhBvn5AkIfmQzDZkgtVVKmGwVrs5tuid38ws281D4l+7x1kP487+FlKDh5kfMZ8WSPAdmdA== dependencies: - "@types/jest-diff" "*" + jest-diff "^25.2.1" + pretty-format "^25.2.1" "@types/lodash.sortby@^4.7.6": version "4.7.6" @@ -428,32 +711,45 @@ "@types/lodash" "*" "@types/lodash@*": - version "4.14.136" - resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.136.tgz#413e85089046b865d960c9ff1d400e04c31ab60f" - integrity sha512-0GJhzBdvsW2RUccNHOBkabI8HZVdOXmXbXhuKlDEd5Vv12P7oAVGfomGp3Ne21o5D/qu1WmthlNKFaoZJJeErA== + version "4.14.161" + resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.161.tgz#a21ca0777dabc6e4f44f3d07f37b765f54188b18" + integrity sha512-EP6O3Jkr7bXvZZSZYlsgt5DIjiGr0dXP1/jVEwVLTFgg0d+3lWVQkRavYVQszV7dYUwvg0B8R0MBDpcmXg7XIA== -"@types/mongodb@^3.1.28": - version "3.1.28" - resolved "https://registry.yarnpkg.com/@types/mongodb/-/mongodb-3.1.28.tgz#c049cdff343788d77f5cc8c5f2e4af72ba7d047b" - integrity sha512-tG+QqJ/hir2p0069ee28t2O9tlGRJKDq1WFZC2QYMlU47LGdldLL8tepfTq6aFLvP58OpwSoxaJ/qjW93ob1NQ== +"@types/mongodb@^3.5.27": + version "3.5.27" + resolved "https://registry.yarnpkg.com/@types/mongodb/-/mongodb-3.5.27.tgz#158a7a43ce25ef3592ac8a62e62ab38bebf661f2" + integrity sha512-1jxKDgdfJEOO9zp+lv43p8jOqRs02xPrdUTzAZIVK9tVEySfCEmktL2jEu9A3wOBEOs18yKzpVIKUh8b8ALk3w== dependencies: "@types/bson" "*" "@types/node" "*" -"@types/node@*": - version "12.6.3" - resolved "https://registry.yarnpkg.com/@types/node/-/node-12.6.3.tgz#44d507c5634f85e7164707ca36bba21b5213d487" - integrity sha512-7TEYTQT1/6PP53NftXXabIZDaZfaoBdeBm8Md/i7zsWRoBe0YwOXguyK8vhHs8ehgB/w9U4K/6EWuTyp0W6nIA== - -"@types/node@^12.0.12": - version "12.0.12" - resolved "https://registry.yarnpkg.com/@types/node/-/node-12.0.12.tgz#cc791b402360db1eaf7176479072f91ee6c6c7ca" - integrity sha512-Uy0PN4R5vgBUXFoJrKryf5aTk3kJ8Rv3PdlHjl6UaX+Cqp1QE0yPQ68MPXGrZOfG7gZVNDIJZYyot0B9ubXUrQ== +"@types/node@*", "@types/node@>= 8", "@types/node@^14.6.4": + version "14.10.1" + resolved "https://registry.yarnpkg.com/@types/node/-/node-14.10.1.tgz#cc323bad8e8a533d4822f45ce4e5326f36e42177" + integrity sha512-aYNbO+FZ/3KGeQCEkNhHFRIzBOUgc7QvcVNKXbfnhDkSfwUv91JsQQa10rDgKSTSLkXZ1UIyPe4FJJNVgw1xWQ== "@types/node@^12.6.1": - version "12.6.1" - resolved "https://registry.yarnpkg.com/@types/node/-/node-12.6.1.tgz#d5544f6de0aae03eefbb63d5120f6c8be0691946" - integrity sha512-rp7La3m845mSESCgsJePNL/JQyhkOJA6G4vcwvVgkDAwHhGdq5GCumxmPjEk1MZf+8p5ZQAUE7tqgQRQTXN7uQ== + version "12.12.58" + resolved "https://registry.yarnpkg.com/@types/node/-/node-12.12.58.tgz#46dae9b2b9ee5992818c8f7cee01ff4ce03ab44c" + integrity sha512-Be46CNIHWAagEfINOjmriSxuv7IVcqbGe+sDSg2SYCEz/0CRBy7LRASGfRbD8KZkqoePU73Wsx3UvOSFcq/9hA== + +"@types/normalize-package-data@^2.4.0": + version "2.4.0" + resolved "https://registry.yarnpkg.com/@types/normalize-package-data/-/normalize-package-data-2.4.0.tgz#e486d0d97396d79beedd0a6e33f4534ff6b4973e" + integrity sha512-f5j5b/Gf71L+dbqxIpQ4Z2WlmI/mPJ0fOkGGmFgtb6sAu97EPczzbS3/tJKxmcYDj55OX6ssqwDAWOHIYDRDGA== + +"@types/pino@^5.8.8": + version "5.20.0" + resolved "https://registry.yarnpkg.com/@types/pino/-/pino-5.20.0.tgz#d4bafa71d992d223d29c857c11988e8c3abc66f0" + integrity sha512-gz3Ahvx1UDEveXViOQtYqnUkjSVQFdoJqpZTW/63spEHwOGRJRJIi3JMJSClp5Sk1x1ljn9tHWjGczmP6s/rvg== + dependencies: + "@types/events" "*" + "@types/node" "*" + +"@types/prettier@^2.0.0": + version "2.1.0" + resolved "https://registry.yarnpkg.com/@types/prettier/-/prettier-2.1.0.tgz#5f96562c1075ee715a5b138f0b7f591c1f40f6b8" + integrity sha512-hiYA88aHiEIgDmeKlsyVsuQdcFn3Z2VuFd/Xm/HCnGnPD8UFU5BM128uzzRVVGEzKDKYUrRsRH9S2o+NUy/3IA== "@types/stack-utils@^1.0.1": version "1.0.1" @@ -461,98 +757,97 @@ integrity sha512-l42BggppR6zLmpfU6fq9HEa2oGPEI8yrSPL3GITjfRInppYFahObbIQOQK3UGxEnyQpltZLaPe75046NOZQikw== "@types/yargs-parser@*": - version "13.0.0" - resolved "https://registry.yarnpkg.com/@types/yargs-parser/-/yargs-parser-13.0.0.tgz#453743c5bbf9f1bed61d959baab5b06be029b2d0" - integrity sha512-wBlsw+8n21e6eTd4yVv8YD/E3xq0O6nNnJIquutAsFGE7EyMKz7W6RNT6BRu1SmdgmlCZ9tb0X+j+D6HGr8pZw== - -"@types/yargs@^12.0.2", "@types/yargs@^12.0.9": - version "12.0.12" - resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-12.0.12.tgz#45dd1d0638e8c8f153e87d296907659296873916" - integrity sha512-SOhuU4wNBxhhTHxYaiG5NY4HBhDIDnJF60GU+2LqHAdKKer86//e4yg69aENCtQ04n0ovz+tq2YPME5t5yp4pw== + version "15.0.0" + resolved "https://registry.yarnpkg.com/@types/yargs-parser/-/yargs-parser-15.0.0.tgz#cb3f9f741869e20cce330ffbeb9271590483882d" + integrity sha512-FA/BWv8t8ZWJ+gEOnLLd8ygxH/2UFbAvgEonyfN6yWGLKc7zVjbpl2Y4CTjid9h2RfgPP6SEt6uHwEOply00yw== "@types/yargs@^13.0.0": - version "13.0.0" - resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-13.0.0.tgz#d2acb3bec0047d8f648ebacdab6b928a900c42c4" - integrity sha512-hY0o+kcz9M6kH32NUeb6VURghqMuCVkiUx+8Btsqhj4Hhov/hVGUx9DmBJeIkzlp1uAQK4wngQBCjqWdUUkFyA== + version "13.0.10" + resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-13.0.10.tgz#e77bf3fc73c781d48c2eb541f87c453e321e5f4b" + integrity sha512-MU10TSgzNABgdzKvQVW1nuuT+sgBMWeXNc3XOs5YXV5SDAK+PPja2eUuBNB9iqElu03xyEDqlnGw0jgl4nbqGQ== dependencies: "@types/yargs-parser" "*" -"@typescript-eslint/typescript-estree@^1.9.0": - version "1.12.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-1.12.0.tgz#d8dd0a7cffb5e3c0c3e98714042d83e316dfc9a9" - integrity sha512-nwN6yy//XcVhFs0ZyU+teJHB8tbCm7AIA8mu6E2r5hu6MajwYBY3Uwop7+rPZWUN/IUOHpL8C+iUPMDVYUU3og== +"@types/yargs@^15.0.0": + version "15.0.5" + resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-15.0.5.tgz#947e9a6561483bdee9adffc983e91a6902af8b79" + integrity sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w== dependencies: - lodash.unescape "4.0.1" - semver "5.5.0" - -abab@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/abab/-/abab-2.0.0.tgz#aba0ab4c5eee2d4c79d3487d85450fb2376ebb0f" - integrity sha512-sY5AXXVZv4Y1VACTtR11UJCPHHudgY5i26Qj5TypE6DKlIApbwb5uqhXcJ5UUGbvZNRh7EeIoW+LrJumBsKp7w== - -abbrev@1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" - integrity sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q== + "@types/yargs-parser" "*" -acorn-globals@^4.1.0: - version "4.3.2" - resolved "https://registry.yarnpkg.com/acorn-globals/-/acorn-globals-4.3.2.tgz#4e2c2313a597fd589720395f6354b41cd5ec8006" - integrity sha512-BbzvZhVtZP+Bs1J1HcwrQe8ycfO0wStkSGxuul3He3GkHOIZ6eTqOkPuw9IP1X3+IkOo4wiJmwkobzXYz4wewQ== +"@typescript-eslint/typescript-estree@^2.29.0": + version "2.34.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-2.34.0.tgz#14aeb6353b39ef0732cc7f1b8285294937cf37d5" + integrity sha512-OMAr+nJWKdlVM9LOqCqh3pQQPwxHAN7Du8DR6dmwCrAmxtiXQnhHJ6tBNtf+cggqfo51SG/FCwnKhXCIM7hnVg== dependencies: - acorn "^6.0.1" - acorn-walk "^6.0.1" + debug "^4.1.1" + eslint-visitor-keys "^1.1.0" + glob "^7.1.6" + is-glob "^4.0.1" + lodash "^4.17.15" + semver "^7.3.2" + tsutils "^3.17.1" + +"@vercel/ncc@^0.24.0": + version "0.24.0" + resolved "https://registry.yarnpkg.com/@vercel/ncc/-/ncc-0.24.0.tgz#a2e8783a185caa99b5d8961a57dfc9665de16296" + integrity sha512-crqItMcIwCkvdXY/V3/TzrHJQx6nbIaRqE1cOopJhgGX6izvNov40SmD//nS5flfEvdK54YGjwVVq+zG6crjOg== + +abab@^2.0.3: + version "2.0.5" + resolved "https://registry.yarnpkg.com/abab/-/abab-2.0.5.tgz#c0b678fb32d60fc1219c784d6a826fe385aeb79a" + integrity sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q== -acorn-walk@^6.0.1: - version "6.2.0" - resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-6.2.0.tgz#123cb8f3b84c2171f1f7fb252615b1c78a6b1a8c" - integrity sha512-7evsyfH1cLOCdAzZAd43Cic04yKydNx0cF+7tiA19p1XnLLPU4dpCQOqpjqwokFe//vS0QqfqqjCS2JkiIs0cA== +acorn-globals@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/acorn-globals/-/acorn-globals-6.0.0.tgz#46cdd39f0f8ff08a876619b55f5ac8a6dc770b45" + integrity sha512-ZQl7LOWaF5ePqqcX4hLuv/bLXYQNfNWw2c0/yX/TsPRKamzHcTGQnlCjHT3TsmkOUVEPS3crCxiPfdzE/Trlhg== + dependencies: + acorn "^7.1.1" + acorn-walk "^7.1.1" -acorn@^5.5.3: - version "5.7.3" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-5.7.3.tgz#67aa231bf8812974b85235a96771eb6bd07ea279" - integrity sha512-T/zvzYRfbVojPWahDsE5evJdHb3oJoQfFbsrKM7w5Zcs++Tr257tia3BmMP8XYVjp1S9RZXQMh7gao96BlqZOw== +acorn-walk@^7.1.1: + version "7.2.0" + resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-7.2.0.tgz#0de889a601203909b0fbe07b8938dc21d2e967bc" + integrity sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA== -acorn@^6.0.1: - version "6.2.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.2.0.tgz#67f0da2fc339d6cfb5d6fb244fd449f33cd8bbe3" - integrity sha512-8oe72N3WPMjA+2zVG71Ia0nXZ8DpQH+QyyHO+p06jT8eg8FGG3FbcUIi8KziHlAfheJQZeoqbvq1mQSQHXKYLw== +acorn@^7.1.1: + version "7.4.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.4.0.tgz#e1ad486e6c54501634c6c397c5c121daa383607c" + integrity sha512-+G7P8jJmCHr+S+cLfQxygbWhXy+8YTVGzAkpEbcLo2mLoL7tij/VG41QSHACSf5QgYRhMZYHuNc6drJaO0Da+w== -ajv@^6.5.5: - version "6.10.1" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.10.1.tgz#ebf8d3af22552df9dd049bfbe50cc2390e823593" - integrity sha512-w1YQaVGNC6t2UCPjEawK/vo/dG8OOrVtUmhBT1uJJYxbl5kU2Tj3v6LGqBcsysN1yhuCStJCCA3GqdvKY8sqXQ== +ajv@^6.12.3: + version "6.12.4" + resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.4.tgz#0614facc4522127fa713445c6bfd3ebd376e2234" + integrity sha512-eienB2c9qVQs2KWexhkrdMLVDoIQCz5KSeLxwg9Lzk4DOfBtIK9PQwwufcsn1jjGuf9WZmqPMbGxOzfcuphJCQ== dependencies: - fast-deep-equal "^2.0.1" + fast-deep-equal "^3.1.1" fast-json-stable-stringify "^2.0.0" json-schema-traverse "^0.4.1" uri-js "^4.2.2" -ansi-escapes@^3.0.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-3.2.0.tgz#8780b98ff9dbf5638152d1f1fe5c1d7b4442976b" - integrity sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ== +ansi-escapes@^4.2.1: + version "4.3.1" + resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.1.tgz#a5c47cc43181f1f38ffd7076837700d395522a61" + integrity sha512-JWF7ocqNrp8u9oqpgV+wH5ftbt+cfvv+PTjOvKLT3AdYly/LmORARfEVT1iyjwN+4MqE5UmVKoAdIBqeoCHgLA== + dependencies: + type-fest "^0.11.0" ansi-regex@^0.2.0, ansi-regex@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-0.2.1.tgz#0d8e946967a3d8143f93e24e298525fc1b2235f9" integrity sha1-DY6UaWej2BQ/k+JOKYUl/BsiNfk= -ansi-regex@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" - integrity sha1-w7M6te42DYbg5ijwRorn7yfWVN8= - -ansi-regex@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998" - integrity sha1-7QMXwyIGT3lGbAKWa922Bas32Zg= - -ansi-regex@^4.0.0, ansi-regex@^4.1.0: +ansi-regex@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.0.tgz#8b9f8f08cf1acb843756a839ca8c7e3168c51997" integrity sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg== +ansi-regex@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.0.tgz#388539f55179bf39339c81af30a654d69f87cb75" + integrity sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg== + ansi-styles@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-1.1.0.tgz#eaecbf66cd706882760b2f4691582b8f55d7a7de" @@ -565,6 +860,14 @@ ansi-styles@^3.2.0, ansi-styles@^3.2.1: dependencies: color-convert "^1.9.0" +ansi-styles@^4.0.0, ansi-styles@^4.1.0: + version "4.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.2.1.tgz#90ae75c424d008d2624c5bf29ead3177ebfcf359" + integrity sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA== + dependencies: + "@types/color-name" "^1.1.1" + color-convert "^2.0.1" + anymatch@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-2.0.0.tgz#bcb24b4f37934d9aa7ac17b4adaf89e7c76ef2eb" @@ -573,28 +876,40 @@ anymatch@^2.0.0: micromatch "^3.1.4" normalize-path "^2.1.1" +anymatch@^3.0.3: + version "3.1.1" + resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.1.tgz#c55ecf02185e2469259399310c173ce31233b142" + integrity sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg== + dependencies: + normalize-path "^3.0.0" + picomatch "^2.0.4" + app-module-path@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/app-module-path/-/app-module-path-2.2.0.tgz#641aa55dfb7d6a6f0a8141c4b9c0aa50b6c24dd5" integrity sha1-ZBqlXft9am8KgUHEucCqULbCTdU= -aproba@^1.0.3: - version "1.2.0" - resolved "https://registry.yarnpkg.com/aproba/-/aproba-1.2.0.tgz#6802e6264efd18c790a1b0d517f0f2627bf2c94a" - integrity sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw== +arg@^4.1.0: + version "4.1.3" + resolved "https://registry.yarnpkg.com/arg/-/arg-4.1.3.tgz#269fc7ad5b8e42cb63c896d5666017261c144089" + integrity sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA== -are-we-there-yet@~1.1.2: - version "1.1.5" - resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-1.1.5.tgz#4b35c2944f062a8bfcda66410760350fe9ddfc21" - integrity sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w== +argparse@^1.0.7: + version "1.0.10" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" + integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== dependencies: - delegates "^1.0.0" - readable-stream "^2.0.6" + sprintf-js "~1.0.2" -arg@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/arg/-/arg-4.1.0.tgz#583c518199419e0037abb74062c37f8519e575f0" - integrity sha512-ZWc51jO3qegGkVh8Hwpv636EkbesNV5ZNQPCtRa+0qytRYPEs9IYT9qITY9buezqUH5uqyzlWLcufrzU2rffdg== +args@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/args/-/args-5.0.1.tgz#4bf298df90a4799a09521362c579278cc2fdd761" + integrity sha512-1kqmFCFsPffavQFGt8OxJdIcETti99kySRUPMpOhaGjL6mRJn8HFU1OxKY5bMqfZKUwTQc1mZkAjmGYaVOHFtQ== + dependencies: + camelcase "5.0.0" + chalk "2.4.2" + leven "2.1.0" + mri "1.1.4" arr-diff@^4.0.0: version "4.0.0" @@ -611,11 +926,6 @@ arr-union@^3.1.0: resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-3.1.0.tgz#e39b09aea9def866a8f206e288af63919bae39c4" integrity sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ= -array-equal@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/array-equal/-/array-equal-1.0.0.tgz#8c2a5ef2472fd9ea742b04c77a75093ba2757c93" - integrity sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM= - array-unique@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428" @@ -638,82 +948,95 @@ assign-symbols@^1.0.0: resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367" integrity sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c= -ast-module-types@^2.3.1, ast-module-types@^2.3.2, ast-module-types@^2.4.0: - version "2.5.0" - resolved "https://registry.yarnpkg.com/ast-module-types/-/ast-module-types-2.5.0.tgz#44b8bcd51684329a77f2af6b2587df9ea6b4d5ff" - integrity sha512-dP6vhvatex3Q+OThhvcyGRvHn4noQBg1b8lCNKUAFL05up80hr2pAExveU3YQNDGMhfNPhQit/vzIkkvBPbSXw== - -astral-regex@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-1.0.0.tgz#6c8c3fb827dd43ee3918f27b82782ab7658a6fd9" - integrity sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg== - -async-limiter@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/async-limiter/-/async-limiter-1.0.0.tgz#78faed8c3d074ab81f22b4e985d79e8738f720f8" - integrity sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg== +ast-module-types@^2.3.1, ast-module-types@^2.3.2, ast-module-types@^2.4.0, ast-module-types@^2.6.0: + version "2.6.0" + resolved "https://registry.yarnpkg.com/ast-module-types/-/ast-module-types-2.6.0.tgz#f9f367fd273bbe01e52f2c51b5f46b65801d5d7f" + integrity sha512-zXSoVaMrf2R+r+ISid5/9a8SXm1LLdkhHzh6pSRhj9jklzruOOl1hva1YmFT33wAstg/f9ZndJAlq1BSrFLSGA== asynckit@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" integrity sha1-x57Zf380y48robyXkLzDZkdLS3k= -atob-lite@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/atob-lite/-/atob-lite-2.0.0.tgz#0fef5ad46f1bd7a8502c65727f0367d5ee43d696" - integrity sha1-D+9a1G8b16hQLGVyfwNn1e5D1pY= - -atob@^2.1.1: +atob@^2.1.2: version "2.1.2" resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9" integrity sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg== +atomic-sleep@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/atomic-sleep/-/atomic-sleep-1.0.0.tgz#eb85b77a601fc932cfe432c5acd364a9e2c9075b" + integrity sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ== + aws-sign2@~0.7.0: version "0.7.0" resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8" integrity sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg= aws4@^1.8.0: - version "1.8.0" - resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.8.0.tgz#f0e003d9ca9e7f59c7a508945d7b2ef9a04a542f" - integrity sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ== - -babel-jest@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-24.8.0.tgz#5c15ff2b28e20b0f45df43fe6b7f2aae93dba589" - integrity sha512-+5/kaZt4I9efoXzPlZASyK/lN9qdRKmmUav9smVc0ruPQD7IsfucQ87gpOE8mn2jbDuS6M/YOW6n3v9ZoIfgnw== - dependencies: - "@jest/transform" "^24.8.0" - "@jest/types" "^24.8.0" - "@types/babel__core" "^7.1.0" - babel-plugin-istanbul "^5.1.0" - babel-preset-jest "^24.6.0" - chalk "^2.4.2" - slash "^2.0.0" - -babel-plugin-istanbul@^5.1.0: - version "5.1.4" - resolved "https://registry.yarnpkg.com/babel-plugin-istanbul/-/babel-plugin-istanbul-5.1.4.tgz#841d16b9a58eeb407a0ddce622ba02fe87a752ba" - integrity sha512-dySz4VJMH+dpndj0wjJ8JPs/7i1TdSPb1nRrn56/92pKOF9VKC1FMFJmMXjzlGGusnCAqujP6PBCiKq0sVA+YQ== - dependencies: - find-up "^3.0.0" - istanbul-lib-instrument "^3.3.0" - test-exclude "^5.2.3" - -babel-plugin-jest-hoist@^24.6.0: - version "24.6.0" - resolved "https://registry.yarnpkg.com/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-24.6.0.tgz#f7f7f7ad150ee96d7a5e8e2c5da8319579e78019" - integrity sha512-3pKNH6hMt9SbOv0F3WVmy5CWQ4uogS3k0GY5XLyQHJ9EGpAT9XWkFd2ZiXXtkwFHdAHa5j7w7kfxSP5lAIwu7w== + version "1.10.1" + resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.10.1.tgz#e1e82e4f3e999e2cfd61b161280d16a111f86428" + integrity sha512-zg7Hz2k5lI8kb7U32998pRRFin7zJlkfezGJjUc2heaD4Pw2wObakCDVzkKztTm/Ln7eiVvYsjqak0Ed4LkMDA== + +babel-jest@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-26.3.0.tgz#10d0ca4b529ca3e7d1417855ef7d7bd6fc0c3463" + integrity sha512-sxPnQGEyHAOPF8NcUsD0g7hDCnvLL2XyblRBcgrzTWBB/mAIpWow3n1bEL+VghnnZfreLhFSBsFluRoK2tRK4g== + dependencies: + "@jest/transform" "^26.3.0" + "@jest/types" "^26.3.0" + "@types/babel__core" "^7.1.7" + babel-plugin-istanbul "^6.0.0" + babel-preset-jest "^26.3.0" + chalk "^4.0.0" + graceful-fs "^4.2.4" + slash "^3.0.0" + +babel-plugin-istanbul@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/babel-plugin-istanbul/-/babel-plugin-istanbul-6.0.0.tgz#e159ccdc9af95e0b570c75b4573b7c34d671d765" + integrity sha512-AF55rZXpe7trmEylbaE1Gv54wn6rwU03aptvRoVIGP8YykoSxqdVLV1TfwflBCE/QtHmqtP8SWlTENqbK8GCSQ== dependencies: + "@babel/helper-plugin-utils" "^7.0.0" + "@istanbuljs/load-nyc-config" "^1.0.0" + "@istanbuljs/schema" "^0.1.2" + istanbul-lib-instrument "^4.0.0" + test-exclude "^6.0.0" + +babel-plugin-jest-hoist@^26.2.0: + version "26.2.0" + resolved "https://registry.yarnpkg.com/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-26.2.0.tgz#bdd0011df0d3d513e5e95f76bd53b51147aca2dd" + integrity sha512-B/hVMRv8Nh1sQ1a3EY8I0n4Y1Wty3NrR5ebOyVT302op+DOAau+xNEImGMsUWOC3++ZlMooCytKz+NgN8aKGbA== + dependencies: + "@babel/template" "^7.3.3" + "@babel/types" "^7.3.3" + "@types/babel__core" "^7.0.0" "@types/babel__traverse" "^7.0.6" -babel-preset-jest@^24.6.0: - version "24.6.0" - resolved "https://registry.yarnpkg.com/babel-preset-jest/-/babel-preset-jest-24.6.0.tgz#66f06136eefce87797539c0d63f1769cc3915984" - integrity sha512-pdZqLEdmy1ZK5kyRUfvBb2IfTPb2BUvIJczlPspS8fWmBQslNNDBqVfh7BW5leOVJMDZKzjD8XEyABTk6gQ5yw== - dependencies: - "@babel/plugin-syntax-object-rest-spread" "^7.0.0" - babel-plugin-jest-hoist "^24.6.0" +babel-preset-current-node-syntax@^0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-0.1.3.tgz#b4b547acddbf963cba555ba9f9cbbb70bfd044da" + integrity sha512-uyexu1sVwcdFnyq9o8UQYsXwXflIh8LvrF5+cKrYam93ned1CStffB3+BEcsxGSgagoA3GEyjDqO4a/58hyPYQ== + dependencies: + "@babel/plugin-syntax-async-generators" "^7.8.4" + "@babel/plugin-syntax-bigint" "^7.8.3" + "@babel/plugin-syntax-class-properties" "^7.8.3" + "@babel/plugin-syntax-import-meta" "^7.8.3" + "@babel/plugin-syntax-json-strings" "^7.8.3" + "@babel/plugin-syntax-logical-assignment-operators" "^7.8.3" + "@babel/plugin-syntax-nullish-coalescing-operator" "^7.8.3" + "@babel/plugin-syntax-numeric-separator" "^7.8.3" + "@babel/plugin-syntax-object-rest-spread" "^7.8.3" + "@babel/plugin-syntax-optional-catch-binding" "^7.8.3" + "@babel/plugin-syntax-optional-chaining" "^7.8.3" + +babel-preset-jest@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/babel-preset-jest/-/babel-preset-jest-26.3.0.tgz#ed6344506225c065fd8a0b53e191986f74890776" + integrity sha512-5WPdf7nyYi2/eRxCbVrE1kKCWxgWY4RsPEbdJWFm7QsesFGqjdkyLeu1zRkwM1cxK6EPIlNd6d2AxLk7J+t4pw== + dependencies: + babel-plugin-jest-hoist "^26.2.0" + babel-preset-current-node-syntax "^0.1.3" balanced-match@^1.0.0: version "1.0.0" @@ -740,7 +1063,7 @@ bcrypt-pbkdf@^1.0.0: dependencies: tweetnacl "^0.14.3" -before-after-hook@^2.0.0: +before-after-hook@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.1.0.tgz#b6c03487f44e24200dd30ca5e6a1979c5d2fb635" integrity sha512-IWIbu7pMqyw3EAJHzzHbWa85b6oud/yfKYg5rqB5hNE8CeMi3nX+2C2sj0HswfblST86hpVEOAb9x34NZd6P7A== @@ -755,6 +1078,14 @@ bistre@^1.0.1: stream-combiner "^0.2.0" through2 "^0.5.1" +bl@^2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/bl/-/bl-2.2.1.tgz#8c11a7b730655c5d56898cdc871224f40fd901d5" + integrity sha512-6Pesp1w0DEX1N550i/uGV/TqucVL4AM/pgThFSN/Qq9si1/DF9aIHs1BxD8V/QU0HoeHO6cQRTAuYnLPKq1e4g== + dependencies: + readable-stream "^2.3.5" + safe-buffer "^5.1.1" + bole@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/bole/-/bole-3.0.2.tgz#bc8a483ca94049da9b837c1ad11cdfebee6e0514" @@ -787,17 +1118,17 @@ braces@^2.3.1: split-string "^3.0.2" to-regex "^3.0.1" -browser-process-hrtime@^0.1.2: - version "0.1.3" - resolved "https://registry.yarnpkg.com/browser-process-hrtime/-/browser-process-hrtime-0.1.3.tgz#616f00faef1df7ec1b5bf9cfe2bdc3170f26c7b4" - integrity sha512-bRFnI4NnjO6cnyLmOV/7PVoDEMJChlcfN0z4s1YMBY989/SvlfMI1lgCnkFUs53e9gQF+w7qu7XdllSTiSl8Aw== - -browser-resolve@^1.11.3: - version "1.11.3" - resolved "https://registry.yarnpkg.com/browser-resolve/-/browser-resolve-1.11.3.tgz#9b7cbb3d0f510e4cb86bdbd796124d28b5890af6" - integrity sha512-exDi1BYWB/6raKHmDTCicQfTkqwN5fioMFV4j8BsfMU4R2DK/QfZfK7kOVkmWCNANf0snkBzqGqAJBao9gZMdQ== +braces@^3.0.1: + version "3.0.2" + resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" + integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== dependencies: - resolve "1.1.7" + fill-range "^7.0.1" + +browser-process-hrtime@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz#3c9b4b7d782c8121e56f10106d84c0d0ffc94626" + integrity sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow== bs-logger@0.x: version "0.2.6" @@ -806,27 +1137,22 @@ bs-logger@0.x: dependencies: fast-json-stable-stringify "2.x" -bser@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/bser/-/bser-2.1.0.tgz#65fc784bf7f87c009b973c12db6546902fa9c7b5" - integrity sha512-8zsjWrQkkBoLK6uxASk1nJ2SKv97ltiGDo6A3wA0/yRPz+CwmEyDo0hUrhIuukG2JHpAl3bvFIixw2/3Hi0DOg== +bser@2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/bser/-/bser-2.1.1.tgz#e6787da20ece9d07998533cfd9de6f5c38f4bc05" + integrity sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ== dependencies: node-int64 "^0.4.0" bson-objectid@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/bson-objectid/-/bson-objectid-1.3.0.tgz#f0f4c7c949fece975f12790510d75d7fe39fb456" - integrity sha512-YcB+lRJEEEIcHNLKyhmHujW7OCVE3+xr9IpEhlprBZnXgF3hqeePeexIsAaOtu1SbkgZRlJVUxvYZ3ngUOyIew== - -bson@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/bson/-/bson-1.1.1.tgz#4330f5e99104c4e751e7351859e2d408279f2f13" - integrity sha512-jCGVYLoYMHDkOsbwJZBCqwMHyH4c+wzgI9hG7Z6SZJRXWr+x58pdIbm2i9a/jFGCkRJqRUr8eoI7lDWa0hTkxg== + version "1.3.1" + resolved "https://registry.yarnpkg.com/bson-objectid/-/bson-objectid-1.3.1.tgz#11e4ce4c3419161fd388113781bb62c1dfbce34b" + integrity sha512-eQBNQXsisEAXlwiSy8zRNZdW2xDBJaEVkTPbodYR9hGxxtE548Qq7ilYOd8WAQ86xF7NRUdiWSQ1pa/TkKiE2A== -btoa-lite@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/btoa-lite/-/btoa-lite-1.0.0.tgz#337766da15801210fdd956c22e9c6891ab9d0337" - integrity sha1-M3dm2hWAEhD92VbCLpxokaudAzc= +bson@^1.1.4: + version "1.1.5" + resolved "https://registry.yarnpkg.com/bson/-/bson-1.1.5.tgz#2aaae98fcdf6750c0848b0cba1ddec3c73060a34" + integrity sha512-kDuEzldR21lHciPQAIulLs1LZlCXdLziXI6Mb/TDkwXhb//UORJNPXgcRs2CuO4H0DcMkpfT3/ySsP3unoZjBg== buffer-from@1.x, buffer-from@^1.0.0: version "1.1.1" @@ -853,16 +1179,21 @@ callsites@^3.0.0: resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== -camelcase@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-4.1.0.tgz#d545635be1e33c542649c69173e5de6acfae34dd" - integrity sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0= +camelcase@5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.0.0.tgz#03295527d58bd3cd4aa75363f35b2e8d97be2f42" + integrity sha512-faqwZqnWxbxn+F1d399ygeamQNy3lPp/H9H6rNrqYh4FSVCtcY+3cub1MxA8o9mDd55mM8Aghuu/kuyYA6VTsA== -camelcase@^5.0.0: +camelcase@^5.0.0, camelcase@^5.3.1: version "5.3.1" resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320" integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== +camelcase@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.0.0.tgz#5259f7c30e35e278f1bdc2a4d91230b37cad981e" + integrity sha512-8KMDF1Vz2gzOq54ONPJS65IvTUaB1cHJ2DMM7MbPmLZljDH1qpzzLsWdiN9pHh6qvkRVDTi/07+eNGch/oLU4w== + capture-exit@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/capture-exit/-/capture-exit-2.0.0.tgz#fb953bfaebeb781f62898239dabb426d08a509a4" @@ -875,6 +1206,15 @@ caseless@~0.12.0: resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc" integrity sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw= +chalk@2.4.2, chalk@^2.0.0, chalk@^2.4.2: + version "2.4.2" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" + integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== + dependencies: + ansi-styles "^3.2.1" + escape-string-regexp "^1.0.5" + supports-color "^5.3.0" + chalk@^0.5.1: version "0.5.1" resolved "https://registry.yarnpkg.com/chalk/-/chalk-0.5.1.tgz#663b3a648b68b55d04690d49167aa837858f2174" @@ -886,19 +1226,26 @@ chalk@^0.5.1: strip-ansi "^0.3.0" supports-color "^0.2.0" -chalk@^2.0.0, chalk@^2.0.1, chalk@^2.4.1, chalk@^2.4.2: - version "2.4.2" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" - integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== +chalk@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-3.0.0.tgz#3f73c2bf526591f574cc492c51e2456349f844e4" + integrity sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg== dependencies: - ansi-styles "^3.2.1" - escape-string-regexp "^1.0.5" - supports-color "^5.3.0" + ansi-styles "^4.1.0" + supports-color "^7.1.0" -chownr@^1.1.1: - version "1.1.2" - resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.2.tgz#a18f1e0b269c8a6a5d3c86eb298beb14c3dd7bf6" - integrity sha512-GkfeAQh+QNy3wquu9oIZr6SS5x7wGdSgNQvD10X3r+AZr1Oys22HW8kAmDMvNg2+Dm0TeGaEuO8gFwdBXxwO8A== +chalk@^4.0.0, chalk@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.0.tgz#4e14870a618d9e2edd97dd8345fd9d9dc315646a" + integrity sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A== + dependencies: + ansi-styles "^4.1.0" + supports-color "^7.1.0" + +char-regex@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/char-regex/-/char-regex-1.0.2.tgz#d744358226217f981ed58f479b1d6bcc29545dcf" + integrity sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw== ci-info@^2.0.0: version "2.0.0" @@ -915,26 +1262,17 @@ class-utils@^0.3.5: isobject "^3.0.0" static-extend "^0.1.1" -cli-cursor@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-2.1.0.tgz#b35dac376479facc3e94747d41d0d0f5238ffcb5" - integrity sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU= +cli-cursor@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-3.1.0.tgz#264305a7ae490d1d03bf0c9ba7c925d1753af307" + integrity sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw== dependencies: - restore-cursor "^2.0.0" - -cli-spinners@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-2.2.0.tgz#e8b988d9206c692302d8ee834e7a85c0144d8f77" - integrity sha512-tgU3fKwzYjiLEQgPMD9Jt+JjHVL9kW93FiIMX/l7rivvOD4/LL0Mf7gda3+4U2KJBloybwgj5KEoQgGRioMiKQ== + restore-cursor "^3.1.0" -cliui@^4.0.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-4.1.0.tgz#348422dbe82d800b3022eef4f6ac10bf2e4d1b49" - integrity sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ== - dependencies: - string-width "^2.1.1" - strip-ansi "^4.0.0" - wrap-ansi "^2.0.0" +cli-spinners@^2.2.0: + version "2.4.0" + resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-2.4.0.tgz#c6256db216b878cfba4720e719cec7cf72685d7f" + integrity sha512-sJAofoarcm76ZGpuooaO0eDy8saEy+YoZBLjC4h8srt4jeBnkYeOgqxgsJQTpyt2LjI5PTfLJHSL+41Yu4fEJA== cliui@^5.0.0: version "5.0.0" @@ -945,6 +1283,15 @@ cliui@^5.0.0: strip-ansi "^5.2.0" wrap-ansi "^5.1.0" +cliui@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-6.0.0.tgz#511d702c0c4e41ca156d7d0e96021f23e13225b1" + integrity sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ== + dependencies: + string-width "^4.2.0" + strip-ansi "^6.0.0" + wrap-ansi "^6.2.0" + clone@^1.0.2: version "1.0.4" resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.4.tgz#da309cc263df15994c688ca902179ca3c7cd7c7e" @@ -955,10 +1302,10 @@ co@^4.6.0: resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" integrity sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ= -code-point-at@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77" - integrity sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c= +collect-v8-coverage@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz#cc2c8e94fc18bbdffe64d6534570c8a673b27f59" + integrity sha512-iBPtljfCNcTKNAto0KEtDfZ3qzjJvqE3aTGZsbhjSBlorqpXJlaWWtPO35D+ZImoC3KWejX64o+yPGxhWSTzfg== collection-visit@^1.0.0: version "1.0.0" @@ -975,11 +1322,23 @@ color-convert@^1.9.0: dependencies: color-name "1.1.3" +color-convert@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" + integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== + dependencies: + color-name "~1.1.4" + color-name@1.1.3: version "1.1.3" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= +color-name@~1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" + integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== + combined-stream@^1.0.6, combined-stream@~1.0.6: version "1.0.8" resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" @@ -987,10 +1346,15 @@ combined-stream@^1.0.6, combined-stream@~1.0.6: dependencies: delayed-stream "~1.0.0" -commander@^2.13.0, commander@^2.15.1, commander@^2.16.0, commander@^2.19.0, commander@^2.8.1, commander@~2.20.0: - version "2.20.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.0.tgz#d58bb2b5c1ee8f87b0d340027e9e94e222c5a422" - integrity sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ== +commander@^2.13.0, commander@^2.16.0, commander@^2.19.0, commander@^2.20.3, commander@^2.8.1: + version "2.20.3" + resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" + integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== + +commander@^5.1.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/commander/-/commander-5.1.0.tgz#46abbd1652f8e059bddaef99bbdcb2ad9cf179ae" + integrity sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg== commondir@^1.0.1: version "1.0.1" @@ -1007,15 +1371,10 @@ concat-map@0.0.1: resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= -console-control-strings@^1.0.0, console-control-strings@~1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e" - integrity sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4= - -convert-source-map@^1.1.0, convert-source-map@^1.4.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.6.0.tgz#51b537a8c43e0f04dec1993bffcdd504e758ac20" - integrity sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A== +convert-source-map@^1.4.0, convert-source-map@^1.6.0, convert-source-map@^1.7.0: + version "1.7.0" + resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.7.0.tgz#17a2cb882d7f77d3490585e2ce6c524424a3a442" + integrity sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA== dependencies: safe-buffer "~5.1.1" @@ -1040,15 +1399,29 @@ cross-spawn@^6.0.0: shebang-command "^1.2.0" which "^1.2.9" -"cssom@>= 0.3.2 < 0.4.0", cssom@~0.3.6: +cross-spawn@^7.0.0: + version "7.0.3" + resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" + integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== + dependencies: + path-key "^3.1.0" + shebang-command "^2.0.0" + which "^2.0.1" + +cssom@^0.4.4: + version "0.4.4" + resolved "https://registry.yarnpkg.com/cssom/-/cssom-0.4.4.tgz#5a66cf93d2d0b661d80bf6a44fb65f5c2e4e0a10" + integrity sha512-p3pvU7r1MyyqbTk+WbNJIgJjG2VmTIaB10rI93LzVPrmDJKkzKYMtxxyAvQXR/NS6otuzveI7+7BBq3SjBS2mw== + +cssom@~0.3.6: version "0.3.8" resolved "https://registry.yarnpkg.com/cssom/-/cssom-0.3.8.tgz#9f1276f5b2b463f2114d3f2c75250af8c1a36f4a" integrity sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg== -cssstyle@^1.0.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/cssstyle/-/cssstyle-1.3.0.tgz#c36c466f7037fd30f03baa271b65f0f17b50585c" - integrity sha512-wXsoRfsRfsLVNaVzoKdqvEmK/5PFaEXNspVT22Ots6K/cnJdpoDKuQFw+qlMiXnmaif1OgeC466X1zISgAOcGg== +cssstyle@^2.2.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/cssstyle/-/cssstyle-2.3.0.tgz#ff665a0ddbdc31864b09647f34163443d90b0852" + integrity sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A== dependencies: cssom "~0.3.6" @@ -1059,14 +1432,19 @@ dashdash@^1.12.0: dependencies: assert-plus "^1.0.0" -data-urls@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/data-urls/-/data-urls-1.1.0.tgz#15ee0582baa5e22bb59c77140da8f9c76963bbfe" - integrity sha512-YTWYI9se1P55u58gL5GkQHW4P6VJBJ5iBT+B5a7i2Tjadhv52paJG0qHX4A0OR6/t52odI64KP2YvFpkDOi3eQ== +data-urls@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/data-urls/-/data-urls-2.0.0.tgz#156485a72963a970f5d5821aaf642bef2bf2db9b" + integrity sha512-X5eWTSXO/BJmpdIKCRuKUgSCgAN0OwliVK3yPKbwIWU1Tdw5BRajxlzMidvh+gwko9AfQ9zIj52pzF91Q3YAvQ== dependencies: - abab "^2.0.0" - whatwg-mimetype "^2.2.0" - whatwg-url "^7.0.0" + abab "^2.0.3" + whatwg-mimetype "^2.3.0" + whatwg-url "^8.0.0" + +dateformat@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-3.0.3.tgz#a6e37499a4d9a9cf85ef5872044d62901c9889ae" + integrity sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q== debug@^2.2.0, debug@^2.3.3: version "2.6.9" @@ -1075,13 +1453,6 @@ debug@^2.2.0, debug@^2.3.3: dependencies: ms "2.0.0" -debug@^3.2.6: - version "3.2.6" - resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.6.tgz#e83d17de16d8a7efb7717edbe5fb10135eee629b" - integrity sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ== - dependencies: - ms "^2.1.1" - debug@^4.0.0, debug@^4.0.1, debug@^4.1.0, debug@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/debug/-/debug-4.1.1.tgz#3b72260255109c6b589cee050f1d516139664791" @@ -1094,11 +1465,23 @@ decamelize@^1.2.0: resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" integrity sha1-9lNNFRSCabIDUue+4m9QH5oZEpA= +decimal.js@^10.2.0: + version "10.2.0" + resolved "https://registry.yarnpkg.com/decimal.js/-/decimal.js-10.2.0.tgz#39466113a9e036111d02f82489b5fd6b0b5ed231" + integrity sha512-vDPw+rDgn3bZe1+F/pyEwb1oMG2XTlRVgAa6B4KccTEpYgF8w6eQllVbQcfIJnZyvzFtFpxnpGtx8dd7DJp/Rw== + decode-uri-component@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545" integrity sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU= +decomment@^0.9.2: + version "0.9.3" + resolved "https://registry.yarnpkg.com/decomment/-/decomment-0.9.3.tgz#b913f32e5fe1113848f516caa5c7afefa9544d38" + integrity sha512-5skH5BfUL3n09RDmMVaHS1QGCiZRnl2nArUwmsE9JRY93Ueh3tihYl5wIrDdAuXnoFhxVis/DmRWREO2c6DG3w== + dependencies: + esprima "4.0.1" + deep-extend@^0.6.0: version "0.6.0" resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" @@ -1109,10 +1492,10 @@ deep-is@~0.1.3: resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" integrity sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ= -deepmerge@4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.0.0.tgz#3e3110ca29205f120d7cb064960a39c3d2087c09" - integrity sha512-YZ1rOP5+kHor4hMAH+HRQnBQHg+wvS1un1hAOuIcxcBy0hzcUf6Jg2a1w65kpoOUnurOfZbERwjI1TfZxNjcww== +deepmerge@^4.2.2: + version "4.2.2" + resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.2.2.tgz#44d2ea3679b8f4d4ffba33f03d865fc1e7bf4955" + integrity sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg== defaults@^1.0.3: version "1.0.3" @@ -1121,13 +1504,6 @@ defaults@^1.0.3: dependencies: clone "^1.0.2" -define-properties@^1.1.2: - version "1.1.3" - resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1" - integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ== - dependencies: - object-keys "^1.0.12" - define-property@^0.2.5: version "0.2.5" resolved "https://registry.yarnpkg.com/define-property/-/define-property-0.2.5.tgz#c35b1ef918ec3c990f9a5bc57be04aacec5c8116" @@ -1155,35 +1531,31 @@ delayed-stream@~1.0.0: resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= -delegates@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a" - integrity sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o= +denque@^1.4.1: + version "1.4.1" + resolved "https://registry.yarnpkg.com/denque/-/denque-1.4.1.tgz#6744ff7641c148c3f8a69c307e51235c1f4a37cf" + integrity sha512-OfzPuSZKGcgr96rf1oODnfjqBFmr1DVoc/TrItj3Ohe0Ah1C5WX5Baquw/9U9KovnQ88EqmJbD66rKYUQYN1tQ== -dependency-tree@^7.0.2: - version "7.0.2" - resolved "https://registry.yarnpkg.com/dependency-tree/-/dependency-tree-7.0.2.tgz#01df8bbdc51e41438f5bb93f4a53e1a9cf8301a1" - integrity sha512-yh3qCLHl/o/ZUPq14HUF6AGEbNTMyCAu92D6AmY3SEynJHkB25o3hTDzvt3Tu/KpR0093ATyrhr4aGwcx8NnVw== +dependency-tree@^7.2.1: + version "7.2.1" + resolved "https://registry.yarnpkg.com/dependency-tree/-/dependency-tree-7.2.1.tgz#41c8f6feb54a2ae32475c0158e8d2c2696bb7f54" + integrity sha512-nBxnjkqDW4LqAzBazy60V4lE0mAtIQ+oers/GIIvVvGYVdCD9+RNNd4G9jjstyz7ZFVg/j/OiYCvK5MjoVqA2w== dependencies: commander "^2.19.0" debug "^4.1.1" - filing-cabinet "^2.3.1" - precinct "^6.1.1" + filing-cabinet "^2.5.1" + precinct "^6.2.0" + typescript "^3.7.5" -deprecation@^2.0.0: +deprecation@^2.0.0, deprecation@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/deprecation/-/deprecation-2.3.1.tgz#6368cbdb40abf3373b525ac87e4a260c3a700919" integrity sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ== -detect-libc@^1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-1.0.3.tgz#fa137c4bd698edf55cd5cd02ac559f91a4c4ba9b" - integrity sha1-+hN8S9aY7fVc1c0CrFWfkaTEups= - -detect-newline@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/detect-newline/-/detect-newline-2.1.0.tgz#f41f1c10be4b00e87b5f13da680759f2c5bfd3e2" - integrity sha1-9B8cEL5LAOh7XxPaaAdZ8sW/0+I= +detect-newline@^3.0.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/detect-newline/-/detect-newline-3.1.0.tgz#576f5dfc63ae1a192ff192d8ad3af6308991b651" + integrity sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA== detective-amd@^3.0.0: version "3.0.0" @@ -1203,10 +1575,10 @@ detective-cjs@^3.1.1: ast-module-types "^2.4.0" node-source-walk "^4.0.0" -detective-es6@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/detective-es6/-/detective-es6-2.1.0.tgz#7848feaec92279d82f7b3a98d8e1f5d93483a0f7" - integrity sha512-QSHqKGOp/YBIfmIqKXaXeq2rlL+bp3bcIQMfZ+0PvKzRlELSOSZxKRvpxVcxlLuocQv4QnOfuWGniGrmPbz8MQ== +detective-es6@^2.1.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/detective-es6/-/detective-es6-2.2.0.tgz#8f2baba3f8cd90a5cfd748f5ac436f0158ed2585" + integrity sha512-fSpNY0SLER7/sVgQZ1NxJPwmc9uCTzNgdkQDhAaj8NPYwr7Qji9QBcmbNvtMCnuuOGMuKn3O7jv0An+/WRWJZQ== dependencies: node-source-walk "^4.0.0" @@ -1219,7 +1591,7 @@ detective-less@^1.0.2: gonzales-pe "^4.2.3" node-source-walk "^4.0.0" -detective-postcss@^3.0.0: +detective-postcss@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/detective-postcss/-/detective-postcss-3.0.1.tgz#511921951f66135e17d0ece2e7604c6e4966c9c6" integrity sha512-tfTS2GdpUal5NY0aCqI4dpEy8Xfr88AehYKB0iBIZvo8y2g3UsrcDnrp9PR2FbzoW7xD5Rip3NJW7eCSvtqdUw== @@ -1229,7 +1601,7 @@ detective-postcss@^3.0.0: postcss "^7.0.2" postcss-values-parser "^1.5.0" -detective-sass@^3.0.0: +detective-sass@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/detective-sass/-/detective-sass-3.0.1.tgz#496b819efd1f5c4dd3f0e19b43a8634bdd6927c4" integrity sha512-oSbrBozRjJ+QFF4WJFbjPQKeakoaY1GiR380NPqwdbWYd5wfl5cLWv0l6LsJVqrgWfFN1bjFqSeo32Nxza8Lbw== @@ -1238,7 +1610,7 @@ detective-sass@^3.0.0: gonzales-pe "^4.2.3" node-source-walk "^4.0.0" -detective-scss@^2.0.0: +detective-scss@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/detective-scss/-/detective-scss-2.0.1.tgz#06f8c21ae6dedad1fccc26d544892d968083eaf8" integrity sha512-VveyXW4WQE04s05KlJ8K0bG34jtHQVgTc9InspqoQxvnelj/rdgSAy7i2DXAazyQNFKlWSWbS+Ro2DWKFOKTPQ== @@ -1252,41 +1624,47 @@ detective-stylus@^1.0.0: resolved "https://registry.yarnpkg.com/detective-stylus/-/detective-stylus-1.0.0.tgz#50aee7db8babb990381f010c63fabba5b58e54cd" integrity sha1-UK7n24uruZA4HwEMY/q7pbWOVM0= -detective-typescript@^5.1.1: - version "5.4.0" - resolved "https://registry.yarnpkg.com/detective-typescript/-/detective-typescript-5.4.0.tgz#277b68308e3dacb10ca7f323e2e6de4cb940c905" - integrity sha512-P2K1R2F5xH65tGma/ZgETbZzicURCZnmO6GqJWT8Ae1auU0Rck34ITgFXrAHcTausaH306pSICJav7frQwy7RA== +detective-typescript@^5.8.0: + version "5.8.0" + resolved "https://registry.yarnpkg.com/detective-typescript/-/detective-typescript-5.8.0.tgz#c46776571e26bad6c9ada020cb3cb4e5625d1311" + integrity sha512-SrsUCfCaDTF64QVMHMidRal+kmkbIc5zP8cxxZPsomWx9vuEUjBlSJNhf7/ypE5cLdJJDI4qzKDmyzqQ+iz/xg== dependencies: - "@typescript-eslint/typescript-estree" "^1.9.0" + "@typescript-eslint/typescript-estree" "^2.29.0" + ast-module-types "^2.6.0" node-source-walk "^4.2.0" - typescript "^3.4.5" + typescript "^3.8.3" -diff-sequences@^24.3.0: - version "24.3.0" - resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-24.3.0.tgz#0f20e8a1df1abddaf4d9c226680952e64118b975" - integrity sha512-xLqpez+Zj9GKSnPWS0WZw1igGocZ+uua8+y+5dDNTT934N3QuY1sp2LkHzwiaYQGz60hMq0pjAshdeXm5VUOEw== +diff-sequences@^25.2.6: + version "25.2.6" + resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-25.2.6.tgz#5f467c00edd35352b7bca46d7927d60e687a76dd" + integrity sha512-Hq8o7+6GaZeoFjtpgvRBUknSXNeJiCx7V9Fr94ZMljNiCr9n9L8H8aJqgWOQiDDGdyn29fRNcDdRVJ5fdyihfg== + +diff-sequences@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-26.3.0.tgz#62a59b1b29ab7fd27cef2a33ae52abe73042d0a2" + integrity sha512-5j5vdRcw3CNctePNYN0Wy2e/JbWT6cAYnXv5OuqPhDpyCGc0uLu2TK0zOCJWNB9kOIfYMSpIulRaDgIi4HJ6Ig== diff@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.1.tgz#0c667cb467ebbb5cea7f14f135cc2dba7780a8ff" - integrity sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q== + version "4.0.2" + resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d" + integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== -domexception@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/domexception/-/domexception-1.0.1.tgz#937442644ca6a31261ef36e3ec677fe805582c90" - integrity sha512-raigMkn7CJNNo6Ihro1fzG7wr3fHuYVytzquZKX5n0yizGsTcYgzdIUwj1X9pK0VvjeihV+XiclP+DjwbsSKug== +domexception@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/domexception/-/domexception-2.0.1.tgz#fb44aefba793e1574b0af6aed2801d057529f304" + integrity sha512-yxJ2mFy/sibVQlu5qHjOkf9J3K6zgmCxgJ94u2EdvDOV09H+32LtRswEcUsmUWN72pVLOEnTSRaIVVzVQgS0dg== dependencies: - webidl-conversions "^4.0.2" + webidl-conversions "^5.0.0" -dotenv@^8.0.0: - version "8.0.0" - resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-8.0.0.tgz#ed310c165b4e8a97bb745b0a9d99c31bda566440" - integrity sha512-30xVGqjLjiUOArT4+M5q9sYdvuR4riM6yK9wMcas9Vbp6zZa+ocC9dp6QoftuhTPhFAiLK/0C5Ni2nou/Bk8lg== +dotenv@^8.2.0: + version "8.2.0" + resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-8.2.0.tgz#97e619259ada750eea3e4ea3e26bceea5424b16a" + integrity sha512-8sJ78ElpbDJBHNeBzUbUVLsqKdccaa/BXF1uPTw3GrvQTBgrQrtObr2mUrE38vzYd8cEv+m/JBfDLioYcfXoaw== duplexer@~0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1" - integrity sha1-rOb/gIwc5mtX0ev5eXessCM0z8E= + version "0.1.2" + resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.2.tgz#3abe43aef3835f8ae077d136ddce0f276b0400e6" + integrity sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg== ecc-jsbn@~0.1.1: version "0.1.2" @@ -1296,25 +1674,35 @@ ecc-jsbn@~0.1.1: jsbn "~0.1.0" safer-buffer "^2.1.0" +emittery@^0.7.1: + version "0.7.1" + resolved "https://registry.yarnpkg.com/emittery/-/emittery-0.7.1.tgz#c02375a927a40948c0345cc903072597f5270451" + integrity sha512-d34LN4L6h18Bzz9xpoku2nPwKxCPlPMr3EEKTkoEBi+1/+b0lcRkRJ1UVyyZaKNeqGR3swcGl6s390DNO4YVgQ== + emoji-regex@^7.0.1: version "7.0.3" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156" integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA== +emoji-regex@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" + integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== + end-of-stream@^1.1.0: - version "1.4.1" - resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.1.tgz#ed29634d19baba463b6ce6b80a37213eab71ec43" - integrity sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q== + version "1.4.4" + resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0" + integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q== dependencies: once "^1.4.0" enhanced-resolve@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz#41c7e0bfdfe74ac1ffe1e57ad6a5c6c9f3742a7f" - integrity sha512-F/7vkyTtyc/llOIn8oWclcB25KdRaiPBpZYDgJHgh/UHtpgT2p2eldQgtQnLtUvfMKPKxbRaQM/hHkvLHt1Vng== + version "4.3.0" + resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-4.3.0.tgz#3b806f3bfafc1ec7de69551ef93cca46c1704126" + integrity sha512-3e87LvavsdxyoCfGusJnrZ5G8SLPOFeHSNpZI/ATL9a5leXo2k0w6MKnbqhdBad9qTobSfB20Ld7UmgoNbAZkQ== dependencies: graceful-fs "^4.1.2" - memory-fs "^0.4.0" + memory-fs "^0.5.0" tapable "^1.0.0" errno@^0.1.3: @@ -1331,68 +1719,52 @@ error-ex@^1.3.1: dependencies: is-arrayish "^0.2.1" -es-abstract@^1.5.1: - version "1.13.0" - resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.13.0.tgz#ac86145fdd5099d8dd49558ccba2eaf9b88e24e9" - integrity sha512-vDZfg/ykNxQVwup/8E1BZhVzFfBxs9NqMzGcvIJrqg5k2/5Za2bWo40dK2J1pgLngZ7c+Shh8lwYtLGyrwPutg== - dependencies: - es-to-primitive "^1.2.0" - function-bind "^1.1.1" - has "^1.0.3" - is-callable "^1.1.4" - is-regex "^1.0.4" - object-keys "^1.0.12" - -es-to-primitive@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.0.tgz#edf72478033456e8dda8ef09e00ad9650707f377" - integrity sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg== - dependencies: - is-callable "^1.1.4" - is-date-object "^1.0.1" - is-symbol "^1.0.2" - escape-string-regexp@^1.0.0, escape-string-regexp@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= -escodegen@^1.8.0, escodegen@^1.9.1: - version "1.11.1" - resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.11.1.tgz#c485ff8d6b4cdb89e27f4a856e91f118401ca510" - integrity sha512-JwiqFD9KdGVVpeuRa68yU3zZnBEOcPs0nKW7wZzXky8Z7tffdYUHbe11bPCV5jYlK6DVdKLWLm0f5I/QlL0Kmw== +escape-string-regexp@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz#a30304e99daa32e23b2fd20f51babd07cffca344" + integrity sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w== + +escodegen@^1.14.1, escodegen@^1.8.0: + version "1.14.3" + resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.14.3.tgz#4e7b81fba61581dc97582ed78cab7f0e8d63f503" + integrity sha512-qFcX0XJkdg+PB3xjZZG/wKSuT1PnQWx57+TVSjIMmILd2yC/6ByYElPwJnslDsuWuSAp4AwJGumarAAmJch5Kw== dependencies: - esprima "^3.1.3" + esprima "^4.0.1" estraverse "^4.2.0" esutils "^2.0.2" optionator "^0.8.1" optionalDependencies: source-map "~0.6.1" -esprima@^3.1.3: - version "3.1.3" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-3.1.3.tgz#fdca51cee6133895e3c88d535ce49dbff62a4633" - integrity sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM= +eslint-visitor-keys@^1.1.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz#30ebd1ef7c2fdff01c3a4f151044af25fab0523e" + integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ== -esprima@^4.0.0: +esprima@4.0.1, esprima@^4.0.0, esprima@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== estraverse@^4.2.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.2.0.tgz#0dee3fed31fcd469618ce7342099fc1afa0bdb13" - integrity sha1-De4/7TH81GlhjOc0IJn8GvoL2xM= + version "4.3.0" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.3.0.tgz#398ad3f3c5a24948be7725e83d11a7de28cdbd1d" + integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw== esutils@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b" - integrity sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs= + version "2.0.3" + resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" + integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== exec-sh@^0.3.2: - version "0.3.2" - resolved "https://registry.yarnpkg.com/exec-sh/-/exec-sh-0.3.2.tgz#6738de2eb7c8e671d0366aea0b0db8c6f7d7391b" - integrity sha512-9sLAvzhI5nc8TpuQUh4ahMdCrWT00wPWz7j47/emR5+2qEfoZP5zzUXvx+vdx+H6ohhnsYC31iX04QLYJK8zTg== + version "0.3.4" + resolved "https://registry.yarnpkg.com/exec-sh/-/exec-sh-0.3.4.tgz#3a018ceb526cc6f6df2bb504b2bfe8e3a4934ec5" + integrity sha512-sEFIkc61v75sWeOe72qyrqg2Qg0OuLESziUDk/O/z2qgS15y2gWVFrI6f2Qn/qw/0/NCfCEsmNA4zOjkwEZT1A== execa@^1.0.0: version "1.0.0" @@ -1407,6 +1779,21 @@ execa@^1.0.0: signal-exit "^3.0.0" strip-eof "^1.0.0" +execa@^4.0.0: + version "4.0.3" + resolved "https://registry.yarnpkg.com/execa/-/execa-4.0.3.tgz#0a34dabbad6d66100bd6f2c576c8669403f317f2" + integrity sha512-WFDXGHckXPWZX19t1kCsXzOpqX9LWYNqn4C+HqZlk/V0imTkzJZqf87ZBhvpHaftERYknpk0fjSylnXVlVgI0A== + dependencies: + cross-spawn "^7.0.0" + get-stream "^5.0.0" + human-signals "^1.1.1" + is-stream "^2.0.0" + merge-stream "^2.0.0" + npm-run-path "^4.0.0" + onetime "^5.1.0" + signal-exit "^3.0.2" + strip-final-newline "^2.0.0" + exit@^0.1.2: version "0.1.2" resolved "https://registry.yarnpkg.com/exit/-/exit-0.1.2.tgz#0632638f8d877cc82107d30a0fff1a17cba1cd0c" @@ -1425,17 +1812,17 @@ expand-brackets@^2.1.4: snapdragon "^0.8.1" to-regex "^3.0.1" -expect@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/expect/-/expect-24.8.0.tgz#471f8ec256b7b6129ca2524b2a62f030df38718d" - integrity sha512-/zYvP8iMDrzaaxHVa724eJBCKqSHmO0FA7EDkBiRHxg6OipmMn1fN+C8T9L9K8yr7UONkOifu6+LLH+z76CnaA== +expect@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/expect/-/expect-26.4.2.tgz#36db120928a5a2d7d9736643032de32f24e1b2a1" + integrity sha512-IlJ3X52Z0lDHm7gjEp+m76uX46ldH5VpqmU0006vqDju/285twh7zaWMRhs67VpQhBwjjMchk+p5aA0VkERCAA== dependencies: - "@jest/types" "^24.8.0" - ansi-styles "^3.2.0" - jest-get-type "^24.8.0" - jest-matcher-utils "^24.8.0" - jest-message-util "^24.8.0" - jest-regex-util "^24.3.0" + "@jest/types" "^26.3.0" + ansi-styles "^4.0.0" + jest-get-type "^26.3.0" + jest-matcher-utils "^26.4.2" + jest-message-util "^26.3.0" + jest-regex-util "^26.0.0" extend-shallow@^2.0.1: version "2.0.1" @@ -1481,46 +1868,57 @@ extsprintf@^1.2.0: resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f" integrity sha1-4mifjzVvrWLMplo6kcXfX5VRaS8= -fast-deep-equal@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz#7b05218ddf9667bf7f370bf7fdb2cb15fdd0aa49" - integrity sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk= +fast-deep-equal@^3.1.1: + version "3.1.3" + resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" + integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== fast-json-stable-stringify@2.x, fast-json-stable-stringify@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2" - integrity sha1-1RQsDK7msRifh9OnYREGT4bIu/I= + version "2.1.0" + resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" + integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== -fast-levenshtein@~2.0.4: +fast-levenshtein@~2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc= +fast-redact@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/fast-redact/-/fast-redact-2.0.0.tgz#17bb8f5e1f56ecf4a38c8455985e5eab4c478431" + integrity sha512-zxpkULI9W9MNTK2sJ3BpPQrTEXFNESd2X6O1tXMFpK/XM0G5c5Rll2EVYZH2TqI3xRGK/VaJ+eEOt7pnENJpeA== + +fast-safe-stringify@^2.0.7: + version "2.0.7" + resolved "https://registry.yarnpkg.com/fast-safe-stringify/-/fast-safe-stringify-2.0.7.tgz#124aa885899261f68aedb42a7c080de9da608743" + integrity sha512-Utm6CdzT+6xsDk2m8S6uL8VHxNwI6Jub+e9NYTcAms28T84pTa25GJQV9j0CY0N1rM8hK4x6grpF2BQf+2qwVA== + fast-safe-stringify@~1.1.0: version "1.1.13" resolved "https://registry.yarnpkg.com/fast-safe-stringify/-/fast-safe-stringify-1.1.13.tgz#a01e9cd9c9e491715c98a75a42d5f0bbd107ff76" integrity sha1-oB6c2cnkkXFcmKdaQtXwu9EH/3Y= fb-watchman@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/fb-watchman/-/fb-watchman-2.0.0.tgz#54e9abf7dfa2f26cd9b1636c588c1afc05de5d58" - integrity sha1-VOmr99+i8mzZsWNsWIwa/AXeXVg= + version "2.0.1" + resolved "https://registry.yarnpkg.com/fb-watchman/-/fb-watchman-2.0.1.tgz#fc84fb39d2709cf3ff6d743706157bb5708a8a85" + integrity sha512-DkPJKQeY6kKwmuMretBhr7G6Vodr7bFwDYTXIkfG1gjvNpaxBTQV3PbXg6bR1c1UP4jPOX0jHUbbHANL9vRjVg== dependencies: - bser "^2.0.0" + bser "2.1.1" file-exists-dazinatorfork@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/file-exists-dazinatorfork/-/file-exists-dazinatorfork-1.0.2.tgz#cd8d0d85f63e39dc81eceb0b687c44a2cca95c47" integrity sha512-r70c72ln2YHzQINNfxDp02hAhbGkt1HffZ+Du8oetWDLjDtFja/Lm10lUaSh9e+wD+7VDvPee0b0C9SAy8pWZg== -filing-cabinet@^2.3.1: - version "2.3.3" - resolved "https://registry.yarnpkg.com/filing-cabinet/-/filing-cabinet-2.3.3.tgz#77882b25ef0859c321a871b440823bc2ed590995" - integrity sha512-Lp9FNBm74UnZI/0tVcH8WlJZmnYf9/qImt1/VUaEj3rlBl+V7M5yVAzYPJ7X1T2WxQeCrSQN4jN64SlQa6Rbew== +filing-cabinet@^2.5.1: + version "2.5.1" + resolved "https://registry.yarnpkg.com/filing-cabinet/-/filing-cabinet-2.5.1.tgz#f920976d46310710595ed995f033a301570ef6ab" + integrity sha512-GWOdObzou2L0HrJUk8MpJa01q0ZOwuTwTssM2+P+ABJWEGlVWd6ueEatANFdin94/3rdkVSdqpH14VqCNqp3RA== dependencies: app-module-path "^2.2.0" commander "^2.13.0" debug "^4.1.1" + decomment "^0.9.2" enhanced-resolve "^4.1.0" is-relative-path "^1.0.2" module-definition "^3.0.0" @@ -1541,6 +1939,13 @@ fill-range@^4.0.0: repeat-string "^1.6.1" to-regex-range "^2.1.0" +fill-range@^7.0.1: + version "7.0.1" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" + integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== + dependencies: + to-regex-range "^5.0.1" + find-up@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73" @@ -1548,6 +1953,14 @@ find-up@^3.0.0: dependencies: locate-path "^3.0.0" +find-up@^4.0.0, find-up@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19" + integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw== + dependencies: + locate-path "^5.0.0" + path-exists "^4.0.0" + find@^0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/find/-/find-0.3.0.tgz#4082e8fc8d8320f1a382b5e4f521b9bc50775cb8" @@ -1555,10 +1968,15 @@ find@^0.3.0: dependencies: traverse-chain "~0.1.0" +flatstr@^1.0.12: + version "1.0.12" + resolved "https://registry.yarnpkg.com/flatstr/-/flatstr-1.0.12.tgz#c2ba6a08173edbb6c9640e3055b95e287ceb5931" + integrity sha512-4zPxDyhCyiN2wIAtSLI6gc82/EjqZc1onI4Mz/l0pWrAlsSfYH/2ZIcU+e3oA2wDwbzIWNKwa23F8rh6+DRWkw== + flatten@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/flatten/-/flatten-1.0.2.tgz#dae46a9d78fbe25292258cc1e780a41d95c03782" - integrity sha1-2uRqnXj74lKSJYzB54CkHZXAN4I= + version "1.0.3" + resolved "https://registry.yarnpkg.com/flatten/-/flatten-1.0.3.tgz#c1283ac9f27b368abc1e36d1ff7b04501a30356b" + integrity sha512-dVsPA/UwQ8+2uoFe5GHtiBMu48dWLTdsuEd7CKGlZlD78r1TTWBvDuFaFGKCo/ZfEr95Uk56vZoX86OsHkUeIg== for-in@^1.0.2: version "1.0.2" @@ -1586,44 +2004,36 @@ fragment-cache@^0.2.1: dependencies: map-cache "^0.2.2" -fs-minipass@^1.2.5: - version "1.2.6" - resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-1.2.6.tgz#2c5cc30ded81282bfe8a0d7c7c1853ddeb102c07" - integrity sha512-crhvyXcMejjv3Z5d2Fa9sf5xLYVCF5O1c71QxbVnbLsmYMBEvDAftewesN/HhY03YRoA7zOMxjNGrF5svGaaeQ== - dependencies: - minipass "^2.2.1" - fs.realpath@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= -fsevents@^1.2.7: - version "1.2.9" - resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.9.tgz#3f5ed66583ccd6f400b5a00db6f7e861363e388f" - integrity sha512-oeyj2H3EjjonWcFjD5NvZNE9Rqe4UW+nQBU2HNeKw0koVLEFIhtyETyAakeAM3de7Z/SW5kcA+fZUait9EApnw== - dependencies: - nan "^2.12.1" - node-pre-gyp "^0.12.0" +fsevents@^2.1.2: + version "2.1.3" + resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.1.3.tgz#fb738703ae8d2f9fe900c33836ddebee8b97f23e" + integrity sha512-Auw9a4AxqWpa9GUfj370BMPzzyncfBABW8Mab7BGWBYDj4Isgq+cDKtx0i6u9jcX9pQDnswsaaOTgTmA5pEjuQ== -function-bind@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" - integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== - -gauge@~2.7.3: - version "2.7.4" - resolved "https://registry.yarnpkg.com/gauge/-/gauge-2.7.4.tgz#2c03405c7538c39d7eb37b317022e325fb018bf7" - integrity sha1-LANAXHU4w51+s3sxcCLjJfsBi/c= - dependencies: - aproba "^1.0.3" - console-control-strings "^1.0.0" - has-unicode "^2.0.0" - object-assign "^4.1.0" - signal-exit "^3.0.0" - string-width "^1.0.1" - strip-ansi "^3.0.1" - wide-align "^1.1.0" +garnish@^5.2.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/garnish/-/garnish-5.2.0.tgz#bed43659382e4b198e33c793897be7c701e65577" + integrity sha1-vtQ2WTguSxmOM8eTiXvnxwHmVXc= + dependencies: + chalk "^0.5.1" + minimist "^1.1.0" + pad-left "^2.0.0" + pad-right "^0.2.2" + prettier-bytes "^1.0.3" + pretty-ms "^2.1.0" + right-now "^1.0.0" + split2 "^0.2.1" + stdout-stream "^1.4.0" + url-trim "^1.0.0" + +gensync@^1.0.0-beta.1: + version "1.0.0-beta.1" + resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.1.tgz#58f4361ff987e5ff6e1e7a210827aa371eaac269" + integrity sha512-r8EC6NO1sngH/zdD9fiRDLdcgnbayXah+mLgManTaIZJqEC1MZstmnox8KpnI2/fxQwrp5OpCOYWLp4rBl4Jcg== get-amd-module-type@^3.0.0: version "3.0.0" @@ -1633,20 +2043,20 @@ get-amd-module-type@^3.0.0: ast-module-types "^2.3.2" node-source-walk "^4.0.0" -get-caller-file@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.3.tgz#f978fa4c90d1dfe7ff2d6beda2a515e713bdcf4a" - integrity sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w== - get-caller-file@^2.0.1: version "2.0.5" resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== get-own-enumerable-property-symbols@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.0.tgz#b877b49a5c16aefac3655f2ed2ea5b684df8d203" - integrity sha512-CIJYJC4GGF06TakLg8z4GQKvDsx9EMspVxOYih7LerEL/WosUnFIww45CGfxfeKHqlg3twgUrYRT1O3WQqjGCg== + version "3.0.2" + resolved "https://registry.yarnpkg.com/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz#b5fde77f22cbe35f390b4e089922c50bce6ef664" + integrity sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g== + +get-package-type@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/get-package-type/-/get-package-type-0.1.0.tgz#8de2d803cff44df3bc6c456e6668b36c3926e11a" + integrity sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q== get-stream@^4.0.0: version "4.1.0" @@ -1655,6 +2065,13 @@ get-stream@^4.0.0: dependencies: pump "^3.0.0" +get-stream@^5.0.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-5.2.0.tgz#4966a1795ee5ace65e706c4b7beb71257d6e22d3" + integrity sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA== + dependencies: + pump "^3.0.0" + get-value@^2.0.3, get-value@^2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28" @@ -1667,10 +2084,10 @@ getpass@^0.1.1: dependencies: assert-plus "^1.0.0" -glob@^7.1.1, glob@^7.1.2, glob@^7.1.3: - version "7.1.4" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.4.tgz#aa608a2f6c577ad357e1ae5a5c26d9a8d1969255" - integrity sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A== +glob@^7.1.1, glob@^7.1.2, glob@^7.1.3, glob@^7.1.4, glob@^7.1.6: + version "7.1.6" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" + integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" @@ -1685,21 +2102,21 @@ globals@^11.1.0: integrity sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA== gonzales-pe@^4.2.3: - version "4.2.4" - resolved "https://registry.yarnpkg.com/gonzales-pe/-/gonzales-pe-4.2.4.tgz#356ae36a312c46fe0f1026dd6cb539039f8500d2" - integrity sha512-v0Ts/8IsSbh9n1OJRnSfa7Nlxi4AkXIsWB6vPept8FDbL4bXn3FNuxjYtO/nmBGu7GDkL9MFeGebeSu6l55EPQ== + version "4.3.0" + resolved "https://registry.yarnpkg.com/gonzales-pe/-/gonzales-pe-4.3.0.tgz#fe9dec5f3c557eead09ff868c65826be54d067b3" + integrity sha512-otgSPpUmdWJ43VXyiNgEYE4luzHCL2pz4wQ0OnDluC6Eg4Ko3Vexy/SrSynglw/eR+OhkzmqFCZa/OFa/RgAOQ== dependencies: - minimist "1.1.x" + minimist "^1.2.5" -graceful-fs@^4.1.11, graceful-fs@^4.1.15, graceful-fs@^4.1.2: - version "4.2.0" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.0.tgz#8d8fdc73977cb04104721cb53666c1ca64cd328b" - integrity sha512-jpSvDPV4Cq/bgtpndIWbI5hmYxhQGHPC4d4cqBPb4DLniCfhJokdXhwhaDuLBGLQdvvRum/UiX6ECVIPvDXqdg== +graceful-fs@^4.1.2, graceful-fs@^4.2.4: + version "4.2.4" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb" + integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw== -graphviz@^0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/graphviz/-/graphviz-0.0.8.tgz#e599e40733ef80e1653bfe89a5f031ecf2aa4aaa" - integrity sha1-5ZnkBzPvgOFlO/6JpfAx7PKqSqo= +graphviz@0.0.9: + version "0.0.9" + resolved "https://registry.yarnpkg.com/graphviz/-/graphviz-0.0.9.tgz#0bbf1df588c6a92259282da35323622528c4bbc4" + integrity sha512-SmoY2pOtcikmMCqCSy2NO1YsRfu9OO0wpTlOYW++giGjfX1a6gax/m1Fo8IdUd0/3H15cTOfR1SMKwohj4LKsg== dependencies: temp "~0.4.0" @@ -1708,28 +2125,17 @@ growly@^1.3.0: resolved "https://registry.yarnpkg.com/growly/-/growly-1.3.0.tgz#f10748cbe76af964b7c96c93c6bcc28af120c081" integrity sha1-8QdIy+dq+WS3yWyTxrzCivEgwIE= -handlebars@^4.1.2: - version "4.1.2" - resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.1.2.tgz#b6b37c1ced0306b221e094fc7aca3ec23b131b67" - integrity sha512-nvfrjqvt9xQ8Z/w0ijewdD/vvWDTOweBUm96NTr66Wfvo1mJenBLwcYmPs3TIBP5ruzYGD7Hx/DaM9RmhroGPw== - dependencies: - neo-async "^2.6.0" - optimist "^0.6.1" - source-map "^0.6.1" - optionalDependencies: - uglify-js "^3.1.4" - har-schema@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92" integrity sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI= -har-validator@~5.1.0: - version "5.1.3" - resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.1.3.tgz#1ef89ebd3e4996557675eed9893110dc350fa080" - integrity sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g== +har-validator@~5.1.3: + version "5.1.5" + resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.1.5.tgz#1f0803b9f8cb20c0fa13822df1ecddb36bde1efd" + integrity sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w== dependencies: - ajv "^6.5.5" + ajv "^6.12.3" har-schema "^2.0.0" has-ansi@^0.1.0: @@ -1744,15 +2150,10 @@ has-flag@^3.0.0: resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= -has-symbols@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.0.tgz#ba1a8f1af2a0fc39650f5c850367704122063b44" - integrity sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q= - -has-unicode@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9" - integrity sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk= +has-flag@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" + integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== has-value@^0.3.1: version "0.3.1" @@ -1785,24 +2186,22 @@ has-values@^1.0.0: is-number "^3.0.0" kind-of "^4.0.0" -has@^1.0.1, has@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796" - integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== - dependencies: - function-bind "^1.1.1" - hosted-git-info@^2.1.4: - version "2.7.1" - resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.7.1.tgz#97f236977bd6e125408930ff6de3eec6281ec047" - integrity sha512-7T/BxH19zbcCTa8XkMlbK5lTo1WtgkFi3GvdWEyNuc4Vex7/9Dqbnpsf4JMydcfj9HCg4zUWFTL3Za6lapg5/w== + version "2.8.8" + resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.8.tgz#7539bd4bc1e0e0a895815a2e0262420b12858488" + integrity sha512-f/wzC2QaWBs7t9IYqB4T3sR1xviIViXJRJTWBlx2Gf3g0Xi5vI7Yy4koXQ1c9OYDGHN9sBy1DQ2AB8fqZBWhUg== -html-encoding-sniffer@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/html-encoding-sniffer/-/html-encoding-sniffer-1.0.2.tgz#e70d84b94da53aa375e11fe3a351be6642ca46f8" - integrity sha512-71lZziiDnsuabfdYiUeWdCVyKuqwWi23L8YeIgV9jSSZHCtb6wB1BKWooH7L3tn4/FuZJMVWyNaIDr4RGmaSYw== +html-encoding-sniffer@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/html-encoding-sniffer/-/html-encoding-sniffer-2.0.1.tgz#42a6dc4fd33f00281176e8b23759ca4e4fa185f3" + integrity sha512-D5JbOMBIR/TVZkubHT+OyT2705QvogUW4IBn6nHd756OwieSF9aDYFj4dv6HHEVGYbHaLETa3WggZYWWMyy3ZQ== dependencies: - whatwg-encoding "^1.0.1" + whatwg-encoding "^1.0.5" + +html-escaper@^2.0.0: + version "2.0.2" + resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453" + integrity sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg== http-signature@~1.2.0: version "1.2.0" @@ -1813,27 +2212,25 @@ http-signature@~1.2.0: jsprim "^1.2.2" sshpk "^1.7.0" -iconv-lite@0.4.24, iconv-lite@^0.4.4: +human-signals@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3" + integrity sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw== + +iconv-lite@0.4.24: version "0.4.24" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA== dependencies: safer-buffer ">= 2.1.2 < 3" -ignore-walk@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/ignore-walk/-/ignore-walk-3.0.1.tgz#a83e62e7d272ac0e3b551aaa82831a19b69f82f8" - integrity sha512-DTVlMx3IYPe0/JJcYP7Gxg7ttZZu3IInhuEhbchuqneY9wWe5Ojy2mXLBaQFUQmo0AW2r3qG7m1mg86js+gnlQ== - dependencies: - minimatch "^3.0.4" - -import-local@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/import-local/-/import-local-2.0.0.tgz#55070be38a5993cf18ef6db7e961f5bee5c5a09d" - integrity sha512-b6s04m3O+s3CGSbqDIyP4R6aAwAeYlVq9+WUWep6iHa8ETRf9yei1U48C5MmfJmV9AiLYYBKPMq/W+/WRpQmCQ== +import-local@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.0.2.tgz#a8cfd0431d1de4a2199703d003e3e62364fa6db6" + integrity sha512-vjL3+w0oulAVZ0hBHnxa/Nm5TAurf9YLQJDhqRZyqb+VKGOB6LU8t9H1Nr5CIo16vh9XfJTOoHwU0B71S557gA== dependencies: - pkg-dir "^3.0.0" - resolve-cwd "^2.0.0" + pkg-dir "^4.2.0" + resolve-cwd "^3.0.0" imurmurhash@^0.1.4: version "0.1.4" @@ -1858,7 +2255,7 @@ inflight@^1.0.4: once "^1.3.0" wrappy "1" -inherits@2, inherits@~2.0.1, inherits@~2.0.3: +inherits@2, inherits@^2.0.3, inherits@~2.0.1, inherits@~2.0.3: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== @@ -1875,10 +2272,10 @@ invariant@^2.2.4: dependencies: loose-envify "^1.0.0" -invert-kv@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-2.0.0.tgz#7393f5afa59ec9ff5f67a27620d11c226e3eec02" - integrity sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA== +ip-regex@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/ip-regex/-/ip-regex-2.1.0.tgz#fa78bf5d2e6913c911ce9f819ee5146bb6d844e9" + integrity sha1-+ni/XS5pE8kRzp+BnuUUa7bYROk= is-accessor-descriptor@^0.1.6: version "0.1.6" @@ -1904,11 +2301,6 @@ is-buffer@^1.1.5: resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== -is-callable@^1.1.4: - version "1.1.4" - resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.1.4.tgz#1e1adf219e1eeb684d691f9d6a05ff0d30a24d75" - integrity sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA== - is-ci@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-ci/-/is-ci-2.0.0.tgz#6bc6334181810e04b5c22b3d589fdca55026404c" @@ -1930,11 +2322,6 @@ is-data-descriptor@^1.0.0: dependencies: kind-of "^6.0.0" -is-date-object@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.1.tgz#9aa20eb6aeebbff77fbd33e74ca01b33581d3a16" - integrity sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY= - is-descriptor@^0.1.0: version "0.1.6" resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca" @@ -1953,6 +2340,11 @@ is-descriptor@^1.0.0, is-descriptor@^1.0.2: is-data-descriptor "^1.0.0" kind-of "^6.0.2" +is-docker@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/is-docker/-/is-docker-2.1.1.tgz#4125a88e44e450d384e09047ede71adc2d144156" + integrity sha512-ZOoqiXfEwtGknTiuDEy8pN2CfE3TxMHprvNer1mXiqwkOT77Rw3YVrUQ52EqAOU3QAWDQ+bQdx7HJzrv7LS2Hw== + is-extendable@^0.1.0, is-extendable@^0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89" @@ -1965,23 +2357,43 @@ is-extendable@^1.0.1: dependencies: is-plain-object "^2.0.4" -is-fullwidth-code-point@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb" - integrity sha1-754xOG8DGn8NZDr4L95QxFfvAMs= - dependencies: - number-is-nan "^1.0.0" +is-extglob@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" + integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= + +is-finite@^1.0.1: + version "1.1.0" + resolved "https://registry.yarnpkg.com/is-finite/-/is-finite-1.1.0.tgz#904135c77fb42c0641d6aa1bcdbc4daa8da082f3" + integrity sha512-cdyMtqX/BOqqNBBiKlIVkytNHm49MtMlYyn1zxzvJKWmFMlGzm+ry5BBfYyeY9YmNKbRSo/o7OX9w9ale0wg3w== is-fullwidth-code-point@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8= +is-fullwidth-code-point@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" + integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== + is-generator-fn@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/is-generator-fn/-/is-generator-fn-2.1.0.tgz#7d140adc389aaf3011a8f2a2a4cfa6faadffb118" integrity sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ== +is-glob@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" + integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== + dependencies: + is-extglob "^2.1.1" + +is-interactive@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-interactive/-/is-interactive-1.0.0.tgz#cea6e6ae5c870a7b0a0004070b7b587e0252912e" + integrity sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w== + is-number@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195" @@ -1989,6 +2401,11 @@ is-number@^3.0.0: dependencies: kind-of "^3.0.2" +is-number@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" + integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== + is-obj@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz#3e4729ac1f5fde025cd7d83a896dab9f4f67db0f" @@ -2001,19 +2418,15 @@ is-plain-object@^2.0.3, is-plain-object@^2.0.4: dependencies: isobject "^3.0.1" -is-plain-object@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-3.0.0.tgz#47bfc5da1b5d50d64110806c199359482e75a928" - integrity sha512-tZIpofR+P05k8Aocp7UI/2UTa9lTJSebCXpFFoR9aibpokDj/uXBsJ8luUu0tTVYKkMU6URDUuOfJZ7koewXvg== - dependencies: - isobject "^4.0.0" +is-plain-object@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-5.0.0.tgz#4427f50ab3429e9025ea7d52e9043a9ef4159344" + integrity sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q== -is-regex@^1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.0.4.tgz#5517489b547091b0930e095654ced25ee97e9491" - integrity sha1-VRdIm1RwkbCTDglWVM7SXul+lJE= - dependencies: - has "^1.0.1" +is-potential-custom-element-name@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.0.tgz#0c52e54bcca391bb2c494b21e8626d7336c6e397" + integrity sha1-DFLlS8yjkbssSUsh6GJtczbG45c= is-regexp@^1.0.0: version "1.0.0" @@ -2030,14 +2443,12 @@ is-stream@^1.1.0: resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-1.1.0.tgz#12d4a3dd4e68e0b79ceb8dbc84173ae80d91ca44" integrity sha1-EtSj3U5o4Lec6428hBc66A2RykQ= -is-symbol@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.2.tgz#a055f6ae57192caee329e7a860118b497a950f38" - integrity sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw== - dependencies: - has-symbols "^1.0.0" +is-stream@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.0.tgz#bde9c32680d6fae04129d6ac9d921ce7815f78e3" + integrity sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw== -is-typedarray@~1.0.0: +is-typedarray@^1.0.0, is-typedarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" integrity sha1-5HnICFjfDBsR3dppQPlgEfzaSpo= @@ -2052,10 +2463,12 @@ is-windows@^1.0.2: resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d" integrity sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA== -is-wsl@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/is-wsl/-/is-wsl-1.1.0.tgz#1f16e4aa22b04d1336b66188a66af3c600c3a66d" - integrity sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0= +is-wsl@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/is-wsl/-/is-wsl-2.2.0.tgz#74a4c76e77ca9fd3f932f290c17ea326cd157271" + integrity sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww== + dependencies: + is-docker "^2.0.0" isarray@0.0.1: version "0.0.1" @@ -2084,453 +2497,495 @@ isobject@^3.0.0, isobject@^3.0.1: resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= -isobject@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-4.0.0.tgz#3f1c9155e73b192022a80819bacd0343711697b0" - integrity sha512-S/2fF5wH8SJA/kmwr6HYhK/RI/OkhD84k8ntalo0iJjZikgq1XFvR5M8NPT1x5F7fBwCG3qHfnzeP/Vh/ZxCUA== - isstream@~0.1.2: version "0.1.2" resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" integrity sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo= -istanbul-lib-coverage@^2.0.2, istanbul-lib-coverage@^2.0.5: - version "2.0.5" - resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.5.tgz#675f0ab69503fad4b1d849f736baaca803344f49" - integrity sha512-8aXznuEPCJvGnMSRft4udDRDtb1V3pkQkMMI5LI+6HuQz5oQ4J2UFn1H82raA3qJtyOLkkwVqICBQkjnGtn5mA== +istanbul-lib-coverage@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-3.0.0.tgz#f5944a37c70b550b02a78a5c3b2055b280cec8ec" + integrity sha512-UiUIqxMgRDET6eR+o5HbfRYP1l0hqkWOs7vNxC/mggutCMUIhWMm8gAHb8tHlyfD3/l6rlgNA5cKdDzEAf6hEg== -istanbul-lib-instrument@^3.0.1, istanbul-lib-instrument@^3.3.0: - version "3.3.0" - resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-3.3.0.tgz#a5f63d91f0bbc0c3e479ef4c5de027335ec6d630" - integrity sha512-5nnIN4vo5xQZHdXno/YDXJ0G+I3dAm4XgzfSVTPLQpj/zAV2dV6Juy0yaf10/zrJOJeHoN3fraFe+XRq2bFVZA== - dependencies: - "@babel/generator" "^7.4.0" - "@babel/parser" "^7.4.3" - "@babel/template" "^7.4.0" - "@babel/traverse" "^7.4.3" - "@babel/types" "^7.4.0" - istanbul-lib-coverage "^2.0.5" - semver "^6.0.0" +istanbul-lib-instrument@^4.0.0, istanbul-lib-instrument@^4.0.3: + version "4.0.3" + resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-4.0.3.tgz#873c6fff897450118222774696a3f28902d77c1d" + integrity sha512-BXgQl9kf4WTCPCCpmFGoJkz/+uhvm7h7PFKUYxh7qarQd3ER33vHG//qaE8eN25l07YqZPpHXU9I09l/RD5aGQ== + dependencies: + "@babel/core" "^7.7.5" + "@istanbuljs/schema" "^0.1.2" + istanbul-lib-coverage "^3.0.0" + semver "^6.3.0" -istanbul-lib-report@^2.0.4: - version "2.0.8" - resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-2.0.8.tgz#5a8113cd746d43c4889eba36ab10e7d50c9b4f33" - integrity sha512-fHBeG573EIihhAblwgxrSenp0Dby6tJMFR/HvlerBsrCTD5bkUuoNtn3gVh29ZCS824cGGBPn7Sg7cNk+2xUsQ== +istanbul-lib-report@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz#7518fe52ea44de372f460a76b5ecda9ffb73d8a6" + integrity sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw== dependencies: - istanbul-lib-coverage "^2.0.5" - make-dir "^2.1.0" - supports-color "^6.1.0" + istanbul-lib-coverage "^3.0.0" + make-dir "^3.0.0" + supports-color "^7.1.0" -istanbul-lib-source-maps@^3.0.1: - version "3.0.6" - resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-3.0.6.tgz#284997c48211752ec486253da97e3879defba8c8" - integrity sha512-R47KzMtDJH6X4/YW9XTx+jrLnZnscW4VpNN+1PViSYTejLVPWv7oov+Duf8YQSPyVRUvueQqz1TcsC6mooZTXw== +istanbul-lib-source-maps@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.0.tgz#75743ce6d96bb86dc7ee4352cf6366a23f0b1ad9" + integrity sha512-c16LpFRkR8vQXyHZ5nLpY35JZtzj1PQY1iZmesUbf1FZHbIupcWfjgOXBY9YHkLEQ6puz1u4Dgj6qmU/DisrZg== dependencies: debug "^4.1.1" - istanbul-lib-coverage "^2.0.5" - make-dir "^2.1.0" - rimraf "^2.6.3" + istanbul-lib-coverage "^3.0.0" source-map "^0.6.1" -istanbul-reports@^2.1.1: - version "2.2.6" - resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-2.2.6.tgz#7b4f2660d82b29303a8fe6091f8ca4bf058da1af" - integrity sha512-SKi4rnMyLBKe0Jy2uUdx28h8oG7ph2PPuQPvIAh31d+Ci+lSiEu4C+h3oBPuJ9+mPKhOyW0M8gY4U5NM1WLeXA== - dependencies: - handlebars "^4.1.2" - -jest-changed-files@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-changed-files/-/jest-changed-files-24.8.0.tgz#7e7eb21cf687587a85e50f3d249d1327e15b157b" - integrity sha512-qgANC1Yrivsq+UrLXsvJefBKVoCsKB0Hv+mBb6NMjjZ90wwxCDmU3hsCXBya30cH+LnPYjwgcU65i6yJ5Nfuug== - dependencies: - "@jest/types" "^24.8.0" - execa "^1.0.0" - throat "^4.0.0" - -jest-cli@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-cli/-/jest-cli-24.8.0.tgz#b075ac914492ed114fa338ade7362a301693e989" - integrity sha512-+p6J00jSMPQ116ZLlHJJvdf8wbjNbZdeSX9ptfHX06/MSNaXmKihQzx5vQcw0q2G6JsdVkUIdWbOWtSnaYs3yA== - dependencies: - "@jest/core" "^24.8.0" - "@jest/test-result" "^24.8.0" - "@jest/types" "^24.8.0" - chalk "^2.0.1" +istanbul-reports@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-3.0.2.tgz#d593210e5000683750cb09fc0644e4b6e27fd53b" + integrity sha512-9tZvz7AiR3PEDNGiV9vIouQ/EAcqMXFmkcA1CDFTwOB98OZVDL0PH9glHotf5Ugp6GCOTypfzGWI/OqjWNCRUw== + dependencies: + html-escaper "^2.0.0" + istanbul-lib-report "^3.0.0" + +jest-changed-files@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/jest-changed-files/-/jest-changed-files-26.3.0.tgz#68fb2a7eb125f50839dab1f5a17db3607fe195b1" + integrity sha512-1C4R4nijgPltX6fugKxM4oQ18zimS7LqQ+zTTY8lMCMFPrxqBFb7KJH0Z2fRQJvw2Slbaipsqq7s1mgX5Iot+g== + dependencies: + "@jest/types" "^26.3.0" + execa "^4.0.0" + throat "^5.0.0" + +jest-cli@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest-cli/-/jest-cli-26.4.2.tgz#24afc6e4dfc25cde4c7ec4226fb7db5f157c21da" + integrity sha512-zb+lGd/SfrPvoRSC/0LWdaWCnscXc1mGYW//NP4/tmBvRPT3VntZ2jtKUONsRi59zc5JqmsSajA9ewJKFYp8Cw== + dependencies: + "@jest/core" "^26.4.2" + "@jest/test-result" "^26.3.0" + "@jest/types" "^26.3.0" + chalk "^4.0.0" exit "^0.1.2" - import-local "^2.0.0" + graceful-fs "^4.2.4" + import-local "^3.0.2" is-ci "^2.0.0" - jest-config "^24.8.0" - jest-util "^24.8.0" - jest-validate "^24.8.0" + jest-config "^26.4.2" + jest-util "^26.3.0" + jest-validate "^26.4.2" prompts "^2.0.1" - realpath-native "^1.1.0" - yargs "^12.0.2" + yargs "^15.3.1" -jest-config@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-config/-/jest-config-24.8.0.tgz#77db3d265a6f726294687cbbccc36f8a76ee0f4f" - integrity sha512-Czl3Nn2uEzVGsOeaewGWoDPD8GStxCpAe0zOYs2x2l0fZAgPbCr3uwUkgNKV3LwE13VXythM946cd5rdGkkBZw== +jest-config@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest-config/-/jest-config-26.4.2.tgz#da0cbb7dc2c131ffe831f0f7f2a36256e6086558" + integrity sha512-QBf7YGLuToiM8PmTnJEdRxyYy3mHWLh24LJZKVdXZ2PNdizSe1B/E8bVm+HYcjbEzGuVXDv/di+EzdO/6Gq80A== dependencies: "@babel/core" "^7.1.0" - "@jest/test-sequencer" "^24.8.0" - "@jest/types" "^24.8.0" - babel-jest "^24.8.0" - chalk "^2.0.1" + "@jest/test-sequencer" "^26.4.2" + "@jest/types" "^26.3.0" + babel-jest "^26.3.0" + chalk "^4.0.0" + deepmerge "^4.2.2" glob "^7.1.1" - jest-environment-jsdom "^24.8.0" - jest-environment-node "^24.8.0" - jest-get-type "^24.8.0" - jest-jasmine2 "^24.8.0" - jest-regex-util "^24.3.0" - jest-resolve "^24.8.0" - jest-util "^24.8.0" - jest-validate "^24.8.0" - micromatch "^3.1.10" - pretty-format "^24.8.0" - realpath-native "^1.1.0" - -jest-diff@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-24.8.0.tgz#146435e7d1e3ffdf293d53ff97e193f1d1546172" - integrity sha512-wxetCEl49zUpJ/bvUmIFjd/o52J+yWcoc5ZyPq4/W1LUKGEhRYDIbP1KcF6t+PvqNrGAFk4/JhtxDq/Nnzs66g== - dependencies: - chalk "^2.0.1" - diff-sequences "^24.3.0" - jest-get-type "^24.8.0" - pretty-format "^24.8.0" - -jest-docblock@^24.3.0: - version "24.3.0" - resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-24.3.0.tgz#b9c32dac70f72e4464520d2ba4aec02ab14db5dd" - integrity sha512-nlANmF9Yq1dufhFlKG9rasfQlrY7wINJbo3q01tu56Jv5eBU5jirylhF2O5ZBnLxzOVBGRDz/9NAwNyBtG4Nyg== - dependencies: - detect-newline "^2.1.0" - -jest-each@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-each/-/jest-each-24.8.0.tgz#a05fd2bf94ddc0b1da66c6d13ec2457f35e52775" - integrity sha512-NrwK9gaL5+XgrgoCsd9svsoWdVkK4gnvyhcpzd6m487tXHqIdYeykgq3MKI1u4I+5Zf0tofr70at9dWJDeb+BA== - dependencies: - "@jest/types" "^24.8.0" - chalk "^2.0.1" - jest-get-type "^24.8.0" - jest-util "^24.8.0" - pretty-format "^24.8.0" - -jest-environment-jsdom@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-environment-jsdom/-/jest-environment-jsdom-24.8.0.tgz#300f6949a146cabe1c9357ad9e9ecf9f43f38857" - integrity sha512-qbvgLmR7PpwjoFjM/sbuqHJt/NCkviuq9vus9NBn/76hhSidO+Z6Bn9tU8friecegbJL8gzZQEMZBQlFWDCwAQ== - dependencies: - "@jest/environment" "^24.8.0" - "@jest/fake-timers" "^24.8.0" - "@jest/types" "^24.8.0" - jest-mock "^24.8.0" - jest-util "^24.8.0" - jsdom "^11.5.1" - -jest-environment-node@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-environment-node/-/jest-environment-node-24.8.0.tgz#d3f726ba8bc53087a60e7a84ca08883a4c892231" - integrity sha512-vIGUEScd1cdDgR6sqn2M08sJTRLQp6Dk/eIkCeO4PFHxZMOgy+uYLPMC4ix3PEfM5Au/x3uQ/5Tl0DpXXZsJ/Q== - dependencies: - "@jest/environment" "^24.8.0" - "@jest/fake-timers" "^24.8.0" - "@jest/types" "^24.8.0" - jest-mock "^24.8.0" - jest-util "^24.8.0" - -jest-get-type@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-24.8.0.tgz#a7440de30b651f5a70ea3ed7ff073a32dfe646fc" - integrity sha512-RR4fo8jEmMD9zSz2nLbs2j0zvPpk/KCEz3a62jJWbd2ayNo0cb+KFRxPHVhE4ZmgGJEQp0fosmNz84IfqM8cMQ== - -jest-haste-map@^24.8.0: - version "24.8.1" - resolved "https://registry.yarnpkg.com/jest-haste-map/-/jest-haste-map-24.8.1.tgz#f39cc1d2b1d907e014165b4bd5a957afcb992982" - integrity sha512-SwaxMGVdAZk3ernAx2Uv2sorA7jm3Kx+lR0grp6rMmnY06Kn/urtKx1LPN2mGTea4fCT38impYT28FfcLUhX0g== - dependencies: - "@jest/types" "^24.8.0" - anymatch "^2.0.0" + graceful-fs "^4.2.4" + jest-environment-jsdom "^26.3.0" + jest-environment-node "^26.3.0" + jest-get-type "^26.3.0" + jest-jasmine2 "^26.4.2" + jest-regex-util "^26.0.0" + jest-resolve "^26.4.0" + jest-util "^26.3.0" + jest-validate "^26.4.2" + micromatch "^4.0.2" + pretty-format "^26.4.2" + +jest-diff@^25.2.1: + version "25.5.0" + resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-25.5.0.tgz#1dd26ed64f96667c068cef026b677dfa01afcfa9" + integrity sha512-z1kygetuPiREYdNIumRpAHY6RXiGmp70YHptjdaxTWGmA085W3iCnXNx0DhflK3vwrKmrRWyY1wUpkPMVxMK7A== + dependencies: + chalk "^3.0.0" + diff-sequences "^25.2.6" + jest-get-type "^25.2.6" + pretty-format "^25.5.0" + +jest-diff@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-26.4.2.tgz#a1b7b303bcc534aabdb3bd4a7caf594ac059f5aa" + integrity sha512-6T1XQY8U28WH0Z5rGpQ+VqZSZz8EN8rZcBtfvXaOkbwxIEeRre6qnuZQlbY1AJ4MKDxQF8EkrCvK+hL/VkyYLQ== + dependencies: + chalk "^4.0.0" + diff-sequences "^26.3.0" + jest-get-type "^26.3.0" + pretty-format "^26.4.2" + +jest-docblock@^26.0.0: + version "26.0.0" + resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-26.0.0.tgz#3e2fa20899fc928cb13bd0ff68bd3711a36889b5" + integrity sha512-RDZ4Iz3QbtRWycd8bUEPxQsTlYazfYn/h5R65Fc6gOfwozFhoImx+affzky/FFBuqISPTqjXomoIGJVKBWoo0w== + dependencies: + detect-newline "^3.0.0" + +jest-each@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest-each/-/jest-each-26.4.2.tgz#bb14f7f4304f2bb2e2b81f783f989449b8b6ffae" + integrity sha512-p15rt8r8cUcRY0Mvo1fpkOGYm7iI8S6ySxgIdfh3oOIv+gHwrHTy5VWCGOecWUhDsit4Nz8avJWdT07WLpbwDA== + dependencies: + "@jest/types" "^26.3.0" + chalk "^4.0.0" + jest-get-type "^26.3.0" + jest-util "^26.3.0" + pretty-format "^26.4.2" + +jest-environment-jsdom@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/jest-environment-jsdom/-/jest-environment-jsdom-26.3.0.tgz#3b749ba0f3a78e92ba2c9ce519e16e5dd515220c" + integrity sha512-zra8He2btIMJkAzvLaiZ9QwEPGEetbxqmjEBQwhH3CA+Hhhu0jSiEJxnJMbX28TGUvPLxBt/zyaTLrOPF4yMJA== + dependencies: + "@jest/environment" "^26.3.0" + "@jest/fake-timers" "^26.3.0" + "@jest/types" "^26.3.0" + "@types/node" "*" + jest-mock "^26.3.0" + jest-util "^26.3.0" + jsdom "^16.2.2" + +jest-environment-node@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/jest-environment-node/-/jest-environment-node-26.3.0.tgz#56c6cfb506d1597f94ee8d717072bda7228df849" + integrity sha512-c9BvYoo+FGcMj5FunbBgtBnbR5qk3uky8PKyRVpSfe2/8+LrNQMiXX53z6q2kY+j15SkjQCOSL/6LHnCPLVHNw== + dependencies: + "@jest/environment" "^26.3.0" + "@jest/fake-timers" "^26.3.0" + "@jest/types" "^26.3.0" + "@types/node" "*" + jest-mock "^26.3.0" + jest-util "^26.3.0" + +jest-get-type@^25.2.6: + version "25.2.6" + resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-25.2.6.tgz#0b0a32fab8908b44d508be81681487dbabb8d877" + integrity sha512-DxjtyzOHjObRM+sM1knti6or+eOgcGU4xVSb2HNP1TqO4ahsT+rqZg+nyqHWJSvWgKC5cG3QjGFBqxLghiF/Ig== + +jest-get-type@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-26.3.0.tgz#e97dc3c3f53c2b406ca7afaed4493b1d099199e0" + integrity sha512-TpfaviN1R2pQWkIihlfEanwOXK0zcxrKEE4MlU6Tn7keoXdN6/3gK/xl0yEh8DOunn5pOVGKf8hB4R9gVh04ig== + +jest-haste-map@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/jest-haste-map/-/jest-haste-map-26.3.0.tgz#c51a3b40100d53ab777bfdad382d2e7a00e5c726" + integrity sha512-DHWBpTJgJhLLGwE5Z1ZaqLTYqeODQIZpby0zMBsCU9iRFHYyhklYqP4EiG73j5dkbaAdSZhgB938mL51Q5LeZA== + dependencies: + "@jest/types" "^26.3.0" + "@types/graceful-fs" "^4.1.2" + "@types/node" "*" + anymatch "^3.0.3" fb-watchman "^2.0.0" - graceful-fs "^4.1.15" - invariant "^2.2.4" - jest-serializer "^24.4.0" - jest-util "^24.8.0" - jest-worker "^24.6.0" - micromatch "^3.1.10" + graceful-fs "^4.2.4" + jest-regex-util "^26.0.0" + jest-serializer "^26.3.0" + jest-util "^26.3.0" + jest-worker "^26.3.0" + micromatch "^4.0.2" sane "^4.0.3" walker "^1.0.7" optionalDependencies: - fsevents "^1.2.7" + fsevents "^2.1.2" -jest-jasmine2@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-jasmine2/-/jest-jasmine2-24.8.0.tgz#a9c7e14c83dd77d8b15e820549ce8987cc8cd898" - integrity sha512-cEky88npEE5LKd5jPpTdDCLvKkdyklnaRycBXL6GNmpxe41F0WN44+i7lpQKa/hcbXaQ+rc9RMaM4dsebrYong== +jest-jasmine2@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest-jasmine2/-/jest-jasmine2-26.4.2.tgz#18a9d5bec30904267ac5e9797570932aec1e2257" + integrity sha512-z7H4EpCldHN1J8fNgsja58QftxBSL+JcwZmaXIvV9WKIM+x49F4GLHu/+BQh2kzRKHAgaN/E82od+8rTOBPyPA== dependencies: "@babel/traverse" "^7.1.0" - "@jest/environment" "^24.8.0" - "@jest/test-result" "^24.8.0" - "@jest/types" "^24.8.0" - chalk "^2.0.1" + "@jest/environment" "^26.3.0" + "@jest/source-map" "^26.3.0" + "@jest/test-result" "^26.3.0" + "@jest/types" "^26.3.0" + "@types/node" "*" + chalk "^4.0.0" co "^4.6.0" - expect "^24.8.0" + expect "^26.4.2" is-generator-fn "^2.0.0" - jest-each "^24.8.0" - jest-matcher-utils "^24.8.0" - jest-message-util "^24.8.0" - jest-runtime "^24.8.0" - jest-snapshot "^24.8.0" - jest-util "^24.8.0" - pretty-format "^24.8.0" - throat "^4.0.0" - -jest-leak-detector@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-leak-detector/-/jest-leak-detector-24.8.0.tgz#c0086384e1f650c2d8348095df769f29b48e6980" - integrity sha512-cG0yRSK8A831LN8lIHxI3AblB40uhv0z+SsQdW3GoMMVcK+sJwrIIyax5tu3eHHNJ8Fu6IMDpnLda2jhn2pD/g== - dependencies: - pretty-format "^24.8.0" - -jest-matcher-utils@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-matcher-utils/-/jest-matcher-utils-24.8.0.tgz#2bce42204c9af12bde46f83dc839efe8be832495" - integrity sha512-lex1yASY51FvUuHgm0GOVj7DCYEouWSlIYmCW7APSqB9v8mXmKSn5+sWVF0MhuASG0bnYY106/49JU1FZNl5hw== - dependencies: - chalk "^2.0.1" - jest-diff "^24.8.0" - jest-get-type "^24.8.0" - pretty-format "^24.8.0" - -jest-message-util@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-message-util/-/jest-message-util-24.8.0.tgz#0d6891e72a4beacc0292b638685df42e28d6218b" - integrity sha512-p2k71rf/b6ns8btdB0uVdljWo9h0ovpnEe05ZKWceQGfXYr4KkzgKo3PBi8wdnd9OtNh46VpNIJynUn/3MKm1g== + jest-each "^26.4.2" + jest-matcher-utils "^26.4.2" + jest-message-util "^26.3.0" + jest-runtime "^26.4.2" + jest-snapshot "^26.4.2" + jest-util "^26.3.0" + pretty-format "^26.4.2" + throat "^5.0.0" + +jest-leak-detector@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest-leak-detector/-/jest-leak-detector-26.4.2.tgz#c73e2fa8757bf905f6f66fb9e0070b70fa0f573f" + integrity sha512-akzGcxwxtE+9ZJZRW+M2o+nTNnmQZxrHJxX/HjgDaU5+PLmY1qnQPnMjgADPGCRPhB+Yawe1iij0REe+k/aHoA== + dependencies: + jest-get-type "^26.3.0" + pretty-format "^26.4.2" + +jest-matcher-utils@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest-matcher-utils/-/jest-matcher-utils-26.4.2.tgz#fa81f3693f7cb67e5fc1537317525ef3b85f4b06" + integrity sha512-KcbNqWfWUG24R7tu9WcAOKKdiXiXCbMvQYT6iodZ9k1f7065k0keUOW6XpJMMvah+hTfqkhJhRXmA3r3zMAg0Q== + dependencies: + chalk "^4.0.0" + jest-diff "^26.4.2" + jest-get-type "^26.3.0" + pretty-format "^26.4.2" + +jest-message-util@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/jest-message-util/-/jest-message-util-26.3.0.tgz#3bdb538af27bb417f2d4d16557606fd082d5841a" + integrity sha512-xIavRYqr4/otGOiLxLZGj3ieMmjcNE73Ui+LdSW/Y790j5acqCsAdDiLIbzHCZMpN07JOENRWX5DcU+OQ+TjTA== dependencies: "@babel/code-frame" "^7.0.0" - "@jest/test-result" "^24.8.0" - "@jest/types" "^24.8.0" + "@jest/types" "^26.3.0" "@types/stack-utils" "^1.0.1" - chalk "^2.0.1" - micromatch "^3.1.10" - slash "^2.0.0" - stack-utils "^1.0.1" - -jest-mock@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-mock/-/jest-mock-24.8.0.tgz#2f9d14d37699e863f1febf4e4d5a33b7fdbbde56" - integrity sha512-6kWugwjGjJw+ZkK4mDa0Df3sDlUTsV47MSrT0nGQ0RBWJbpODDQ8MHDVtGtUYBne3IwZUhtB7elxHspU79WH3A== - dependencies: - "@jest/types" "^24.8.0" - -jest-pnp-resolver@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/jest-pnp-resolver/-/jest-pnp-resolver-1.2.1.tgz#ecdae604c077a7fbc70defb6d517c3c1c898923a" - integrity sha512-pgFw2tm54fzgYvc/OHrnysABEObZCUNFnhjoRjaVOCN8NYc032/gVjPaHD4Aq6ApkSieWtfKAFQtmDKAmhupnQ== - -jest-regex-util@^24.3.0: - version "24.3.0" - resolved "https://registry.yarnpkg.com/jest-regex-util/-/jest-regex-util-24.3.0.tgz#d5a65f60be1ae3e310d5214a0307581995227b36" - integrity sha512-tXQR1NEOyGlfylyEjg1ImtScwMq8Oh3iJbGTjN7p0J23EuVX1MA8rwU69K4sLbCmwzgCUbVkm0FkSF9TdzOhtg== - -jest-resolve-dependencies@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-resolve-dependencies/-/jest-resolve-dependencies-24.8.0.tgz#19eec3241f2045d3f990dba331d0d7526acff8e0" - integrity sha512-hyK1qfIf/krV+fSNyhyJeq3elVMhK9Eijlwy+j5jqmZ9QsxwKBiP6qukQxaHtK8k6zql/KYWwCTQ+fDGTIJauw== - dependencies: - "@jest/types" "^24.8.0" - jest-regex-util "^24.3.0" - jest-snapshot "^24.8.0" - -jest-resolve@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-resolve/-/jest-resolve-24.8.0.tgz#84b8e5408c1f6a11539793e2b5feb1b6e722439f" - integrity sha512-+hjSzi1PoRvnuOICoYd5V/KpIQmkAsfjFO71458hQ2Whi/yf1GDeBOFj8Gxw4LrApHsVJvn5fmjcPdmoUHaVKw== - dependencies: - "@jest/types" "^24.8.0" - browser-resolve "^1.11.3" - chalk "^2.0.1" - jest-pnp-resolver "^1.2.1" - realpath-native "^1.1.0" - -jest-runner@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-runner/-/jest-runner-24.8.0.tgz#4f9ae07b767db27b740d7deffad0cf67ccb4c5bb" - integrity sha512-utFqC5BaA3JmznbissSs95X1ZF+d+4WuOWwpM9+Ak356YtMhHE/GXUondZdcyAAOTBEsRGAgH/0TwLzfI9h7ow== - dependencies: - "@jest/console" "^24.7.1" - "@jest/environment" "^24.8.0" - "@jest/test-result" "^24.8.0" - "@jest/types" "^24.8.0" - chalk "^2.4.2" + chalk "^4.0.0" + graceful-fs "^4.2.4" + micromatch "^4.0.2" + slash "^3.0.0" + stack-utils "^2.0.2" + +jest-mock@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/jest-mock/-/jest-mock-26.3.0.tgz#ee62207c3c5ebe5f35b760e1267fee19a1cfdeba" + integrity sha512-PeaRrg8Dc6mnS35gOo/CbZovoDPKAeB1FICZiuagAgGvbWdNNyjQjkOaGUa/3N3JtpQ/Mh9P4A2D4Fv51NnP8Q== + dependencies: + "@jest/types" "^26.3.0" + "@types/node" "*" + +jest-pnp-resolver@^1.2.2: + version "1.2.2" + resolved "https://registry.yarnpkg.com/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz#b704ac0ae028a89108a4d040b3f919dfddc8e33c" + integrity sha512-olV41bKSMm8BdnuMsewT4jqlZ8+3TCARAXjZGT9jcoSnrfUnRCqnMoF9XEeoWjbzObpqF9dRhHQj0Xb9QdF6/w== + +jest-regex-util@^26.0.0: + version "26.0.0" + resolved "https://registry.yarnpkg.com/jest-regex-util/-/jest-regex-util-26.0.0.tgz#d25e7184b36e39fd466c3bc41be0971e821fee28" + integrity sha512-Gv3ZIs/nA48/Zvjrl34bf+oD76JHiGDUxNOVgUjh3j890sblXryjY4rss71fPtD/njchl6PSE2hIhvyWa1eT0A== + +jest-resolve-dependencies@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest-resolve-dependencies/-/jest-resolve-dependencies-26.4.2.tgz#739bdb027c14befb2fe5aabbd03f7bab355f1dc5" + integrity sha512-ADHaOwqEcVc71uTfySzSowA/RdxUpCxhxa2FNLiin9vWLB1uLPad3we+JSSROq5+SrL9iYPdZZF8bdKM7XABTQ== + dependencies: + "@jest/types" "^26.3.0" + jest-regex-util "^26.0.0" + jest-snapshot "^26.4.2" + +jest-resolve@^26.4.0: + version "26.4.0" + resolved "https://registry.yarnpkg.com/jest-resolve/-/jest-resolve-26.4.0.tgz#6dc0af7fb93e65b73fec0368ca2b76f3eb59a6d7" + integrity sha512-bn/JoZTEXRSlEx3+SfgZcJAVuTMOksYq9xe9O6s4Ekg84aKBObEaVXKOEilULRqviSLAYJldnoWV9c07kwtiCg== + dependencies: + "@jest/types" "^26.3.0" + chalk "^4.0.0" + graceful-fs "^4.2.4" + jest-pnp-resolver "^1.2.2" + jest-util "^26.3.0" + read-pkg-up "^7.0.1" + resolve "^1.17.0" + slash "^3.0.0" + +jest-runner@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest-runner/-/jest-runner-26.4.2.tgz#c3ec5482c8edd31973bd3935df5a449a45b5b853" + integrity sha512-FgjDHeVknDjw1gRAYaoUoShe1K3XUuFMkIaXbdhEys+1O4bEJS8Avmn4lBwoMfL8O5oFTdWYKcf3tEJyyYyk8g== + dependencies: + "@jest/console" "^26.3.0" + "@jest/environment" "^26.3.0" + "@jest/test-result" "^26.3.0" + "@jest/types" "^26.3.0" + "@types/node" "*" + chalk "^4.0.0" + emittery "^0.7.1" exit "^0.1.2" - graceful-fs "^4.1.15" - jest-config "^24.8.0" - jest-docblock "^24.3.0" - jest-haste-map "^24.8.0" - jest-jasmine2 "^24.8.0" - jest-leak-detector "^24.8.0" - jest-message-util "^24.8.0" - jest-resolve "^24.8.0" - jest-runtime "^24.8.0" - jest-util "^24.8.0" - jest-worker "^24.6.0" + graceful-fs "^4.2.4" + jest-config "^26.4.2" + jest-docblock "^26.0.0" + jest-haste-map "^26.3.0" + jest-leak-detector "^26.4.2" + jest-message-util "^26.3.0" + jest-resolve "^26.4.0" + jest-runtime "^26.4.2" + jest-util "^26.3.0" + jest-worker "^26.3.0" source-map-support "^0.5.6" - throat "^4.0.0" - -jest-runtime@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-runtime/-/jest-runtime-24.8.0.tgz#05f94d5b05c21f6dc54e427cd2e4980923350620" - integrity sha512-Mq0aIXhvO/3bX44ccT+czU1/57IgOMyy80oM0XR/nyD5zgBcesF84BPabZi39pJVA6UXw+fY2Q1N+4BiVUBWOA== - dependencies: - "@jest/console" "^24.7.1" - "@jest/environment" "^24.8.0" - "@jest/source-map" "^24.3.0" - "@jest/transform" "^24.8.0" - "@jest/types" "^24.8.0" - "@types/yargs" "^12.0.2" - chalk "^2.0.1" + throat "^5.0.0" + +jest-runtime@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest-runtime/-/jest-runtime-26.4.2.tgz#94ce17890353c92e4206580c73a8f0c024c33c42" + integrity sha512-4Pe7Uk5a80FnbHwSOk7ojNCJvz3Ks2CNQWT5Z7MJo4tX0jb3V/LThKvD9tKPNVNyeMH98J/nzGlcwc00R2dSHQ== + dependencies: + "@jest/console" "^26.3.0" + "@jest/environment" "^26.3.0" + "@jest/fake-timers" "^26.3.0" + "@jest/globals" "^26.4.2" + "@jest/source-map" "^26.3.0" + "@jest/test-result" "^26.3.0" + "@jest/transform" "^26.3.0" + "@jest/types" "^26.3.0" + "@types/yargs" "^15.0.0" + chalk "^4.0.0" + collect-v8-coverage "^1.0.0" exit "^0.1.2" glob "^7.1.3" - graceful-fs "^4.1.15" - jest-config "^24.8.0" - jest-haste-map "^24.8.0" - jest-message-util "^24.8.0" - jest-mock "^24.8.0" - jest-regex-util "^24.3.0" - jest-resolve "^24.8.0" - jest-snapshot "^24.8.0" - jest-util "^24.8.0" - jest-validate "^24.8.0" - realpath-native "^1.1.0" - slash "^2.0.0" - strip-bom "^3.0.0" - yargs "^12.0.2" - -jest-serializer@^24.4.0: - version "24.4.0" - resolved "https://registry.yarnpkg.com/jest-serializer/-/jest-serializer-24.4.0.tgz#f70c5918c8ea9235ccb1276d232e459080588db3" - integrity sha512-k//0DtglVstc1fv+GY/VHDIjrtNjdYvYjMlbLUed4kxrE92sIUewOi5Hj3vrpB8CXfkJntRPDRjCrCvUhBdL8Q== - -jest-snapshot@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-snapshot/-/jest-snapshot-24.8.0.tgz#3bec6a59da2ff7bc7d097a853fb67f9d415cb7c6" - integrity sha512-5ehtWoc8oU9/cAPe6fez6QofVJLBKyqkY2+TlKTOf0VllBB/mqUNdARdcjlZrs9F1Cv+/HKoCS/BknT0+tmfPg== + graceful-fs "^4.2.4" + jest-config "^26.4.2" + jest-haste-map "^26.3.0" + jest-message-util "^26.3.0" + jest-mock "^26.3.0" + jest-regex-util "^26.0.0" + jest-resolve "^26.4.0" + jest-snapshot "^26.4.2" + jest-util "^26.3.0" + jest-validate "^26.4.2" + slash "^3.0.0" + strip-bom "^4.0.0" + yargs "^15.3.1" + +jest-serializer@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/jest-serializer/-/jest-serializer-26.3.0.tgz#1c9d5e1b74d6e5f7e7f9627080fa205d976c33ef" + integrity sha512-IDRBQBLPlKa4flg77fqg0n/pH87tcRKwe8zxOVTWISxGpPHYkRZ1dXKyh04JOja7gppc60+soKVZ791mruVdow== + dependencies: + "@types/node" "*" + graceful-fs "^4.2.4" + +jest-snapshot@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest-snapshot/-/jest-snapshot-26.4.2.tgz#87d3ac2f2bd87ea8003602fbebd8fcb9e94104f6" + integrity sha512-N6Uub8FccKlf5SBFnL2Ri/xofbaA68Cc3MGjP/NuwgnsvWh+9hLIR/DhrxbSiKXMY9vUW5dI6EW1eHaDHqe9sg== dependencies: "@babel/types" "^7.0.0" - "@jest/types" "^24.8.0" - chalk "^2.0.1" - expect "^24.8.0" - jest-diff "^24.8.0" - jest-matcher-utils "^24.8.0" - jest-message-util "^24.8.0" - jest-resolve "^24.8.0" - mkdirp "^0.5.1" + "@jest/types" "^26.3.0" + "@types/prettier" "^2.0.0" + chalk "^4.0.0" + expect "^26.4.2" + graceful-fs "^4.2.4" + jest-diff "^26.4.2" + jest-get-type "^26.3.0" + jest-haste-map "^26.3.0" + jest-matcher-utils "^26.4.2" + jest-message-util "^26.3.0" + jest-resolve "^26.4.0" natural-compare "^1.4.0" - pretty-format "^24.8.0" - semver "^5.5.0" + pretty-format "^26.4.2" + semver "^7.3.2" -jest-util@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-util/-/jest-util-24.8.0.tgz#41f0e945da11df44cc76d64ffb915d0716f46cd1" - integrity sha512-DYZeE+XyAnbNt0BG1OQqKy/4GVLPtzwGx5tsnDrFcax36rVE3lTA5fbvgmbVPUZf9w77AJ8otqR4VBbfFJkUZA== +jest-util@26.x, jest-util@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/jest-util/-/jest-util-26.3.0.tgz#a8974b191df30e2bf523ebbfdbaeb8efca535b3e" + integrity sha512-4zpn6bwV0+AMFN0IYhH/wnzIQzRaYVrz1A8sYnRnj4UXDXbOVtWmlaZkO9mipFqZ13okIfN87aDoJWB7VH6hcw== dependencies: - "@jest/console" "^24.7.1" - "@jest/fake-timers" "^24.8.0" - "@jest/source-map" "^24.3.0" - "@jest/test-result" "^24.8.0" - "@jest/types" "^24.8.0" - callsites "^3.0.0" - chalk "^2.0.1" - graceful-fs "^4.1.15" + "@jest/types" "^26.3.0" + "@types/node" "*" + chalk "^4.0.0" + graceful-fs "^4.2.4" is-ci "^2.0.0" - mkdirp "^0.5.1" - slash "^2.0.0" - source-map "^0.6.0" + micromatch "^4.0.2" + +jest-validate@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest-validate/-/jest-validate-26.4.2.tgz#e871b0dfe97747133014dcf6445ee8018398f39c" + integrity sha512-blft+xDX7XXghfhY0mrsBCYhX365n8K5wNDC4XAcNKqqjEzsRUSXP44m6PL0QJEW2crxQFLLztVnJ4j7oPlQrQ== + dependencies: + "@jest/types" "^26.3.0" + camelcase "^6.0.0" + chalk "^4.0.0" + jest-get-type "^26.3.0" + leven "^3.1.0" + pretty-format "^26.4.2" + +jest-watcher@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/jest-watcher/-/jest-watcher-26.3.0.tgz#f8ef3068ddb8af160ef868400318dc4a898eed08" + integrity sha512-XnLdKmyCGJ3VoF6G/p5ohbJ04q/vv5aH9ENI+i6BL0uu9WWB6Z7Z2lhQQk0d2AVZcRGp1yW+/TsoToMhBFPRdQ== + dependencies: + "@jest/test-result" "^26.3.0" + "@jest/types" "^26.3.0" + "@types/node" "*" + ansi-escapes "^4.2.1" + chalk "^4.0.0" + jest-util "^26.3.0" + string-length "^4.0.1" -jest-validate@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-validate/-/jest-validate-24.8.0.tgz#624c41533e6dfe356ffadc6e2423a35c2d3b4849" - integrity sha512-+/N7VOEMW1Vzsrk3UWBDYTExTPwf68tavEPKDnJzrC6UlHtUDU/fuEdXqFoHzv9XnQ+zW6X3qMZhJ3YexfeLDA== +jest-worker@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-26.3.0.tgz#7c8a97e4f4364b4f05ed8bca8ca0c24de091871f" + integrity sha512-Vmpn2F6IASefL+DVBhPzI2J9/GJUsqzomdeN+P+dK8/jKxbh8R3BtFnx3FIta7wYlPU62cpJMJQo4kuOowcMnw== dependencies: - "@jest/types" "^24.8.0" - camelcase "^5.0.0" - chalk "^2.0.1" - jest-get-type "^24.8.0" - leven "^2.1.0" - pretty-format "^24.8.0" - -jest-watcher@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest-watcher/-/jest-watcher-24.8.0.tgz#58d49915ceddd2de85e238f6213cef1c93715de4" - integrity sha512-SBjwHt5NedQoVu54M5GEx7cl7IGEFFznvd/HNT8ier7cCAx/Qgu9ZMlaTQkvK22G1YOpcWBLQPFSImmxdn3DAw== - dependencies: - "@jest/test-result" "^24.8.0" - "@jest/types" "^24.8.0" - "@types/yargs" "^12.0.9" - ansi-escapes "^3.0.0" - chalk "^2.0.1" - jest-util "^24.8.0" - string-length "^2.0.0" - -jest-worker@^24.6.0: - version "24.6.0" - resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-24.6.0.tgz#7f81ceae34b7cde0c9827a6980c35b7cdc0161b3" - integrity sha512-jDwgW5W9qGNvpI1tNnvajh0a5IE/PuGLFmHk6aR/BZFz8tSgGw17GsDPXAJ6p91IvYDjOw8GpFbvvZGAK+DPQQ== - dependencies: - merge-stream "^1.0.1" - supports-color "^6.1.0" + "@types/node" "*" + merge-stream "^2.0.0" + supports-color "^7.0.0" -jest@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/jest/-/jest-24.8.0.tgz#d5dff1984d0d1002196e9b7f12f75af1b2809081" - integrity sha512-o0HM90RKFRNWmAWvlyV8i5jGZ97pFwkeVoGvPW1EtLTgJc2+jcuqcbbqcSZLE/3f2S5pt0y2ZBETuhpWNl1Reg== +jest@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/jest/-/jest-26.4.2.tgz#7e8bfb348ec33f5459adeaffc1a25d5752d9d312" + integrity sha512-LLCjPrUh98Ik8CzW8LLVnSCfLaiY+wbK53U7VxnFSX7Q+kWC4noVeDvGWIFw0Amfq1lq2VfGm7YHWSLBV62MJw== dependencies: - import-local "^2.0.0" - jest-cli "^24.8.0" + "@jest/core" "^26.4.2" + import-local "^3.0.2" + jest-cli "^26.4.2" + +jmespath@^0.15.0: + version "0.15.0" + resolved "https://registry.yarnpkg.com/jmespath/-/jmespath-0.15.0.tgz#a3f222a9aae9f966f5d27c796510e28091764217" + integrity sha1-o/Iiqarp+Wb10nx5ZRDigJF2Qhc= + +joycon@^2.2.5: + version "2.2.5" + resolved "https://registry.yarnpkg.com/joycon/-/joycon-2.2.5.tgz#8d4cf4cbb2544d7b7583c216fcdfec19f6be1615" + integrity sha512-YqvUxoOcVPnCp0VU1/56f+iKSdvIRJYPznH22BdXV3xMk75SFXhWeJkZ8C9XxUWt1b5x2X1SxuFygW1U0FmkEQ== "js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== +js-yaml@^3.13.1, js-yaml@^3.14.0: + version "3.14.0" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.0.tgz#a7a34170f26a21bb162424d8adacb4113a69e482" + integrity sha512-/4IbIeHcD9VMHFqDR/gQ7EdZdLimOvW2DdcxFjdyyZ9NsbS+ccrXqVWDtab/lRl5AlUqmpBx8EhPaWR+OtY17A== + dependencies: + argparse "^1.0.7" + esprima "^4.0.0" + jsbn@~0.1.0: version "0.1.1" resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" integrity sha1-peZUwuWi3rXyAdls77yoDA7y9RM= -jsdom@^11.5.1: - version "11.12.0" - resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-11.12.0.tgz#1a80d40ddd378a1de59656e9e6dc5a3ba8657bc8" - integrity sha512-y8Px43oyiBM13Zc1z780FrfNLJCXTL40EWlty/LXUtcjykRBNgLlCjWXpfSPBl2iv+N7koQN+dvqszHZgT/Fjw== - dependencies: - abab "^2.0.0" - acorn "^5.5.3" - acorn-globals "^4.1.0" - array-equal "^1.0.0" - cssom ">= 0.3.2 < 0.4.0" - cssstyle "^1.0.0" - data-urls "^1.0.0" - domexception "^1.0.1" - escodegen "^1.9.1" - html-encoding-sniffer "^1.0.2" - left-pad "^1.3.0" - nwsapi "^2.0.7" - parse5 "4.0.0" - pn "^1.1.0" - request "^2.87.0" - request-promise-native "^1.0.5" - sax "^1.2.4" - symbol-tree "^3.2.2" - tough-cookie "^2.3.4" - w3c-hr-time "^1.0.1" - webidl-conversions "^4.0.2" - whatwg-encoding "^1.0.3" - whatwg-mimetype "^2.1.0" - whatwg-url "^6.4.1" - ws "^5.2.0" +jsdom@^16.2.2: + version "16.4.0" + resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-16.4.0.tgz#36005bde2d136f73eee1a830c6d45e55408edddb" + integrity sha512-lYMm3wYdgPhrl7pDcRmvzPhhrGVBeVhPIqeHjzeiHN3DFmD1RBpbExbi8vU7BJdH8VAZYovR8DMt0PNNDM7k8w== + dependencies: + abab "^2.0.3" + acorn "^7.1.1" + acorn-globals "^6.0.0" + cssom "^0.4.4" + cssstyle "^2.2.0" + data-urls "^2.0.0" + decimal.js "^10.2.0" + domexception "^2.0.1" + escodegen "^1.14.1" + html-encoding-sniffer "^2.0.1" + is-potential-custom-element-name "^1.0.0" + nwsapi "^2.2.0" + parse5 "5.1.1" + request "^2.88.2" + request-promise-native "^1.0.8" + saxes "^5.0.0" + symbol-tree "^3.2.4" + tough-cookie "^3.0.1" + w3c-hr-time "^1.0.2" + w3c-xmlserializer "^2.0.0" + webidl-conversions "^6.1.0" + whatwg-encoding "^1.0.5" + whatwg-mimetype "^2.3.0" + whatwg-url "^8.0.0" + ws "^7.2.3" xml-name-validator "^3.0.0" jsesc@^2.5.1: @@ -2538,10 +2993,10 @@ jsesc@^2.5.1: resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-2.5.2.tgz#80564d2e483dacf6e8ef209650a67df3f0c283a4" integrity sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA== -json-parse-better-errors@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz#bb867cfb3450e69107c131d1c514bab3dc8bcaa9" - integrity sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw== +json-parse-even-better-errors@^2.3.0: + version "2.3.1" + resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" + integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== json-schema-traverse@^0.4.1: version "0.4.1" @@ -2558,12 +3013,12 @@ json-stringify-safe@~5.0.1: resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" integrity sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus= -json5@2.x, json5@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/json5/-/json5-2.1.0.tgz#e7a0c62c48285c628d20a10b85c89bb807c32850" - integrity sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ== +json5@2.x, json5@^2.1.2: + version "2.1.3" + resolved "https://registry.yarnpkg.com/json5/-/json5-2.1.3.tgz#c9b0f7fa9233bfe5807fe66fcf3a5617ed597d43" + integrity sha512-KXPvOm8K9IJKFM0bmdn8QXh7udDh1g/giieX0NLCaMnb4hEiVFqnop2ImTXCc5e0/oHz3LTqmHGtExn5hfMkOA== dependencies: - minimist "^1.2.0" + minimist "^1.2.5" jsprim@^1.2.2: version "1.4.1" @@ -2595,32 +3050,25 @@ kind-of@^5.0.0: integrity sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw== kind-of@^6.0.0, kind-of@^6.0.2: - version "6.0.2" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.2.tgz#01146b36a6218e64e58f3a8d66de5d7fc6f6d051" - integrity sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA== + version "6.0.3" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" + integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== -kleur@^3.0.2: +kleur@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e" integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w== -lcid@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/lcid/-/lcid-2.0.0.tgz#6ef5d2df60e52f82eb228a4c373e8d1f397253cf" - integrity sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA== - dependencies: - invert-kv "^2.0.0" - -left-pad@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/left-pad/-/left-pad-1.3.0.tgz#5b8a3a7765dfe001261dde915589e782f8c94d1e" - integrity sha512-XI5MPzVNApjAyhQzphX8BkmKsKUxD4LdyK24iZeQGinBN9yTQT3bFlCBy/aVx2HrNcqQGsdot8ghrjyrvMCoEA== - -leven@^2.1.0: +leven@2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/leven/-/leven-2.1.0.tgz#c2e7a9f772094dee9d34202ae8acce4687875580" integrity sha1-wuep93IJTe6dNCAq6KzORoeHVYA= +leven@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/leven/-/leven-3.1.0.tgz#77891de834064cccba82ae7842bb6b14a13ed7f2" + integrity sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A== + levn@~0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" @@ -2629,15 +3077,10 @@ levn@~0.3.0: prelude-ls "~1.1.2" type-check "~0.3.2" -load-json-file@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-4.0.0.tgz#2f5f45ab91e33216234fd53adab668eb4ec0993b" - integrity sha1-L19Fq5HjMhYjT9U62rZo607AmTs= - dependencies: - graceful-fs "^4.1.2" - parse-json "^4.0.0" - pify "^3.0.0" - strip-bom "^3.0.0" +lines-and-columns@^1.1.6: + version "1.1.6" + resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00" + integrity sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA= locate-path@^3.0.0: version "3.0.0" @@ -2647,42 +3090,34 @@ locate-path@^3.0.0: p-locate "^3.0.0" path-exists "^3.0.0" -lodash.get@^4.4.2: - version "4.4.2" - resolved "https://registry.yarnpkg.com/lodash.get/-/lodash.get-4.4.2.tgz#2d177f652fa31e939b4438d5341499dfa3825e99" - integrity sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk= +locate-path@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" + integrity sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g== + dependencies: + p-locate "^4.1.0" -lodash.set@^4.3.2: - version "4.3.2" - resolved "https://registry.yarnpkg.com/lodash.set/-/lodash.set-4.3.2.tgz#d8757b1da807dde24816b0d6a84bea1a76230b23" - integrity sha1-2HV7HagH3eJIFrDWqEvqGnYjCyM= +lodash.memoize@4.x: + version "4.1.2" + resolved "https://registry.yarnpkg.com/lodash.memoize/-/lodash.memoize-4.1.2.tgz#bcc6c49a42a2840ed997f323eada5ecd182e0bfe" + integrity sha1-vMbEmkKihA7Zl/Mj6tpezRguC/4= lodash.sortby@^4.7.0: version "4.7.0" resolved "https://registry.yarnpkg.com/lodash.sortby/-/lodash.sortby-4.7.0.tgz#edd14c824e2cc9c1e0b0a1b42bb5210516a42438" integrity sha1-7dFMgk4sycHgsKG0K7UhBRakJDg= -lodash.unescape@4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/lodash.unescape/-/lodash.unescape-4.0.1.tgz#bf2249886ce514cda112fae9218cdc065211fc9c" - integrity sha1-vyJJiGzlFM2hEvrpIYzcBlIR/Jw= - -lodash.uniq@^4.5.0: - version "4.5.0" - resolved "https://registry.yarnpkg.com/lodash.uniq/-/lodash.uniq-4.5.0.tgz#d0225373aeb652adc1bc82e4945339a842754773" - integrity sha1-0CJTc662Uq3BvILklFM5qEJ1R3M= - -lodash@^4.17.11: - version "4.17.11" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.11.tgz#b39ea6229ef607ecd89e2c8df12536891cac9b8d" - integrity sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg== +lodash@^4.17.15, lodash@^4.17.19: + version "4.17.20" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.20.tgz#b44a9b6297bcb698f1c51a3545a2b3b368d59c52" + integrity sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA== -log-symbols@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-2.2.0.tgz#5740e1c5d6f0dfda4ad9323b5332107ef6b4c40a" - integrity sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg== +log-symbols@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-3.0.0.tgz#f3a08516a5dea893336a7dee14d18a1cfdab77c4" + integrity sha512-dSkNGuI7iG3mfvDzUuYZyvk5dD9ocYCYzNU6CYDE6+Xqd+gwme6Z00NS3dUh8mq/73HaEtT7m6W+yUPtU6BZnQ== dependencies: - chalk "^2.0.1" + chalk "^2.4.2" loose-envify@^1.0.0: version "1.4.0" @@ -2691,28 +3126,34 @@ loose-envify@^1.0.0: dependencies: js-tokens "^3.0.0 || ^4.0.0" -macos-release@^2.2.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/macos-release/-/macos-release-2.3.0.tgz#eb1930b036c0800adebccd5f17bc4c12de8bb71f" - integrity sha512-OHhSbtcviqMPt7yfw5ef5aghS2jzFVKEFyCJndQt2YpSQ9qRVSEv2axSJI1paVThEu+FFGs584h/1YhxjVqajA== - -madge@^3.4.4: - version "3.4.4" - resolved "https://registry.yarnpkg.com/madge/-/madge-3.4.4.tgz#f0b254a78f6e0fb54bb8dfe5ffdee3caee280b3d" - integrity sha512-ywk2Zca1Qn3FMH4btNcJN9q3z2+AZhJeUCzUMbUwSL/xmevCC4CzBQNF6i22V1SJ8cbXLKrXrJ6k0QQPtd9/KQ== +madge@^3.9.2: + version "3.9.2" + resolved "https://registry.yarnpkg.com/madge/-/madge-3.9.2.tgz#a432de2c858092d379c2910a21a622ad2b1b24c7" + integrity sha512-6ZvyKinAOOzcRpvpm1iyOuds+LvWIq3o3GmUYAHMJdIpDAgVY3mphxVzeWNo3agIOv0X0T/zbLycXQm9Rn19nA== dependencies: - chalk "^2.4.1" - commander "^2.15.1" + chalk "^4.1.0" + commander "^5.1.0" commondir "^1.0.1" debug "^4.0.1" - dependency-tree "^7.0.2" - graphviz "^0.0.8" - ora "^3.0.0" - pify "^4.0.0" - pluralize "^7.0.0" - pretty-ms "^4.0.0" + dependency-tree "^7.2.1" + detective-amd "^3.0.0" + detective-cjs "^3.1.1" + detective-es6 "^2.1.0" + detective-less "^1.0.2" + detective-postcss "^3.0.1" + detective-sass "^3.0.1" + detective-scss "^2.0.1" + detective-stylus "^1.0.0" + detective-typescript "^5.8.0" + graphviz "0.0.9" + ora "^4.0.4" + pify "^5.0.0" + pluralize "^8.0.0" + precinct "^6.3.1" + pretty-ms "^7.0.0" rc "^1.2.7" - walkdir "^0.0.12" + typescript "^3.9.5" + walkdir "^0.4.1" make-dir@^2.1.0: version "2.1.0" @@ -2722,10 +3163,17 @@ make-dir@^2.1.0: pify "^4.0.1" semver "^5.6.0" +make-dir@^3.0.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-3.1.0.tgz#415e967046b3a7f1d185277d84aa58203726a13f" + integrity sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw== + dependencies: + semver "^6.0.0" + make-error@1.x, make-error@^1.1.1: - version "1.3.5" - resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.5.tgz#efe4e81f6db28cadd605c70f29c831b58ef776c8" - integrity sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g== + version "1.3.6" + resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2" + integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== makeerror@1.0.x: version "1.0.11" @@ -2734,13 +3182,6 @@ makeerror@1.0.x: dependencies: tmpl "1.0.x" -map-age-cleaner@^0.1.1: - version "0.1.3" - resolved "https://registry.yarnpkg.com/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz#7d583a7306434c055fe474b0f45078e6e1b4b92a" - integrity sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w== - dependencies: - p-defer "^1.0.0" - map-cache@^0.2.2: version "0.2.2" resolved "https://registry.yarnpkg.com/map-cache/-/map-cache-0.2.2.tgz#c32abd0bd6525d9b051645bb4f26ac5dc98a0dbf" @@ -2753,19 +3194,10 @@ map-visit@^1.0.0: dependencies: object-visit "^1.0.0" -mem@^4.0.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/mem/-/mem-4.3.0.tgz#461af497bc4ae09608cdb2e60eefb69bff744178" - integrity sha512-qX2bG48pTqYRVmDB37rn/6PT7LcR8T7oAX3bf99u1Tt1nzxYfxkgqDwUwolPlXweM0XzBOBFzSx4kfp7KP1s/w== - dependencies: - map-age-cleaner "^0.1.1" - mimic-fn "^2.0.0" - p-is-promise "^2.0.0" - -memory-fs@^0.4.0: - version "0.4.1" - resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.4.1.tgz#3a9a20b8462523e447cfbc7e8bb80ed667bfc552" - integrity sha1-OpoguEYlI+RHz7x+i7gO1me/xVI= +memory-fs@^0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.5.0.tgz#324c01288b88652966d161db77838720845a8e3c" + integrity sha512-jA0rdU5KoQMC0e6ppoNRtpp6vjFq6+NY7r8hywnC7V+1Xj/MtHwGIbB1QaK/dunyjWteJzmkpd7ooeWg10T7GA== dependencies: errno "^0.1.3" readable-stream "^2.0.1" @@ -2775,14 +3207,12 @@ memory-pager@^1.0.2: resolved "https://registry.yarnpkg.com/memory-pager/-/memory-pager-1.5.0.tgz#d8751655d22d384682741c972f2c3d6dfa3e66b5" integrity sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg== -merge-stream@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-1.0.1.tgz#4041202d508a342ba00174008df0c251b8c135e1" - integrity sha1-QEEgLVCKNCugAXQAjfDCUbjBNeE= - dependencies: - readable-stream "^2.0.1" +merge-stream@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" + integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== -micromatch@^3.1.10, micromatch@^3.1.4: +micromatch@^3.1.4: version "3.1.10" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23" integrity sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg== @@ -2801,24 +3231,27 @@ micromatch@^3.1.10, micromatch@^3.1.4: snapdragon "^0.8.1" to-regex "^3.0.2" -mime-db@1.40.0: - version "1.40.0" - resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.40.0.tgz#a65057e998db090f732a68f6c276d387d4126c32" - integrity sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA== +micromatch@^4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.2.tgz#4fcb0999bf9fbc2fcbdd212f6d629b9a56c39259" + integrity sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q== + dependencies: + braces "^3.0.1" + picomatch "^2.0.5" + +mime-db@1.44.0: + version "1.44.0" + resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.44.0.tgz#fa11c5eb0aca1334b4233cb4d52f10c5a6272f92" + integrity sha512-/NOTfLrsPBVeH7YtFPgsVWveuL+4SjjYxaQ1xtM1KMFj7HdxlBlxeyNLzhyJVx7r4rZGJAZ/6lkKCitSc/Nmpg== mime-types@^2.1.12, mime-types@~2.1.19: - version "2.1.24" - resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.24.tgz#b6f8d0b3e951efb77dedeca194cff6d16f676f81" - integrity sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ== + version "2.1.27" + resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.27.tgz#47949f98e279ea53119f5722e0f34e529bec009f" + integrity sha512-JIhqnCasI9yD+SsmkquHBxTSEuZdQX5BuQnS2Vc7puQQQ+8yiP5AY5uWhpdv4YL4VM5c6iliiYWPgJ/nJQLp7w== dependencies: - mime-db "1.40.0" + mime-db "1.44.0" -mimic-fn@^1.0.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-1.2.0.tgz#820c86a39334640e99516928bd03fca88057d022" - integrity sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ== - -mimic-fn@^2.0.0: +mimic-fn@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== @@ -2830,40 +3263,10 @@ minimatch@^3.0.4: dependencies: brace-expansion "^1.1.7" -minimist@0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" - integrity sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0= - -minimist@1.1.x: - version "1.1.3" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.1.3.tgz#3bedfd91a92d39016fcfaa1c681e8faa1a1efda8" - integrity sha1-O+39kaktOQFvz6ocaB6Pqhoe/ag= - -minimist@^1.1.1, minimist@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" - integrity sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ= - -minimist@~0.0.1: - version "0.0.10" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf" - integrity sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8= - -minipass@^2.2.1, minipass@^2.3.5: - version "2.3.5" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-2.3.5.tgz#cacebe492022497f656b0f0f51e2682a9ed2d848" - integrity sha512-Gi1W4k059gyRbyVUZQ4mEqLm0YIUiGYfvxhF6SIlk3ui1WVxMTGfGdQ2SInh3PDrRTVvPKgULkpJtT4RH10+VA== - dependencies: - safe-buffer "^5.1.2" - yallist "^3.0.0" - -minizlib@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-1.2.1.tgz#dd27ea6136243c7c880684e8672bb3a45fd9b614" - integrity sha512-7+4oTUOWKg7AuL3vloEWekXY2/D20cevzsrNT2kGWm+39J9hGTCBv8VI5Pm5lXZ/o3/mdR4f8rflAPhnQb8mPA== - dependencies: - minipass "^2.2.1" +minimist@^1.1.0, minimist@^1.1.1, minimist@^1.2.0, minimist@^1.2.5: + version "1.2.5" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602" + integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw== mixin-deep@^1.2.0: version "1.3.2" @@ -2873,19 +3276,17 @@ mixin-deep@^1.2.0: for-in "^1.0.2" is-extendable "^1.0.1" -mkdirp@0.x, mkdirp@^0.5.0, mkdirp@^0.5.1: - version "0.5.1" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" - integrity sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM= - dependencies: - minimist "0.0.8" +mkdirp@1.x: + version "1.0.4" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" + integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== -module-definition@^3.0.0, module-definition@^3.1.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/module-definition/-/module-definition-3.2.0.tgz#a1741d5ddf60d76c60d5b1f41ba8744ba08d3ef4" - integrity sha512-PO6o0BajpdRR+fb3FUSeDISgJpnyxg8UDUEalR8LPQajl0M5+m4jHWhgrMGGSEl6D9+sVl/l1fjOCvpBXIQ+2Q== +module-definition@^3.0.0, module-definition@^3.3.0: + version "3.3.0" + resolved "https://registry.yarnpkg.com/module-definition/-/module-definition-3.3.0.tgz#aae06d68c99c5f93841e59b8a4469b974956d4d4" + integrity sha512-HTplA9xwDzH67XJFC1YvZMUElWJD28DV0dUq7lhTs+JKJamUOWA/CcYWSlhW5amJO66uWtY7XdltT+LfX0wIVg== dependencies: - ast-module-types "^2.4.0" + ast-module-types "^2.6.0" node-source-walk "^4.0.0" module-lookup-amd@^6.1.0: @@ -2900,24 +3301,23 @@ module-lookup-amd@^6.1.0: requirejs "^2.3.5" requirejs-config-file "^3.1.1" -mongodb-core@3.2.7: - version "3.2.7" - resolved "https://registry.yarnpkg.com/mongodb-core/-/mongodb-core-3.2.7.tgz#a8ef1fe764a192c979252dacbc600dc88d77e28f" - integrity sha512-WypKdLxFNPOH/Jy6i9z47IjG2wIldA54iDZBmHMINcgKOUcWJh8og+Wix76oGd7EyYkHJKssQ2FAOw5Su/n4XQ== +mongodb@^3.6.1: + version "3.6.2" + resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-3.6.2.tgz#1154a4ac107bf1375112d83a29c5cf97704e96b6" + integrity sha512-sSZOb04w3HcnrrXC82NEh/YGCmBuRgR+C1hZgmmv4L6dBz4BkRse6Y8/q/neXer9i95fKUBbFi4KgeceXmbsOA== dependencies: - bson "^1.1.1" + bl "^2.2.1" + bson "^1.1.4" + denque "^1.4.1" require_optional "^1.0.1" safe-buffer "^5.1.2" optionalDependencies: saslprep "^1.0.0" -mongodb@^3.2.7: - version "3.2.7" - resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-3.2.7.tgz#8ba149e4be708257cad0dea72aebb2bbb311a7ac" - integrity sha512-2YdWrdf1PJgxcCrT1tWoL6nHuk6hCxhddAAaEh8QJL231ci4+P9FLyqopbTm2Z2sAU6mhCri+wd9r1hOcHdoMw== - dependencies: - mongodb-core "3.2.7" - safe-buffer "^5.1.2" +mri@1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/mri/-/mri-1.1.4.tgz#7cb1dd1b9b40905f1fac053abe25b6720f44744a" + integrity sha512-6y7IjGPm8AzlvoUrwAaw1tLnUBudaS3752vcd8JtrpGGQn+rXIe63LFVHm/YMwtqAuh+LJPCFdlLYPWM1nYn6w== ms@2.0.0: version "2.0.0" @@ -2929,10 +3329,10 @@ ms@^2.1.1: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== -nan@^2.12.1: - version "2.14.0" - resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.0.tgz#7818f722027b2459a86f0295d434d1fc2336c52c" - integrity sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg== +mute-stream@0.0.8: + version "0.0.8" + resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.8.tgz#1630c42b2251ff81e2a283de96a5497ea92e5e0d" + integrity sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA== nanomatch@^1.2.9: version "1.2.13" @@ -2956,29 +3356,15 @@ natural-compare@^1.4.0: resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" integrity sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc= -needle@^2.2.1: - version "2.4.0" - resolved "https://registry.yarnpkg.com/needle/-/needle-2.4.0.tgz#6833e74975c444642590e15a750288c5f939b57c" - integrity sha512-4Hnwzr3mi5L97hMYeNl8wRW/Onhy4nUKR/lVemJ8gJedxxUyBLm9kkrDColJvoSfwi0jCNhD+xCdOtiGDQiRZg== - dependencies: - debug "^3.2.6" - iconv-lite "^0.4.4" - sax "^1.2.4" - -neo-async@^2.6.0: - version "2.6.1" - resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.1.tgz#ac27ada66167fa8849a6addd837f6b189ad2081c" - integrity sha512-iyam8fBuCUpWeKPGpaNMetEocMt364qkCsfL9JuhjXX6dRnguRVOfk2GZaDpPjcOKiiXCPINZC1GczQ7iTq3Zw== - nice-try@^1.0.4: version "1.0.5" resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366" integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ== node-fetch@^2.3.0: - version "2.6.0" - resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.0.tgz#e633456386d4aa55863f676a7ab0daa8fdecb0fd" - integrity sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA== + version "2.6.1" + resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.1.tgz#045bd323631f76ed2e2b55573394416b639a0052" + integrity sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw== node-int64@^0.4.0: version "0.4.0" @@ -2990,32 +3376,17 @@ node-modules-regexp@^1.0.0: resolved "https://registry.yarnpkg.com/node-modules-regexp/-/node-modules-regexp-1.0.0.tgz#8d9dbe28964a4ac5712e9131642107c71e90ec40" integrity sha1-jZ2+KJZKSsVxLpExZCEHxx6Q7EA= -node-notifier@^5.2.1: - version "5.4.0" - resolved "https://registry.yarnpkg.com/node-notifier/-/node-notifier-5.4.0.tgz#7b455fdce9f7de0c63538297354f3db468426e6a" - integrity sha512-SUDEb+o71XR5lXSTyivXd9J7fCloE3SyP4lSgt3lU2oSANiox+SxlNRGPjDKrwU1YN3ix2KN/VGGCg0t01rttQ== +node-notifier@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/node-notifier/-/node-notifier-8.0.0.tgz#a7eee2d51da6d0f7ff5094bc7108c911240c1620" + integrity sha512-46z7DUmcjoYdaWyXouuFNNfUo6eFa94t23c53c+lG/9Cvauk4a98rAUp9672X5dxGdQmLpPzTxzu8f/OeEPaFA== dependencies: growly "^1.3.0" - is-wsl "^1.1.0" - semver "^5.5.0" + is-wsl "^2.2.0" + semver "^7.3.2" shellwords "^0.1.1" - which "^1.3.0" - -node-pre-gyp@^0.12.0: - version "0.12.0" - resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.12.0.tgz#39ba4bb1439da030295f899e3b520b7785766149" - integrity sha512-4KghwV8vH5k+g2ylT+sLTjy5wmUOb9vPhnM8NHvRf9dHmnW/CndrFXy2aRPaPST6dugXSdHXfeaHQm77PIz/1A== - dependencies: - detect-libc "^1.0.2" - mkdirp "^0.5.1" - needle "^2.2.1" - nopt "^4.0.1" - npm-packlist "^1.1.6" - npmlog "^4.0.2" - rc "^1.2.7" - rimraf "^2.6.1" - semver "^5.3.0" - tar "^4" + uuid "^8.3.0" + which "^2.0.2" node-source-walk@^4.0.0, node-source-walk@^4.2.0: version "4.2.0" @@ -3024,15 +3395,7 @@ node-source-walk@^4.0.0, node-source-walk@^4.2.0: dependencies: "@babel/parser" "^7.0.0" -nopt@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/nopt/-/nopt-4.0.1.tgz#d0d4685afd5415193c8c7505602d0d17cd64474d" - integrity sha1-0NRoWv1UFRk8jHUFYC0NF81kR00= - dependencies: - abbrev "1" - osenv "^0.1.4" - -normalize-package-data@^2.3.2: +normalize-package-data@^2.5.0: version "2.5.0" resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz#e66db1838b200c1dfc233225d12cb36520e234a8" integrity sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA== @@ -3049,18 +3412,10 @@ normalize-path@^2.1.1: dependencies: remove-trailing-separator "^1.0.1" -npm-bundled@^1.0.1: - version "1.0.6" - resolved "https://registry.yarnpkg.com/npm-bundled/-/npm-bundled-1.0.6.tgz#e7ba9aadcef962bb61248f91721cd932b3fe6bdd" - integrity sha512-8/JCaftHwbd//k6y2rEWp6k1wxVfpFzB6t1p825+cUb7Ym2XQfhwIC5KwhrvzZRJu+LtDE585zVaS32+CGtf0g== - -npm-packlist@^1.1.6: - version "1.4.4" - resolved "https://registry.yarnpkg.com/npm-packlist/-/npm-packlist-1.4.4.tgz#866224233850ac534b63d1a6e76050092b5d2f44" - integrity sha512-zTLo8UcVYtDU3gdeaFu2Xu0n0EvelfHDGuqtNIn5RO7yQj4H1TqNdBc/yZjxnWA0PVB8D3Woyp0i5B43JwQ6Vw== - dependencies: - ignore-walk "^3.0.1" - npm-bundled "^1.0.1" +normalize-path@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" + integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== npm-run-path@^2.0.0: version "2.0.2" @@ -3069,36 +3424,23 @@ npm-run-path@^2.0.0: dependencies: path-key "^2.0.0" -npmlog@^4.0.2: - version "4.1.2" - resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-4.1.2.tgz#08a7f2a8bf734604779a9efa4ad5cc717abb954b" - integrity sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg== +npm-run-path@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-4.0.1.tgz#b7ecd1e5ed53da8e37a55e1c2269e0b97ed748ea" + integrity sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw== dependencies: - are-we-there-yet "~1.1.2" - console-control-strings "~1.1.0" - gauge "~2.7.3" - set-blocking "~2.0.0" + path-key "^3.0.0" -number-is-nan@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" - integrity sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0= - -nwsapi@^2.0.7: - version "2.1.4" - resolved "https://registry.yarnpkg.com/nwsapi/-/nwsapi-2.1.4.tgz#e006a878db23636f8e8a67d33ca0e4edf61a842f" - integrity sha512-iGfd9Y6SFdTNldEy2L0GUhcarIutFmk+MPWIn9dmj8NMIup03G08uUF2KGbbmv/Ux4RT0VZJoP/sVbWA6d/VIw== +nwsapi@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/nwsapi/-/nwsapi-2.2.0.tgz#204879a9e3d068ff2a55139c2c772780681a38b7" + integrity sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ== oauth-sign@~0.9.0: version "0.9.0" resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.9.0.tgz#47a7b016baa68b5fa0ecf3dee08a85c679ac6455" integrity sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ== -object-assign@^4.1.0: - version "4.1.1" - resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" - integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM= - object-copy@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/object-copy/-/object-copy-0.1.0.tgz#7e7d858b781bd7c991a41ba975ed3812754e998c" @@ -3108,11 +3450,6 @@ object-copy@^0.1.0: define-property "^0.2.5" kind-of "^3.0.3" -object-keys@^1.0.12: - version "1.1.1" - resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" - integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== - object-visit@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/object-visit/-/object-visit-1.0.1.tgz#f79c4493af0c5377b59fe39d395e41042dd045bb" @@ -3120,14 +3457,6 @@ object-visit@^1.0.0: dependencies: isobject "^3.0.0" -object.getownpropertydescriptors@^2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.0.3.tgz#8758c846f5b407adab0f236e0986f14b051caa16" - integrity sha1-h1jIRvW0B62rDyNuCYbxSwUcqhY= - dependencies: - define-properties "^1.1.2" - es-abstract "^1.5.1" - object.pick@^1.3.0: version "1.3.0" resolved "https://registry.yarnpkg.com/object.pick/-/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747" @@ -3135,11 +3464,6 @@ object.pick@^1.3.0: dependencies: isobject "^3.0.1" -octokit-pagination-methods@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/octokit-pagination-methods/-/octokit-pagination-methods-1.1.0.tgz#cf472edc9d551055f9ef73f6e42b4dbb4c80bea4" - integrity sha512-fZ4qZdQ2nxJvtcasX7Ghl+WlWS/d9IgnBIwFZXVNNZUmzpno91SX5bc5vuxiuKoCtK78XxGGNuSCrDC7xYB3OQ== - once@^1.3.0, once@^1.3.1, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" @@ -3147,106 +3471,53 @@ once@^1.3.0, once@^1.3.1, once@^1.4.0: dependencies: wrappy "1" -onetime@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/onetime/-/onetime-2.0.1.tgz#067428230fd67443b2794b22bba528b6867962d4" - integrity sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ= - dependencies: - mimic-fn "^1.0.0" - -optimist@^0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.6.1.tgz#da3ea74686fa21a19a111c326e90eb15a0196686" - integrity sha1-2j6nRob6IaGaERwybpDrFaAZZoY= +onetime@^5.1.0: + version "5.1.2" + resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.2.tgz#d0e96ebb56b07476df1dd9c4806e5237985ca45e" + integrity sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg== dependencies: - minimist "~0.0.1" - wordwrap "~0.0.2" + mimic-fn "^2.1.0" optionator@^0.8.1: - version "0.8.2" - resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.2.tgz#364c5e409d3f4d6301d6c0b4c05bba50180aeb64" - integrity sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q= + version "0.8.3" + resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.3.tgz#84fa1d036fe9d3c7e21d99884b601167ec8fb495" + integrity sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA== dependencies: deep-is "~0.1.3" - fast-levenshtein "~2.0.4" + fast-levenshtein "~2.0.6" levn "~0.3.0" prelude-ls "~1.1.2" type-check "~0.3.2" - wordwrap "~1.0.0" + word-wrap "~1.2.3" -ora@^3.0.0: - version "3.4.0" - resolved "https://registry.yarnpkg.com/ora/-/ora-3.4.0.tgz#bf0752491059a3ef3ed4c85097531de9fdbcd318" - integrity sha512-eNwHudNbO1folBP3JsZ19v9azXWtQZjICdr3Q0TDPIaeBQ3mXLrh54wM+er0+hSp+dWKf+Z8KM58CYzEyIYxYg== - dependencies: - chalk "^2.4.2" - cli-cursor "^2.1.0" - cli-spinners "^2.0.0" - log-symbols "^2.2.0" - strip-ansi "^5.2.0" +ora@^4.0.4: + version "4.1.1" + resolved "https://registry.yarnpkg.com/ora/-/ora-4.1.1.tgz#566cc0348a15c36f5f0e979612842e02ba9dddbc" + integrity sha512-sjYP8QyVWBpBZWD6Vr1M/KwknSw6kJOz41tvGMlwWeClHBtYKTbHMki1PsLZnxKpXMPbTKv9b3pjQu3REib96A== + dependencies: + chalk "^3.0.0" + cli-cursor "^3.1.0" + cli-spinners "^2.2.0" + is-interactive "^1.0.0" + log-symbols "^3.0.0" + mute-stream "0.0.8" + strip-ansi "^6.0.0" wcwidth "^1.0.1" -os-homedir@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" - integrity sha1-/7xJiDNuDoM94MFox+8VISGqf7M= - -os-locale@^3.0.0, os-locale@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-3.1.0.tgz#a802a6ee17f24c10483ab9935719cef4ed16bf1a" - integrity sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q== - dependencies: - execa "^1.0.0" - lcid "^2.0.0" - mem "^4.0.0" - -os-name@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/os-name/-/os-name-3.1.0.tgz#dec19d966296e1cd62d701a5a66ee1ddeae70801" - integrity sha512-h8L+8aNjNcMpo/mAIBPn5PXCM16iyPGjHNWo6U1YO8sJTMHtEtyczI6QJnLoplswm6goopQkqc7OAnjhWcugVg== - dependencies: - macos-release "^2.2.0" - windows-release "^3.1.0" - -os-tmpdir@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" - integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ= - -osenv@^0.1.4: - version "0.1.5" - resolved "https://registry.yarnpkg.com/osenv/-/osenv-0.1.5.tgz#85cdfafaeb28e8677f416e287592b5f3f49ea410" - integrity sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g== - dependencies: - os-homedir "^1.0.0" - os-tmpdir "^1.0.0" - -p-defer@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/p-defer/-/p-defer-1.0.0.tgz#9f6eb182f6c9aa8cd743004a7d4f96b196b0fb0c" - integrity sha1-n26xgvbJqozXQwBKfU+WsZaw+ww= - -p-each-series@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/p-each-series/-/p-each-series-1.0.0.tgz#930f3d12dd1f50e7434457a22cd6f04ac6ad7f71" - integrity sha1-kw89Et0fUOdDRFeiLNbwSsatf3E= - dependencies: - p-reduce "^1.0.0" +p-each-series@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/p-each-series/-/p-each-series-2.1.0.tgz#961c8dd3f195ea96c747e636b262b800a6b1af48" + integrity sha512-ZuRs1miPT4HrjFa+9fRfOFXxGJfORgelKV9f9nNOWw2gl6gVsRaVDOQP0+MI0G0wGKns1Yacsu0GjOFbTK0JFQ== p-finally@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/p-finally/-/p-finally-1.0.0.tgz#3fbcfb15b899a44123b34b6dcc18b724336a2cae" integrity sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4= -p-is-promise@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/p-is-promise/-/p-is-promise-2.1.0.tgz#918cebaea248a62cf7ffab8e3bca8c5f882fc42e" - integrity sha512-Y3W0wlRPK8ZMRbNq97l4M5otioeA5lm1z7bkNkxCka8HSPjR0xRWmpCmc9utiaLP9Jb1eD8BgeIxTW4AIF45Pg== - -p-limit@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.2.0.tgz#417c9941e6027a9abcba5092dd2904e255b5fbc2" - integrity sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ== +p-limit@^2.0.0, p-limit@^2.2.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" + integrity sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w== dependencies: p-try "^2.0.0" @@ -3257,33 +3528,56 @@ p-locate@^3.0.0: dependencies: p-limit "^2.0.0" -p-reduce@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/p-reduce/-/p-reduce-1.0.0.tgz#18c2b0dd936a4690a529f8231f58a0fdb6a47dfa" - integrity sha1-GMKw3ZNqRpClKfgjH1ig/bakffo= +p-locate@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-4.1.0.tgz#a3428bb7088b3a60292f66919278b7c297ad4f07" + integrity sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A== + dependencies: + p-limit "^2.2.0" p-try@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== -parse-json@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-4.0.0.tgz#be35f5425be1f7f6c747184f98a788cb99477ee0" - integrity sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA= +pad-left@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/pad-left/-/pad-left-2.1.0.tgz#16e6a3b2d44a8e138cb0838cc7cb403a4fc9e994" + integrity sha1-FuajstRKjhOMsIOMx8tAOk/J6ZQ= + dependencies: + repeat-string "^1.5.4" + +pad-right@^0.2.2: + version "0.2.2" + resolved "https://registry.yarnpkg.com/pad-right/-/pad-right-0.2.2.tgz#6fbc924045d244f2a2a244503060d3bfc6009774" + integrity sha1-b7ySQEXSRPKiokRQMGDTv8YAl3Q= + dependencies: + repeat-string "^1.5.2" + +parse-json@^5.0.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.1.0.tgz#f96088cdf24a8faa9aea9a009f2d9d942c999646" + integrity sha512-+mi/lmVVNKFNVyLXV31ERiy2CY5E1/F6QtJFEzoChPRwwngMNXRDQ9GJ5WdE2Z2P4AujsOi0/+2qHID68KwfIQ== dependencies: + "@babel/code-frame" "^7.0.0" error-ex "^1.3.1" - json-parse-better-errors "^1.0.1" + json-parse-even-better-errors "^2.3.0" + lines-and-columns "^1.1.6" + +parse-ms@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/parse-ms/-/parse-ms-1.0.1.tgz#56346d4749d78f23430ca0c713850aef91aa361d" + integrity sha1-VjRtR0nXjyNDDKDHE4UK75GqNh0= -parse-ms@^2.0.0: +parse-ms@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/parse-ms/-/parse-ms-2.1.0.tgz#348565a753d4391fa524029956b172cb7753097d" integrity sha512-kHt7kzLoS9VBZfUsiKjv43mr91ea+U05EyKkEtqp7vNbHxmaVuEqN7XxeEVnGrMtYOAxGrDElSi96K7EgO1zCA== -parse5@4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/parse5/-/parse5-4.0.0.tgz#6d78656e3da8d78b4ec0b906f7c08ef1dfe3f608" - integrity sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA== +parse5@5.1.1: + version "5.1.1" + resolved "https://registry.yarnpkg.com/parse5/-/parse5-5.1.1.tgz#f68e4e5ba1852ac2cadc00f4555fff6c2abb6178" + integrity sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug== pascalcase@^0.1.1: version "0.1.1" @@ -3295,6 +3589,11 @@ path-exists@^3.0.0: resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515" integrity sha1-zg6+ql94yxiSXqfYENe1mwEP1RU= +path-exists@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" + integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== + path-is-absolute@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" @@ -3305,33 +3604,70 @@ path-key@^2.0.0, path-key@^2.0.1: resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40" integrity sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A= +path-key@^3.0.0, path-key@^3.1.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" + integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== + path-parse@^1.0.6: version "1.0.6" resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c" integrity sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw== -path-type@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/path-type/-/path-type-3.0.0.tgz#cef31dc8e0a1a3bb0d105c0cd97cf3bf47f4e36f" - integrity sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg== - dependencies: - pify "^3.0.0" - performance-now@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns= -pify@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/pify/-/pify-3.0.0.tgz#e5a4acd2c101fdf3d9a4d07f0dbc4db49dd28176" - integrity sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY= +picomatch@^2.0.4, picomatch@^2.0.5: + version "2.2.2" + resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.2.tgz#21f333e9b6b8eaff02468f5146ea406d345f4dad" + integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg== -pify@^4.0.0, pify@^4.0.1: +pify@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/pify/-/pify-4.0.1.tgz#4b2cd25c50d598735c50292224fd8c6df41e3231" integrity sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g== +pify@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/pify/-/pify-5.0.0.tgz#1f5eca3f5e87ebec28cc6d54a0e4aaf00acc127f" + integrity sha512-eW/gHNMlxdSP6dmG6uJip6FXN0EQBwm2clYYd8Wul42Cwu/DK8HEftzsapcNdYe2MfLiIwZqsDk2RDEsTE79hA== + +pino-pretty@^3.2.0: + version "3.6.1" + resolved "https://registry.yarnpkg.com/pino-pretty/-/pino-pretty-3.6.1.tgz#61aabf9bf851d0ed831f7e9b813dea20f61116a3" + integrity sha512-S3bal+Yd313OEaPijbf7V+jPxVaTaRO5RQX8S/Mwdtb/8+JOgo1KolDeJTfMDTU2/k6+MHvEbxv+T1ZRfGlnjA== + dependencies: + "@hapi/bourne" "^1.3.2" + args "^5.0.1" + chalk "^2.4.2" + dateformat "^3.0.3" + fast-safe-stringify "^2.0.7" + jmespath "^0.15.0" + joycon "^2.2.5" + pump "^3.0.0" + readable-stream "^3.4.0" + split2 "^3.1.1" + strip-json-comments "^3.0.1" + +pino-std-serializers@^2.4.2: + version "2.5.0" + resolved "https://registry.yarnpkg.com/pino-std-serializers/-/pino-std-serializers-2.5.0.tgz#40ead781c65a0ce7ecd9c1c33f409d31fe712315" + integrity sha512-wXqbqSrIhE58TdrxxlfLwU9eDhrzppQDvGhBEr1gYbzzM4KKo3Y63gSjiDXRKLVS2UOXdPNR2v+KnQgNrs+xUg== + +pino@^5.13.0: + version "5.17.0" + resolved "https://registry.yarnpkg.com/pino/-/pino-5.17.0.tgz#b9def314e82402154f89a25d76a31f20ca84b4c8" + integrity sha512-LqrqmRcJz8etUjyV0ddqB6OTUutCgQULPFg2b4dtijRHUsucaAdBgSUW58vY6RFSX+NT8963F+q0tM6lNwGShA== + dependencies: + fast-redact "^2.0.0" + fast-safe-stringify "^2.0.7" + flatstr "^1.0.12" + pino-std-serializers "^2.4.2" + quick-format-unescaped "^3.0.3" + sonic-boom "^0.7.5" + pirates@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/pirates/-/pirates-4.0.1.tgz#643a92caf894566f91b2b986d2c66950a8e2fb87" @@ -3339,22 +3675,22 @@ pirates@^4.0.1: dependencies: node-modules-regexp "^1.0.0" -pkg-dir@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-3.0.0.tgz#2749020f239ed990881b1f71210d51eb6523bea3" - integrity sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw== +pkg-dir@^4.2.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-4.2.0.tgz#f099133df7ede422e81d1d8448270eeb3e4261f3" + integrity sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ== dependencies: - find-up "^3.0.0" + find-up "^4.0.0" -pluralize@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-7.0.0.tgz#298b89df8b93b0221dbf421ad2b1b1ea23fc6777" - integrity sha512-ARhBOdzS3e41FbkW/XWrTEtukqqLoK5+Z/4UeDaLuSW+39JPeFgs4gCGqsrJHVZX0fUrx//4OF0K1CUGwlIFow== +plur@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/plur/-/plur-1.0.0.tgz#db85c6814f5e5e5a3b49efc28d604fec62975156" + integrity sha1-24XGgU9eXlo7Se/CjWBP7GKXUVY= -pn@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/pn/-/pn-1.1.0.tgz#e2f4cef0e219f463c179ab37463e4e1ecdccbafb" - integrity sha512-2qHaIQr2VLRFoxe2nASzsV6ef4yOOH+Fi9FBOVH6cqeSgUnoyySPZkxzLuzd+RYOQTRpROA0ztTMqxROKSb/nA== +pluralize@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-8.0.0.tgz#1a6fa16a38d12a1901e0320fa017051c539ce3b1" + integrity sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA== posix-character-classes@^0.1.0: version "0.1.1" @@ -3371,31 +3707,31 @@ postcss-values-parser@^1.5.0: uniq "^1.0.1" postcss@^7.0.2: - version "7.0.17" - resolved "https://registry.yarnpkg.com/postcss/-/postcss-7.0.17.tgz#4da1bdff5322d4a0acaab4d87f3e782436bad31f" - integrity sha512-546ZowA+KZ3OasvQZHsbuEpysvwTZNGJv9EfyCQdsIDltPSWHAeTQ5fQy/Npi2ZDtLI3zs7Ps/p6wThErhm9fQ== + version "7.0.32" + resolved "https://registry.yarnpkg.com/postcss/-/postcss-7.0.32.tgz#4310d6ee347053da3433db2be492883d62cec59d" + integrity sha512-03eXong5NLnNCD05xscnGKGDZ98CyzoqPSMjOe6SuoQY7Z2hIj0Ld1g/O/UQRuOle2aRtiIRDg9tDcTGAkLfKw== dependencies: chalk "^2.4.2" source-map "^0.6.1" supports-color "^6.1.0" -precinct@^6.1.1: - version "6.1.2" - resolved "https://registry.yarnpkg.com/precinct/-/precinct-6.1.2.tgz#279cc694ff109969fa0f82d77e62bcfa4a6c93be" - integrity sha512-Mk+oWvR7N2D2EY+5vKNnnXPGor1aU3ZbkcHp2ER68el5PL1nmZsvpq41s69emiNMSuL6TMoIeTabvwfe5w7vNg== +precinct@^6.2.0, precinct@^6.3.1: + version "6.3.1" + resolved "https://registry.yarnpkg.com/precinct/-/precinct-6.3.1.tgz#8ad735a8afdfc48b56ed39c9ad3bf999b6b928dc" + integrity sha512-JAwyLCgTylWminoD7V0VJwMElWmwrVSR6r9HaPWCoswkB4iFzX7aNtO7VBfAVPy+NhmjKb8IF8UmlWJXzUkOIQ== dependencies: - commander "^2.19.0" + commander "^2.20.3" debug "^4.1.1" detective-amd "^3.0.0" detective-cjs "^3.1.1" - detective-es6 "^2.0.0" + detective-es6 "^2.1.0" detective-less "^1.0.2" - detective-postcss "^3.0.0" - detective-sass "^3.0.0" - detective-scss "^2.0.0" + detective-postcss "^3.0.1" + detective-sass "^3.0.1" + detective-scss "^2.0.1" detective-stylus "^1.0.0" - detective-typescript "^5.1.1" - module-definition "^3.1.0" + detective-typescript "^5.8.0" + module-definition "^3.3.0" node-source-walk "^4.2.0" prelude-ls@~1.1.2: @@ -3403,22 +3739,46 @@ prelude-ls@~1.1.2: resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ= -pretty-format@^24.8.0: - version "24.8.0" - resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-24.8.0.tgz#8dae7044f58db7cb8be245383b565a963e3c27f2" - integrity sha512-P952T7dkrDEplsR+TuY7q3VXDae5Sr7zmQb12JU/NDQa/3CH7/QW0yvqLcGN6jL+zQFKaoJcPc+yJxMTGmosqw== +prettier-bytes@^1.0.3: + version "1.0.4" + resolved "https://registry.yarnpkg.com/prettier-bytes/-/prettier-bytes-1.0.4.tgz#994b02aa46f699c50b6257b5faaa7fe2557e62d6" + integrity sha1-mUsCqkb2mcULYle1+qp/4lV+YtY= + +pretty-format@^25.2.1, pretty-format@^25.5.0: + version "25.5.0" + resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-25.5.0.tgz#7873c1d774f682c34b8d48b6743a2bf2ac55791a" + integrity sha512-kbo/kq2LQ/A/is0PQwsEHM7Ca6//bGPPvU6UnsdDRSKTWxT/ru/xb88v4BJf6a69H+uTytOEsTusT9ksd/1iWQ== + dependencies: + "@jest/types" "^25.5.0" + ansi-regex "^5.0.0" + ansi-styles "^4.0.0" + react-is "^16.12.0" + +pretty-format@^26.4.2: + version "26.4.2" + resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-26.4.2.tgz#d081d032b398e801e2012af2df1214ef75a81237" + integrity sha512-zK6Gd8zDsEiVydOCGLkoBoZuqv8VTiHyAbKznXe/gaph/DAeZOmit9yMfgIz5adIgAMMs5XfoYSwAX3jcCO1tA== + dependencies: + "@jest/types" "^26.3.0" + ansi-regex "^5.0.0" + ansi-styles "^4.0.0" + react-is "^16.12.0" + +pretty-ms@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-2.1.0.tgz#4257c256df3fb0b451d6affaab021884126981dc" + integrity sha1-QlfCVt8/sLRR1q/6qwIYhBJpgdw= dependencies: - "@jest/types" "^24.8.0" - ansi-regex "^4.0.0" - ansi-styles "^3.2.0" - react-is "^16.8.4" + is-finite "^1.0.1" + parse-ms "^1.0.0" + plur "^1.0.0" -pretty-ms@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-4.0.0.tgz#31baf41b94fd02227098aaa03bd62608eb0d6e92" - integrity sha512-qG66ahoLCwpLXD09ZPHSCbUWYTqdosB7SMP4OffgTgL2PBKXMuUsrk5Bwg8q4qPkjTXsKBMr+YK3Ltd/6F9s/Q== +pretty-ms@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-7.0.0.tgz#45781273110caf35f55cab21a8a9bd403a233dc0" + integrity sha512-J3aPWiC5e9ZeZFuSeBraGxSkGMOvulSWsxDByOcbD1Pr75YL3LSNIKIb52WXbCLE1sS5s4inBBbryjF4Y05Ceg== dependencies: - parse-ms "^2.0.0" + parse-ms "^2.1.0" process-nextick-args@~2.0.0: version "2.0.1" @@ -3426,22 +3786,22 @@ process-nextick-args@~2.0.0: integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== prompts@^2.0.1: - version "2.1.0" - resolved "https://registry.yarnpkg.com/prompts/-/prompts-2.1.0.tgz#bf90bc71f6065d255ea2bdc0fe6520485c1b45db" - integrity sha512-+x5TozgqYdOwWsQFZizE/Tra3fKvAoy037kOyU6cgz84n8f6zxngLOV4O32kTwt9FcLCxAqw0P/c8rOr9y+Gfg== + version "2.3.2" + resolved "https://registry.yarnpkg.com/prompts/-/prompts-2.3.2.tgz#480572d89ecf39566d2bd3fe2c9fccb7c4c0b068" + integrity sha512-Q06uKs2CkNYVID0VqwfAl9mipo99zkBv/n2JtWY89Yxa3ZabWSrs0e2KTudKVa3peLUvYXMefDqIleLPVUBZMA== dependencies: - kleur "^3.0.2" - sisteransi "^1.0.0" + kleur "^3.0.3" + sisteransi "^1.0.4" prr@~1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/prr/-/prr-1.0.1.tgz#d3fc114ba06995a45ec6893f484ceb1d78f5f476" integrity sha1-0/wRS6BplaRexok/SEzrHXj19HY= -psl@^1.1.24, psl@^1.1.28: - version "1.2.0" - resolved "https://registry.yarnpkg.com/psl/-/psl-1.2.0.tgz#df12b5b1b3a30f51c329eacbdef98f3a6e136dc6" - integrity sha512-GEn74ZffufCmkDDLNcl3uuyF/aSD6exEyh1v/ZSdAomB82t6G9hzJVRx0jBmLDW+VfZqks3aScmMw9DszwUalA== +psl@^1.1.28: + version "1.8.0" + resolved "https://registry.yarnpkg.com/psl/-/psl-1.8.0.tgz#9326f8bcfb013adcc005fdff056acce020e51c24" + integrity sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ== pump@^3.0.0: version "3.0.0" @@ -3451,11 +3811,6 @@ pump@^3.0.0: end-of-stream "^1.1.0" once "^1.3.1" -punycode@^1.4.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e" - integrity sha1-wNWmOycYgArY4esPpSachN1BhF4= - punycode@^2.1.0, punycode@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec" @@ -3466,6 +3821,11 @@ qs@~6.5.2: resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.2.tgz#cb3ae806e8740444584ef154ce8ee98d403f3e36" integrity sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA== +quick-format-unescaped@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/quick-format-unescaped/-/quick-format-unescaped-3.0.3.tgz#fb3e468ac64c01d22305806c39f121ddac0d1fb9" + integrity sha512-dy1yjycmn9blucmJLXOfZDx1ikZJUi6E8bBZLnhPG5gBrVhHXx2xVyqqgKBubVNEXmx51dBACMHpoMQK/N/AXQ== + rc@^1.2.7: version "1.2.8" resolved "https://registry.yarnpkg.com/rc/-/rc-1.2.8.tgz#cd924bf5200a075b83c188cd6b9e211b7fc0d3ed" @@ -3476,42 +3836,31 @@ rc@^1.2.7: minimist "^1.2.0" strip-json-comments "~2.0.1" -react-is@^16.8.4: - version "16.8.6" - resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.8.6.tgz#5bbc1e2d29141c9fbdfed456343fe2bc430a6a16" - integrity sha512-aUk3bHfZ2bRSVFFbbeVS4i+lNPZr3/WM5jT2J5omUVV1zzcs1nAaf3l51ctA5FFvCRbhrH0bdAsRRQddFJZPtA== +react-is@^16.12.0: + version "16.13.1" + resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4" + integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ== -read-pkg-up@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-4.0.0.tgz#1b221c6088ba7799601c808f91161c66e58f8978" - integrity sha512-6etQSH7nJGsK0RbG/2TeDzZFa8shjQ1um+SwQQ5cwKy0dhSXdOncEhb1CPpvQG4h7FyOV6EB6YlV0yJvZQNAkA== - dependencies: - find-up "^3.0.0" - read-pkg "^3.0.0" - -read-pkg@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-3.0.0.tgz#9cbc686978fee65d16c00e2b19c237fcf6e38389" - integrity sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k= +read-pkg-up@^7.0.1: + version "7.0.1" + resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-7.0.1.tgz#f3a6135758459733ae2b95638056e1854e7ef507" + integrity sha512-zK0TB7Xd6JpCLmlLmufqykGE+/TlOePD6qKClNW7hHDKFh/J7/7gCWGR7joEQEW1bKq3a3yUZSObOoWLFQ4ohg== dependencies: - load-json-file "^4.0.0" - normalize-package-data "^2.3.2" - path-type "^3.0.0" + find-up "^4.1.0" + read-pkg "^5.2.0" + type-fest "^0.8.1" -readable-stream@^2.0.1, readable-stream@^2.0.6: - version "2.3.6" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf" - integrity sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw== +read-pkg@^5.2.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-5.2.0.tgz#7bf295438ca5a33e56cd30e053b34ee7250c93cc" + integrity sha512-Ug69mNOpfvKDAc2Q8DRpMjjzdtrnv9HcSMX+4VsZxD1aZ6ZzrIE7rlzXBtWTyhULSMKg076AW6WR5iZpD0JiOg== dependencies: - core-util-is "~1.0.0" - inherits "~2.0.3" - isarray "~1.0.0" - process-nextick-args "~2.0.0" - safe-buffer "~5.1.1" - string_decoder "~1.1.1" - util-deprecate "~1.0.1" + "@types/normalize-package-data" "^2.4.0" + normalize-package-data "^2.5.0" + parse-json "^5.0.0" + type-fest "^0.6.0" -readable-stream@~1.0.17: +"readable-stream@>=1.0.33-1 <1.1.0-0", readable-stream@~1.0.17: version "1.0.34" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.0.34.tgz#125820e34bc842d2f2aaafafe4c2916ee32c157c" integrity sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw= @@ -3521,12 +3870,27 @@ readable-stream@~1.0.17: isarray "0.0.1" string_decoder "~0.10.x" -realpath-native@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/realpath-native/-/realpath-native-1.1.0.tgz#2003294fea23fb0672f2476ebe22fcf498a2d65c" - integrity sha512-wlgPA6cCIIg9gKz0fgAPjnzh4yR/LnXovwuo9hvyGvx3h8nX4+/iLZplfUWasXpqD8BdnGnP5njOFjkUwPzvjA== +readable-stream@^2.0.1, readable-stream@^2.3.5: + version "2.3.7" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.7.tgz#1eca1cf711aef814c04f62252a36a62f6cb23b57" + integrity sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw== + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.3" + isarray "~1.0.0" + process-nextick-args "~2.0.0" + safe-buffer "~5.1.1" + string_decoder "~1.1.1" + util-deprecate "~1.0.1" + +readable-stream@^3.0.0, readable-stream@^3.4.0: + version "3.6.0" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz#337bbda3adc0706bd3e024426a286d4b4b2c9198" + integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA== dependencies: - util.promisify "^1.0.0" + inherits "^2.0.3" + string_decoder "^1.1.1" + util-deprecate "^1.0.1" regex-not@^1.0.0, regex-not@^1.0.2: version "1.0.2" @@ -3546,31 +3910,31 @@ repeat-element@^1.1.2: resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.3.tgz#782e0d825c0c5a3bb39731f84efee6b742e6b1ce" integrity sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g== -repeat-string@^1.6.1: +repeat-string@^1.5.2, repeat-string@^1.5.4, repeat-string@^1.6.1: version "1.6.1" resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= -request-promise-core@1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/request-promise-core/-/request-promise-core-1.1.2.tgz#339f6aababcafdb31c799ff158700336301d3346" - integrity sha512-UHYyq1MO8GsefGEt7EprS8UrXsm1TxEvFUX1IMTuSLU2Rh7fTIdFtl8xD7JiEYiWU2dl+NYAjCTksTehQUxPag== +request-promise-core@1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/request-promise-core/-/request-promise-core-1.1.4.tgz#3eedd4223208d419867b78ce815167d10593a22f" + integrity sha512-TTbAfBBRdWD7aNNOoVOBH4pN/KigV6LyapYNNlAPA8JwbovRti1E88m3sYAwsLi5ryhPKsE9APwnjFTgdUjTpw== dependencies: - lodash "^4.17.11" + lodash "^4.17.19" -request-promise-native@^1.0.5: - version "1.0.7" - resolved "https://registry.yarnpkg.com/request-promise-native/-/request-promise-native-1.0.7.tgz#a49868a624bdea5069f1251d0a836e0d89aa2c59" - integrity sha512-rIMnbBdgNViL37nZ1b3L/VfPOpSi0TqVDQPAvO6U14lMzOLrt5nilxCQqtDKhZeDiW0/hkCXGoQjhgJd/tCh6w== +request-promise-native@^1.0.8: + version "1.0.9" + resolved "https://registry.yarnpkg.com/request-promise-native/-/request-promise-native-1.0.9.tgz#e407120526a5efdc9a39b28a5679bf47b9d9dc28" + integrity sha512-wcW+sIUiWnKgNY0dqCpOZkUbF/I+YPi+f09JZIDa39Ec+q82CpSYniDp+ISgTTbKmnpJWASeJBPZmoxH84wt3g== dependencies: - request-promise-core "1.1.2" + request-promise-core "1.1.4" stealthy-require "^1.1.1" tough-cookie "^2.3.3" -request@^2.87.0: - version "2.88.0" - resolved "https://registry.yarnpkg.com/request/-/request-2.88.0.tgz#9c2fca4f7d35b592efe57c7f0a55e81052124fef" - integrity sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg== +request@^2.88.2: + version "2.88.2" + resolved "https://registry.yarnpkg.com/request/-/request-2.88.2.tgz#d73c918731cb5a87da047e207234146f664d12b3" + integrity sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw== dependencies: aws-sign2 "~0.7.0" aws4 "^1.8.0" @@ -3579,7 +3943,7 @@ request@^2.87.0: extend "~3.0.2" forever-agent "~0.6.1" form-data "~2.3.2" - har-validator "~5.1.0" + har-validator "~5.1.3" http-signature "~1.2.0" is-typedarray "~1.0.0" isstream "~0.1.2" @@ -3589,7 +3953,7 @@ request@^2.87.0: performance-now "^2.1.0" qs "~6.5.2" safe-buffer "^5.1.2" - tough-cookie "~2.4.3" + tough-cookie "~2.5.0" tunnel-agent "^0.6.0" uuid "^3.3.2" @@ -3598,11 +3962,6 @@ require-directory@^2.1.1: resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= -require-main-filename@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz#97f717b69d48784f5f526a6c5aa8ffdda055a4d1" - integrity sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE= - require-main-filename@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-2.0.0.tgz#d0b329ecc7cc0f61649f62215be69af54aa8989b" @@ -3630,12 +3989,12 @@ requirejs@^2.3.5: resolved "https://registry.yarnpkg.com/requirejs/-/requirejs-2.3.6.tgz#e5093d9601c2829251258c0b9445d4d19fa9e7c9" integrity sha512-ipEzlWQe6RK3jkzikgCupiTbTvm4S0/CAU5GlgptkN5SO6F3u0UD0K18wy6ErDqiCyP4J4YYe1HuAShvsxePLg== -resolve-cwd@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-2.0.0.tgz#00a9f7387556e27038eae232caa372a6a59b665a" - integrity sha1-AKn3OHVW4nA46uIyyqNypqWbZlo= +resolve-cwd@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-3.0.0.tgz#0f0075f1bb2544766cf73ba6a6e2adfebcb13f2d" + integrity sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg== dependencies: - resolve-from "^3.0.0" + resolve-from "^5.0.0" resolve-dependency-path@^2.0.0: version "2.0.0" @@ -3647,34 +4006,29 @@ resolve-from@^2.0.0: resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-2.0.0.tgz#9480ab20e94ffa1d9e80a804c7ea147611966b57" integrity sha1-lICrIOlP+h2egKgEx+oUdhGWa1c= -resolve-from@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-3.0.0.tgz#b22c7af7d9d6881bc8b6e653335eebcb0a188748" - integrity sha1-six699nWiBvItuZTM17rywoYh0g= +resolve-from@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69" + integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw== resolve-url@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a" integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo= -resolve@1.1.7: - version "1.1.7" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" - integrity sha1-IDEU2CrSxe2ejgQRs5ModeiJ6Xs= - -resolve@1.x, resolve@^1.10.0, resolve@^1.11.1, resolve@^1.3.2: - version "1.11.1" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.11.1.tgz#ea10d8110376982fef578df8fc30b9ac30a07a3e" - integrity sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw== +resolve@^1.10.0, resolve@^1.11.1, resolve@^1.17.0, resolve@^1.3.2: + version "1.17.0" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" + integrity sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w== dependencies: path-parse "^1.0.6" -restore-cursor@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-2.0.0.tgz#9f7ee287f82fd326d4fd162923d62129eee0dfaf" - integrity sha1-n37ih/gv0ybU/RYpI9YhKe7g368= +restore-cursor@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-3.1.0.tgz#39f67c54b3a7a58cea5236d95cf0034239631f7e" + integrity sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA== dependencies: - onetime "^2.0.0" + onetime "^5.1.0" signal-exit "^3.0.2" ret@~0.1.10: @@ -3682,10 +4036,15 @@ ret@~0.1.10: resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc" integrity sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg== -rimraf@^2.5.4, rimraf@^2.6.1, rimraf@^2.6.3: - version "2.6.3" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab" - integrity sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA== +right-now@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/right-now/-/right-now-1.0.0.tgz#6e89609deebd7dcdaf8daecc9aea39cf585a0918" + integrity sha1-bolgne69fc2vja7Mmuo5z1haCRg= + +rimraf@^3.0.0: + version "3.0.2" + resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a" + integrity sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA== dependencies: glob "^7.1.3" @@ -3694,10 +4053,10 @@ rsvp@^4.8.4: resolved "https://registry.yarnpkg.com/rsvp/-/rsvp-4.8.5.tgz#c8f155311d167f68f21e168df71ec5b083113734" integrity sha512-nfMOlASu9OnRJo1mbEk2cz0D56a1MBNrJ7orjRZQG10XDyuvwksKbuXNp6qa+kbn839HwjwhBzhFmdsaEAfauA== -safe-buffer@^5.0.1, safe-buffer@^5.1.2: - version "5.2.0" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.0.tgz#b74daec49b1148f88c64b68d49b1e815c1f2f519" - integrity sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg== +safe-buffer@^5.0.1, safe-buffer@^5.1.1, safe-buffer@^5.1.2, safe-buffer@~5.2.0: + version "5.2.1" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" + integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== safe-buffer@~5.1.0, safe-buffer@~5.1.1: version "5.1.2" @@ -3745,27 +4104,29 @@ sass-lookup@^3.0.0: dependencies: commander "^2.16.0" -sax@^1.2.4: - version "1.2.4" - resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" - integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw== +saxes@^5.0.0: + version "5.0.1" + resolved "https://registry.yarnpkg.com/saxes/-/saxes-5.0.1.tgz#eebab953fa3b7608dbe94e5dadb15c888fa6696d" + integrity sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw== + dependencies: + xmlchars "^2.2.0" -"semver@2 || 3 || 4 || 5", semver@^5.1.0, semver@^5.3.0, semver@^5.4.1, semver@^5.5, semver@^5.5.0, semver@^5.6.0: - version "5.7.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.0.tgz#790a7cf6fea5459bac96110b29b60412dc8ff96b" - integrity sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA== +"semver@2 || 3 || 4 || 5", semver@^5.1.0, semver@^5.4.1, semver@^5.5.0, semver@^5.6.0: + version "5.7.1" + resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" + integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== -semver@5.5.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.5.0.tgz#dc4bbc7a6ca9d916dee5d43516f0092b58f7b8ab" - integrity sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA== +semver@7.x, semver@^7.3.2: + version "7.3.2" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.2.tgz#604962b052b81ed0786aae84389ffba70ffd3938" + integrity sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ== -semver@^6.0.0: - version "6.2.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-6.2.0.tgz#4d813d9590aaf8a9192693d6c85b9344de5901db" - integrity sha512-jdFC1VdUGT/2Scgbimf7FSx9iJLXoqfglSF+gJeuNWVpiE37OIbc1jywR/GJyFdz3mnkz2/id0L0J/cr0izR5A== +semver@^6.0.0, semver@^6.3.0: + version "6.3.0" + resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d" + integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== -set-blocking@^2.0.0, set-blocking@~2.0.0: +set-blocking@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc= @@ -3787,30 +4148,42 @@ shebang-command@^1.2.0: dependencies: shebang-regex "^1.0.0" +shebang-command@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" + integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== + dependencies: + shebang-regex "^3.0.0" + shebang-regex@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3" integrity sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM= +shebang-regex@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" + integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== + shellwords@^0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/shellwords/-/shellwords-0.1.1.tgz#d6b9181c1a48d397324c84871efbcfc73fc0654b" integrity sha512-vFwSUfQvqybiICwZY5+DAWIPLKsWO31Q91JSKl3UYv+K5c2QRPzn0qzec6QPu1Qc9eHYItiP3NdJqNVqetYAww== signal-exit@^3.0.0, signal-exit@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d" - integrity sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0= + version "3.0.3" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.3.tgz#a1410c2edd8f077b08b4e253c8eacfcaf057461c" + integrity sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA== -sisteransi@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/sisteransi/-/sisteransi-1.0.2.tgz#ec57d64b6f25c4f26c0e2c7dd23f2d7f12f7e418" - integrity sha512-ZcYcZcT69nSLAR2oLN2JwNmLkJEKGooFMCdvOkFrToUt/WfcRWqhIg4P4KwY4dmLbuyXIx4o4YmPsvMRJYJd/w== +sisteransi@^1.0.4: + version "1.0.5" + resolved "https://registry.yarnpkg.com/sisteransi/-/sisteransi-1.0.5.tgz#134d681297756437cc05ca01370d3a7a571075ed" + integrity sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg== -slash@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/slash/-/slash-2.0.0.tgz#de552851a1759df3a8f206535442f5ec4ddeab44" - integrity sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A== +slash@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" + integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== snapdragon-node@^2.0.1: version "2.1.1" @@ -3842,21 +4215,29 @@ snapdragon@^0.8.1: source-map-resolve "^0.5.0" use "^3.1.0" +sonic-boom@^0.7.5: + version "0.7.7" + resolved "https://registry.yarnpkg.com/sonic-boom/-/sonic-boom-0.7.7.tgz#d921de887428208bfa07b0ae32c278de043f350a" + integrity sha512-Ei5YOo5J64GKClHIL/5evJPgASXFVpfVYbJV9PILZQytTK6/LCwHvsZJW2Ig4p9FMC2OrBrMnXKgRN/OEoAWfg== + dependencies: + atomic-sleep "^1.0.0" + flatstr "^1.0.12" + source-map-resolve@^0.5.0: - version "0.5.2" - resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.2.tgz#72e2cc34095543e43b2c62b2c4c10d4a9054f259" - integrity sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA== + version "0.5.3" + resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.3.tgz#190866bece7553e1f8f267a2ee82c606b5509a1a" + integrity sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw== dependencies: - atob "^2.1.1" + atob "^2.1.2" decode-uri-component "^0.2.0" resolve-url "^0.2.1" source-map-url "^0.4.0" urix "^0.1.0" -source-map-support@^0.5.6: - version "0.5.12" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.12.tgz#b4f3b10d51857a5af0138d3ce8003b201613d599" - integrity sha512-4h2Pbvyy15EE02G+JOZpUCmqWJuqrs+sEkzewTm++BPi7Hvn/HwcqLAcNxYAyI0x13CpPPn+kMjl+hplXMHITQ== +source-map-support@^0.5.17, source-map-support@^0.5.6: + version "0.5.19" + resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.19.tgz#a98b62f86dcaf4f67399648c085291ab9e8fed61" + integrity sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw== dependencies: buffer-from "^1.0.0" source-map "^0.6.0" @@ -3876,6 +4257,11 @@ source-map@^0.6.0, source-map@^0.6.1, source-map@~0.6.1: resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== +source-map@^0.7.3: + version "0.7.3" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.7.3.tgz#5302f8169031735226544092e64981f751750383" + integrity sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ== + sparse-bitfield@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz#ff4ae6e68656056ba4b3e792ab3334d38273ca11" @@ -3884,30 +4270,30 @@ sparse-bitfield@^3.0.3: memory-pager "^1.0.2" spdx-correct@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.0.tgz#fb83e504445268f154b074e218c87c003cd31df4" - integrity sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q== + version "3.1.1" + resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.1.tgz#dece81ac9c1e6713e5f7d1b6f17d468fa53d89a9" + integrity sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w== dependencies: spdx-expression-parse "^3.0.0" spdx-license-ids "^3.0.0" spdx-exceptions@^2.1.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz#2ea450aee74f2a89bfb94519c07fcd6f41322977" - integrity sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA== + version "2.3.0" + resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz#3f28ce1a77a00372683eade4a433183527a2163d" + integrity sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A== spdx-expression-parse@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz#99e119b7a5da00e05491c9fa338b7904823b41d0" - integrity sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg== + version "3.0.1" + resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz#cf70f50482eefdc98e3ce0a6833e4a53ceeba679" + integrity sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q== dependencies: spdx-exceptions "^2.1.0" spdx-license-ids "^3.0.0" spdx-license-ids@^3.0.0: - version "3.0.4" - resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.4.tgz#75ecd1a88de8c184ef015eafb51b5b48bfd11bb1" - integrity sha512-7j8LYJLeY/Yb6ACbQ7F76qy5jHkp0U6jgBfJsk97bwWlVUnUWsAgpyaCvo17h0/RQGnQ036tVDomiwoI4pDkQA== + version "3.0.5" + resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.5.tgz#3694b5804567a458d3c8045842a6358632f62654" + integrity sha512-J+FWzZoynJEXGphVIS+XEh3kFSjZX/1i9gFBaWQcB+/tmpe2qUsSBABpcxqxnAxFdiUFEgAX1bjYGQvIZmoz9Q== split-string@^3.0.1, split-string@^3.0.2: version "3.1.0" @@ -3916,6 +4302,20 @@ split-string@^3.0.1, split-string@^3.0.2: dependencies: extend-shallow "^3.0.0" +split2@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/split2/-/split2-0.2.1.tgz#02ddac9adc03ec0bb78c1282ec079ca6e85ae900" + integrity sha1-At2smtwD7Au3jBKC7Aecpuha6QA= + dependencies: + through2 "~0.6.1" + +split2@^3.1.1: + version "3.2.2" + resolved "https://registry.yarnpkg.com/split2/-/split2-3.2.2.tgz#bf2cf2a37d838312c249c89206fd7a17dd12365f" + integrity sha512-9NThjpgZnifTkJpzTZ7Eue85S49QwpNhZTq6GRJwObb6jnLFNGB7Qm73V5HewTROPyxD0C29xqmaI68bQtV+hg== + dependencies: + readable-stream "^3.0.0" + split@^0.3.0: version "0.3.3" resolved "https://registry.yarnpkg.com/split/-/split-0.3.3.tgz#cd0eea5e63a211dfff7eb0f091c4133e2d0dd28f" @@ -3923,6 +4323,11 @@ split@^0.3.0: dependencies: through "2" +sprintf-js@~1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" + integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= + sshpk@^1.7.0: version "1.16.1" resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.16.1.tgz#fb661c0bef29b39db40769ee39fa70093d6f6877" @@ -3938,10 +4343,12 @@ sshpk@^1.7.0: safer-buffer "^2.0.2" tweetnacl "~0.14.0" -stack-utils@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/stack-utils/-/stack-utils-1.0.2.tgz#33eba3897788558bebfc2db059dc158ec36cebb8" - integrity sha512-MTX+MeG5U994cazkjd/9KNAapsHnibjMLnfXodlkXw76JEea0UiNzrqidzo1emMwk7w5Qhc9jd4Bn9TBb1MFwA== +stack-utils@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/stack-utils/-/stack-utils-2.0.2.tgz#5cf48b4557becb4638d0bc4f21d23f5d19586593" + integrity sha512-0H7QK2ECz3fyZMzQ8rH0j2ykpfbnd20BFtfg/SqVC2+sCTtcw0aDTGB7dk+de4U4uUeuz6nOtJcrkFFLG1B0Rg== + dependencies: + escape-string-regexp "^2.0.0" static-extend@^0.1.1: version "0.1.2" @@ -3951,6 +4358,13 @@ static-extend@^0.1.1: define-property "^0.2.5" object-copy "^0.1.0" +stdout-stream@^1.4.0: + version "1.4.1" + resolved "https://registry.yarnpkg.com/stdout-stream/-/stdout-stream-1.4.1.tgz#5ac174cdd5cd726104aa0c0b2bd83815d8d535de" + integrity sha512-j4emi03KXqJWcIeF8eIXkjMFN1Cmb8gUlDYGeBALLPo5qdyTfA9bOtl8m33lRoC+vFMkP3gl0WsDr6+gzxbbTA== + dependencies: + readable-stream "^2.0.1" + stealthy-require@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/stealthy-require/-/stealthy-require-1.1.1.tgz#35b09875b4ff49f26a777e509b3090a3226bf24b" @@ -3964,30 +4378,13 @@ stream-combiner@^0.2.0: duplexer "~0.1.1" through "~2.3.4" -string-length@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/string-length/-/string-length-2.0.0.tgz#d40dbb686a3ace960c1cffca562bf2c45f8363ed" - integrity sha1-1A27aGo6zpYMHP/KVivyxF+DY+0= - dependencies: - astral-regex "^1.0.0" - strip-ansi "^4.0.0" - -string-width@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3" - integrity sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M= - dependencies: - code-point-at "^1.0.0" - is-fullwidth-code-point "^1.0.0" - strip-ansi "^3.0.0" - -"string-width@^1.0.2 || 2", string-width@^2.0.0, string-width@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e" - integrity sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw== +string-length@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/string-length/-/string-length-4.0.1.tgz#4a973bf31ef77c4edbceadd6af2611996985f8a1" + integrity sha512-PKyXUd0LK0ePjSOnWn34V2uD6acUWev9uy0Ft05k0E8xRW+SKcA0F7eMr7h5xlzfn+4O3N+55rduYyet3Jk+jw== dependencies: - is-fullwidth-code-point "^2.0.0" - strip-ansi "^4.0.0" + char-regex "^1.0.2" + strip-ansi "^6.0.0" string-width@^3.0.0, string-width@^3.1.0: version "3.1.0" @@ -3998,6 +4395,22 @@ string-width@^3.0.0, string-width@^3.1.0: is-fullwidth-code-point "^2.0.0" strip-ansi "^5.1.0" +string-width@^4.1.0, string-width@^4.2.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.0.tgz#952182c46cc7b2c313d1596e623992bd163b72b5" + integrity sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.0" + +string_decoder@^1.1.1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" + integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== + dependencies: + safe-buffer "~5.2.0" + string_decoder@~0.10.x: version "0.10.31" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.10.31.tgz#62e203bc41766c6c28c9fc84301dab1c5310fa94" @@ -4026,20 +4439,6 @@ strip-ansi@^0.3.0: dependencies: ansi-regex "^0.2.1" -strip-ansi@^3.0.0, strip-ansi@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" - integrity sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8= - dependencies: - ansi-regex "^2.0.0" - -strip-ansi@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" - integrity sha1-qEeQIusaw2iocTibY1JixQXuNo8= - dependencies: - ansi-regex "^3.0.0" - strip-ansi@^5.0.0, strip-ansi@^5.1.0, strip-ansi@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-5.2.0.tgz#8c9a536feb6afc962bdfa5b104a5091c1ad9c0ae" @@ -4047,16 +4446,33 @@ strip-ansi@^5.0.0, strip-ansi@^5.1.0, strip-ansi@^5.2.0: dependencies: ansi-regex "^4.1.0" -strip-bom@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" - integrity sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM= +strip-ansi@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.0.tgz#0b1571dd7669ccd4f3e06e14ef1eed26225ae532" + integrity sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w== + dependencies: + ansi-regex "^5.0.0" + +strip-bom@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-4.0.0.tgz#9c3505c1db45bcedca3d9cf7a16f5c5aa3901878" + integrity sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w== strip-eof@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/strip-eof/-/strip-eof-1.0.0.tgz#bb43ff5598a6eb05d89b59fcd129c983313606bf" integrity sha1-u0P/VZim6wXYm1n80SnJgzE2Br8= +strip-final-newline@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad" + integrity sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA== + +strip-json-comments@^3.0.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" + integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== + strip-json-comments@~2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" @@ -4089,7 +4505,22 @@ supports-color@^6.1.0: dependencies: has-flag "^3.0.0" -symbol-tree@^3.2.2: +supports-color@^7.0.0, supports-color@^7.1.0: + version "7.2.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da" + integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw== + dependencies: + has-flag "^4.0.0" + +supports-hyperlinks@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/supports-hyperlinks/-/supports-hyperlinks-2.1.0.tgz#f663df252af5f37c5d49bbd7eeefa9e0b9e59e47" + integrity sha512-zoE5/e+dnEijk6ASB6/qrK+oYdm2do1hjoLWrqUC/8WEIW1gbxFcKuBof7sW8ArN6e+AYvsE8HBGiVRWL/F5CA== + dependencies: + has-flag "^4.0.0" + supports-color "^7.0.0" + +symbol-tree@^3.2.4: version "3.2.4" resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2" integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw== @@ -4099,38 +4530,32 @@ tapable@^1.0.0: resolved "https://registry.yarnpkg.com/tapable/-/tapable-1.1.3.tgz#a1fccc06b58db61fd7a45da2da44f5f3a3e67ba2" integrity sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA== -tar@^4: - version "4.4.10" - resolved "https://registry.yarnpkg.com/tar/-/tar-4.4.10.tgz#946b2810b9a5e0b26140cf78bea6b0b0d689eba1" - integrity sha512-g2SVs5QIxvo6OLp0GudTqEf05maawKUxXru104iaayWA09551tFCTI8f1Asb4lPfkBr91k07iL4c11XO3/b0tA== - dependencies: - chownr "^1.1.1" - fs-minipass "^1.2.5" - minipass "^2.3.5" - minizlib "^1.2.1" - mkdirp "^0.5.0" - safe-buffer "^5.1.2" - yallist "^3.0.3" - temp@~0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/temp/-/temp-0.4.0.tgz#671ad63d57be0fe9d7294664b3fc400636678a60" integrity sha1-ZxrWPVe+D+nXKUZks/xABjZnimA= -test-exclude@^5.2.3: - version "5.2.3" - resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-5.2.3.tgz#c3d3e1e311eb7ee405e092dac10aefd09091eac0" - integrity sha512-M+oxtseCFO3EDtAaGH7iiej3CBkzXqFMbzqYAACdzKui4eZA+pq3tZEwChvOdNfa7xxy8BfbmgJSIr43cC/+2g== +terminal-link@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/terminal-link/-/terminal-link-2.1.1.tgz#14a64a27ab3c0df933ea546fba55f2d078edc994" + integrity sha512-un0FmiRUQNr5PJqy9kP7c40F5BOfpGlYTrxonDChEZB7pzZxRNp/bt+ymiy9/npwXya9KH99nJ/GXFIiUkYGFQ== dependencies: - glob "^7.1.3" + ansi-escapes "^4.2.1" + supports-hyperlinks "^2.0.0" + +test-exclude@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-6.0.0.tgz#04a8698661d805ea6fa293b6cb9e63ac044ef15e" + integrity sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w== + dependencies: + "@istanbuljs/schema" "^0.1.2" + glob "^7.1.4" minimatch "^3.0.4" - read-pkg-up "^4.0.0" - require-main-filename "^2.0.0" -throat@^4.0.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/throat/-/throat-4.1.0.tgz#89037cbc92c56ab18926e6ba4cbb200e15672a6a" - integrity sha1-iQN8vJLFarGJJua6TLsgDhVnKmo= +throat@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/throat/-/throat-5.0.0.tgz#c5199235803aad18754a667d659b5e72ce16764b" + integrity sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA== through2@^0.5.1: version "0.5.1" @@ -4140,23 +4565,35 @@ through2@^0.5.1: readable-stream "~1.0.17" xtend "~3.0.0" +through2@~0.6.1: + version "0.6.5" + resolved "https://registry.yarnpkg.com/through2/-/through2-0.6.5.tgz#41ab9c67b29d57209071410e1d7a7a968cd3ad48" + integrity sha1-QaucZ7KdVyCQcUEOHXp6lozTrUg= + dependencies: + readable-stream ">=1.0.33-1 <1.1.0-0" + xtend ">=4.0.0 <4.1.0-0" + through@2, through@~2.3.4: version "2.3.8" resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" integrity sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU= -tkt@1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/tkt/-/tkt-1.1.0.tgz#3e7646a131657c93345a507fd90ed0add7420968" - integrity sha512-b/M9hhEHVTxZ92YgB4q6aS06jUavvn/x08Kvg9h9ovnbL3tyPSr8e4Z+DyI0SQEbhHq74qjwlucEpem+eoopQg== +tkt@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/tkt/-/tkt-2.0.0.tgz#59fe8f553f4e8f5e1b6d629798dc904f00b4f725" + integrity sha512-ExJIsw7poRNmU+BGYBL1v7fX2WOpxy8Ugd196NlhRgyl5shwLjFDZBCLtW+vg0p7pOT5GtvSUEGjKyzO4CyRTg== dependencies: "@types/invariant" "^2.2.30" "@types/node" "^12.6.1" + "@types/pino" "^5.8.8" "@types/yargs" "^13.0.0" bistre "^1.0.1" bole "^3.0.2" bson-objectid "^1.3.0" + garnish "^5.2.0" invariant "^2.2.4" + pino "^5.13.0" + pino-pretty "^3.2.0" yargs "^13.2.4" tmpl@1.0.x: @@ -4184,6 +4621,13 @@ to-regex-range@^2.1.0: is-number "^3.0.0" repeat-string "^1.6.1" +to-regex-range@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" + integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== + dependencies: + is-number "^7.0.0" + to-regex@^3.0.1, to-regex@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/to-regex/-/to-regex-3.0.2.tgz#13cfdd9b336552f30b51f33a8ae1b42a7a7599ce" @@ -4194,7 +4638,7 @@ to-regex@^3.0.1, to-regex@^3.0.2: regex-not "^1.0.2" safe-regex "^1.1.0" -tough-cookie@^2.3.3, tough-cookie@^2.3.4: +tough-cookie@^2.3.3, tough-cookie@~2.5.0: version "2.5.0" resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.5.0.tgz#cd9fb2a0aa1d5a12b473bd9fb96fa3dcff65ade2" integrity sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g== @@ -4202,56 +4646,66 @@ tough-cookie@^2.3.3, tough-cookie@^2.3.4: psl "^1.1.28" punycode "^2.1.1" -tough-cookie@~2.4.3: - version "2.4.3" - resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.4.3.tgz#53f36da3f47783b0925afa06ff9f3b165280f781" - integrity sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ== +tough-cookie@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-3.0.1.tgz#9df4f57e739c26930a018184887f4adb7dca73b2" + integrity sha512-yQyJ0u4pZsv9D4clxO69OEjLWYw+jbgspjTue4lTQZLfV0c5l1VmK2y1JK8E9ahdpltPOaAThPcp5nKPUgSnsg== dependencies: - psl "^1.1.24" - punycode "^1.4.1" + ip-regex "^2.1.0" + psl "^1.1.28" + punycode "^2.1.1" -tr46@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/tr46/-/tr46-1.0.1.tgz#a8b13fd6bfd2489519674ccde55ba3693b706d09" - integrity sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk= +tr46@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/tr46/-/tr46-2.0.2.tgz#03273586def1595ae08fedb38d7733cee91d2479" + integrity sha512-3n1qG+/5kg+jrbTzwAykB5yRYtQCTqOGKq5U5PE3b0a1/mzo6snDhjGS0zJVJunO0NrT3Dg1MLy5TjWP/UJppg== dependencies: - punycode "^2.1.0" + punycode "^2.1.1" traverse-chain@~0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/traverse-chain/-/traverse-chain-0.1.0.tgz#61dbc2d53b69ff6091a12a168fd7d433107e40f1" integrity sha1-YdvC1Ttp/2CRoSoWj9fUMxB+QPE= -trim-right@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/trim-right/-/trim-right-1.0.1.tgz#cb2e1203067e0c8de1f614094b9fe45704ea6003" - integrity sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM= - -ts-jest@^24.0.2: - version "24.0.2" - resolved "https://registry.yarnpkg.com/ts-jest/-/ts-jest-24.0.2.tgz#8dde6cece97c31c03e80e474c749753ffd27194d" - integrity sha512-h6ZCZiA1EQgjczxq+uGLXQlNgeg02WWJBbeT8j6nyIBRQdglqbvzDoHahTEIiS6Eor6x8mK6PfZ7brQ9Q6tzHw== +ts-jest@^26.3.0: + version "26.3.0" + resolved "https://registry.yarnpkg.com/ts-jest/-/ts-jest-26.3.0.tgz#6b2845045347dce394f069bb59358253bc1338a9" + integrity sha512-Jq2uKfx6bPd9+JDpZNMBJMdMQUC3sJ08acISj8NXlVgR2d5OqslEHOR2KHMgwymu8h50+lKIm0m0xj/ioYdW2Q== dependencies: + "@types/jest" "26.x" bs-logger "0.x" buffer-from "1.x" fast-json-stable-stringify "2.x" + jest-util "26.x" json5 "2.x" + lodash.memoize "4.x" make-error "1.x" - mkdirp "0.x" - resolve "1.x" - semver "^5.5" - yargs-parser "10.x" + mkdirp "1.x" + semver "7.x" + yargs-parser "18.x" -ts-node@^8.3.0: - version "8.3.0" - resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-8.3.0.tgz#e4059618411371924a1fb5f3b125915f324efb57" - integrity sha512-dyNS/RqyVTDcmNM4NIBAeDMpsAdaQ+ojdf0GOLqE6nwJOgzEkdRNzJywhDfwnuvB10oa6NLVG1rUJQCpRN7qoQ== +ts-node@^9.0.0: + version "9.0.0" + resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-9.0.0.tgz#e7699d2a110cc8c0d3b831715e417688683460b3" + integrity sha512-/TqB4SnererCDR/vb4S/QvSZvzQMJN8daAslg7MeaiHvD8rDZsSfXmNeNumyZZzMned72Xoq/isQljYSt8Ynfg== dependencies: arg "^4.1.0" diff "^4.0.1" make-error "^1.1.1" - source-map-support "^0.5.6" - yn "^3.0.0" + source-map-support "^0.5.17" + yn "3.1.1" + +tslib@^1.8.1: + version "1.13.0" + resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.13.0.tgz#c881e13cc7015894ed914862d276436fa9a47043" + integrity sha512-i/6DQjL8Xf3be4K/E6Wgpekn5Qasl1usyw++dAA35Ue5orEn65VIxOA+YvNNl9HV3qv70T7CNwjODHZrLwvd1Q== + +tsutils@^3.17.1: + version "3.17.1" + resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.17.1.tgz#ed719917f11ca0dee586272b2ac49e015a2dd759" + integrity sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g== + dependencies: + tslib "^1.8.1" tunnel-agent@^0.6.0: version "0.6.0" @@ -4260,6 +4714,11 @@ tunnel-agent@^0.6.0: dependencies: safe-buffer "^5.0.1" +tunnel@0.0.6: + version "0.0.6" + resolved "https://registry.yarnpkg.com/tunnel/-/tunnel-0.0.6.tgz#72f1314b34a5b192db012324df2cc587ca47f92c" + integrity sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg== + tweetnacl@^0.14.3, tweetnacl@~0.14.0: version "0.14.5" resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64" @@ -4272,23 +4731,42 @@ type-check@~0.3.2: dependencies: prelude-ls "~1.1.2" -typescript@^3.0.3, typescript@^3.4.5: - version "3.5.3" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.5.3.tgz#c830f657f93f1ea846819e929092f5fe5983e977" - integrity sha512-ACzBtm/PhXBDId6a6sDJfroT2pOWt/oOnk4/dElG5G33ZL776N3Y6/6bKZJBFpd+b05F3Ct9qDjMeJmRWtE2/g== +type-detect@4.0.8: + version "4.0.8" + resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" + integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== -typescript@^3.5.2: - version "3.5.2" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.5.2.tgz#a09e1dc69bc9551cadf17dba10ee42cf55e5d56c" - integrity sha512-7KxJovlYhTX5RaRbUdkAXN1KUZ8PwWlTzQdHV6xNqvuFOs7+WBo10TQUqT19Q/Jz2hk5v9TQDIhyLhhJY4p5AA== +type-fest@^0.11.0: + version "0.11.0" + resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.11.0.tgz#97abf0872310fed88a5c466b25681576145e33f1" + integrity sha512-OdjXJxnCN1AvyLSzeKIgXTXxV+99ZuXl3Hpo9XpJAv9MBcHrrJOQ5kV7ypXOuQie+AmWG25hLbiKdwYTifzcfQ== -uglify-js@^3.1.4: - version "3.6.0" - resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.6.0.tgz#704681345c53a8b2079fb6cec294b05ead242ff5" - integrity sha512-W+jrUHJr3DXKhrsS7NUVxn3zqMOFn0hL/Ei6v0anCIMoKC93TjcflTagwIHLW7SfMFfiQuktQyFVCFHGUE0+yg== +type-fest@^0.6.0: + version "0.6.0" + resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.6.0.tgz#8d2a2370d3df886eb5c90ada1c5bf6188acf838b" + integrity sha512-q+MB8nYR1KDLrgr4G5yemftpMC7/QLqVndBmEEdqzmNj5dcFOO4Oo8qlwZE3ULT3+Zim1F8Kq4cBnikNhlCMlg== + +type-fest@^0.8.1: + version "0.8.1" + resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d" + integrity sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA== + +typedarray-to-buffer@^3.1.5: + version "3.1.5" + resolved "https://registry.yarnpkg.com/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz#a97ee7a9ff42691b9f783ff1bc5112fe3fca9080" + integrity sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q== dependencies: - commander "~2.20.0" - source-map "~0.6.1" + is-typedarray "^1.0.0" + +typescript@^3.0.3, typescript@^3.7.5, typescript@^3.8.3, typescript@^3.9.5: + version "3.9.7" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.9.7.tgz#98d600a5ebdc38f40cb277522f12dc800e9e25fa" + integrity sha512-BLbiRkiBzAwsjut4x/dsibSTB6yWpwT5qWmC2OfuCg3GgVQCSgMs4vEctYPhsaGtd0AeuuHMkjZ2h2WG8MSzRw== + +typescript@^4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.0.2.tgz#7ea7c88777c723c681e33bf7988be5d008d05ac2" + integrity sha512-e4ERvRV2wb+rRZ/IQeb3jm2VxBsirQLpQhdxplZ2MEzGvDkkMmPglecnNDfSUBivMjP93vRbngYYDQqQ/78bcQ== union-value@^1.0.0: version "1.0.1" @@ -4305,12 +4783,10 @@ uniq@^1.0.1: resolved "https://registry.yarnpkg.com/uniq/-/uniq-1.0.1.tgz#b31c5ae8254844a3a8281541ce2b04b865a734ff" integrity sha1-sxxa6CVIRKOoKBVBzisEuGWnNP8= -universal-user-agent@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/universal-user-agent/-/universal-user-agent-3.0.0.tgz#4cc88d68097bffd7ac42e3b7c903e7481424b4b9" - integrity sha512-T3siHThqoj5X0benA5H0qcDnrKGXzU8TKoX15x/tQHw1hQBvIEBHjxQ2klizYsqBOO/Q+WuxoQUihadeeqDnoA== - dependencies: - os-name "^3.0.0" +universal-user-agent@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/universal-user-agent/-/universal-user-agent-6.0.0.tgz#3381f8503b251c0d9cd21bc1de939ec9df5480ee" + integrity sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w== unset-value@^1.0.0: version "1.0.0" @@ -4321,9 +4797,9 @@ unset-value@^1.0.0: isobject "^3.0.0" uri-js@^4.2.2: - version "4.2.2" - resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.2.2.tgz#94c540e1ff772956e2299507c010aea6c8838eb0" - integrity sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ== + version "4.4.0" + resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.0.tgz#aa714261de793e8a82347a7bcc9ce74e86f28602" + integrity sha512-B0yRTzYdUCCn9n+F4+Gh4yIDtMQcaJsmYBDsTSG8g/OejKBodLQ2IHfN3bM7jUsRXndopT7OIXWdYqc1fjmV6g== dependencies: punycode "^2.1.0" @@ -4332,33 +4808,39 @@ urix@^0.1.0: resolved "https://registry.yarnpkg.com/urix/-/urix-0.1.0.tgz#da937f7a62e21fec1fd18d49b35c2935067a6c72" integrity sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI= -url-template@^2.0.8: - version "2.0.8" - resolved "https://registry.yarnpkg.com/url-template/-/url-template-2.0.8.tgz#fc565a3cccbff7730c775f5641f9555791439f21" - integrity sha1-/FZaPMy/93MMd19WQflVV5FDnyE= +url-trim@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/url-trim/-/url-trim-1.0.0.tgz#40057e2f164b88e5daca7269da47e6d1dd837adc" + integrity sha1-QAV+LxZLiOXaynJp2kfm0d2Detw= use@^3.1.0: version "3.1.1" resolved "https://registry.yarnpkg.com/use/-/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f" integrity sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ== -util-deprecate@~1.0.1: +util-deprecate@^1.0.1, util-deprecate@~1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= -util.promisify@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/util.promisify/-/util.promisify-1.0.0.tgz#440f7165a459c9a16dc145eb8e72f35687097030" - integrity sha512-i+6qA2MPhvoKLuxnJNpXAGhg7HphQOSUq2LKMZD0m15EiskXUkMvKdF4Uui0WYeCUGea+o2cw/ZuwehtfsrNkA== - dependencies: - define-properties "^1.1.2" - object.getownpropertydescriptors "^2.0.3" - uuid@^3.3.2: - version "3.3.2" - resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.3.2.tgz#1b4af4955eb3077c501c23872fc6513811587131" - integrity sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA== + version "3.4.0" + resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee" + integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A== + +uuid@^8.3.0: + version "8.3.0" + resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.0.tgz#ab738085ca22dc9a8c92725e459b1d507df5d6ea" + integrity sha512-fX6Z5o4m6XsXBdli9g7DtWgAx+osMsRRZFKma1mIUsLCz6vRvv+pz5VNbyu9UEDzpMWulZfvpgb/cmDXVulYFQ== + +v8-to-istanbul@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/v8-to-istanbul/-/v8-to-istanbul-5.0.1.tgz#0608f5b49a481458625edb058488607f25498ba5" + integrity sha512-mbDNjuDajqYe3TXFk5qxcQy8L1msXNE37WTlLoqqpBfRsimbNcrlhQlDPntmECEcUvdC+AQ8CyMMf6EUx1r74Q== + dependencies: + "@types/istanbul-lib-coverage" "^2.0.1" + convert-source-map "^1.6.0" + source-map "^0.7.3" validate-npm-package-license@^3.0.1: version "3.0.4" @@ -4377,17 +4859,24 @@ verror@1.10.0: core-util-is "1.0.2" extsprintf "^1.2.0" -w3c-hr-time@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/w3c-hr-time/-/w3c-hr-time-1.0.1.tgz#82ac2bff63d950ea9e3189a58a65625fedf19045" - integrity sha1-gqwr/2PZUOqeMYmlimViX+3xkEU= +w3c-hr-time@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz#0a89cdf5cc15822df9c360543676963e0cc308cd" + integrity sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ== + dependencies: + browser-process-hrtime "^1.0.0" + +w3c-xmlserializer@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/w3c-xmlserializer/-/w3c-xmlserializer-2.0.0.tgz#3e7104a05b75146cc60f564380b7f683acf1020a" + integrity sha512-4tzD0mF8iSiMiNs30BiLO3EpfGLZUT2MSX/G+o7ZywDzliWQ3OPtTZ0PTC3B3ca1UAf4cJMHB+2Bf56EriJuRA== dependencies: - browser-process-hrtime "^0.1.2" + xml-name-validator "^3.0.0" -walkdir@^0.0.12: - version "0.0.12" - resolved "https://registry.yarnpkg.com/walkdir/-/walkdir-0.0.12.tgz#2f24f1ade64aab1e458591d4442c8868356e9281" - integrity sha512-HFhaD4mMWPzFSqhpyDG48KDdrjfn409YQuVW7ckZYhW4sE87mYtWifdB/+73RA7+p4s4K18n5Jfx1kHthE1gBw== +walkdir@^0.4.1: + version "0.4.1" + resolved "https://registry.yarnpkg.com/walkdir/-/walkdir-0.4.1.tgz#dc119f83f4421df52e3061e514228a2db20afa39" + integrity sha512-3eBwRyEln6E1MSzcxcVpQIhRG8Q1jLvEqRmCZqS3dsfXEDR/AhOF4d+jHg1qvDCpYaVRZjENPQyrVxAkQqxPgQ== walker@^1.0.7, walker@~1.0.5: version "1.0.7" @@ -4403,84 +4892,60 @@ wcwidth@^1.0.1: dependencies: defaults "^1.0.3" -webidl-conversions@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-4.0.2.tgz#a855980b1f0b6b359ba1d5d9fb39ae941faa63ad" - integrity sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg== +webidl-conversions@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-5.0.0.tgz#ae59c8a00b121543a2acc65c0434f57b0fc11aff" + integrity sha512-VlZwKPCkYKxQgeSbH5EyngOmRp7Ww7I9rQLERETtf5ofd9pGeswWiOtogpEO850jziPRarreGxn5QIiTqpb2wA== -whatwg-encoding@^1.0.1, whatwg-encoding@^1.0.3: +webidl-conversions@^6.1.0: + version "6.1.0" + resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-6.1.0.tgz#9111b4d7ea80acd40f5270d666621afa78b69514" + integrity sha512-qBIvFLGiBpLjfwmYAaHPXsn+ho5xZnGvyGvsarywGNc8VyQJUMHJ8OBKGGrPER0okBeMDaan4mNBlgBROxuI8w== + +whatwg-encoding@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz#5abacf777c32166a51d085d6b4f3e7d27113ddb0" integrity sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw== dependencies: iconv-lite "0.4.24" -whatwg-mimetype@^2.1.0, whatwg-mimetype@^2.2.0: +whatwg-mimetype@^2.3.0: version "2.3.0" resolved "https://registry.yarnpkg.com/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz#3d4b1e0312d2079879f826aff18dbeeca5960fbf" integrity sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g== -whatwg-url@^6.4.1: - version "6.5.0" - resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-6.5.0.tgz#f2df02bff176fd65070df74ad5ccbb5a199965a8" - integrity sha512-rhRZRqx/TLJQWUpQ6bmrt2UV4f0HCQ463yQuONJqC6fO2VoEb1pTYddbe59SkYq87aoM5A3bdhMZiUiVws+fzQ== - dependencies: - lodash.sortby "^4.7.0" - tr46 "^1.0.1" - webidl-conversions "^4.0.2" - -whatwg-url@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-7.0.0.tgz#fde926fa54a599f3adf82dff25a9f7be02dc6edd" - integrity sha512-37GeVSIJ3kn1JgKyjiYNmSLP1yzbpb29jdmwBSgkD9h40/hyrR/OifpVUndji3tmwGgD8qpw7iQu3RSbCrBpsQ== +whatwg-url@^8.0.0: + version "8.2.2" + resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-8.2.2.tgz#85e7f9795108b53d554cec640b2e8aee2a0d4bfd" + integrity sha512-PcVnO6NiewhkmzV0qn7A+UZ9Xx4maNTI+O+TShmfE4pqjoCMwUMjkvoNhNHPTvgR7QH9Xt3R13iHuWy2sToFxQ== dependencies: lodash.sortby "^4.7.0" - tr46 "^1.0.1" - webidl-conversions "^4.0.2" + tr46 "^2.0.2" + webidl-conversions "^6.1.0" which-module@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/which-module/-/which-module-2.0.0.tgz#d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a" integrity sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho= -which@^1.2.9, which@^1.3.0: +which@^1.2.9: version "1.3.1" resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== dependencies: isexe "^2.0.0" -wide-align@^1.1.0: - version "1.1.3" - resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.3.tgz#ae074e6bdc0c14a431e804e624549c633b000457" - integrity sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA== - dependencies: - string-width "^1.0.2 || 2" - -windows-release@^3.1.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/windows-release/-/windows-release-3.2.0.tgz#8122dad5afc303d833422380680a79cdfa91785f" - integrity sha512-QTlz2hKLrdqukrsapKsINzqMgOUpQW268eJ0OaOpJN32h272waxR9fkB9VoWRtK7uKHG5EHJcTXQBD8XZVJkFA== +which@^2.0.1, which@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" + integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== dependencies: - execa "^1.0.0" - -wordwrap@~0.0.2: - version "0.0.3" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107" - integrity sha1-o9XabNXAvAAI03I0u68b7WMFkQc= - -wordwrap@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" - integrity sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus= + isexe "^2.0.0" -wrap-ansi@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85" - integrity sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU= - dependencies: - string-width "^1.0.1" - strip-ansi "^3.0.1" +word-wrap@~1.2.3: + version "1.2.3" + resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c" + integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== wrap-ansi@^5.1.0: version "5.1.0" @@ -4491,106 +4956,110 @@ wrap-ansi@^5.1.0: string-width "^3.0.0" strip-ansi "^5.0.0" +wrap-ansi@^6.2.0: + version "6.2.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz#e9393ba07102e6c91a3b221478f0257cd2856e53" + integrity sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + wrappy@1: version "1.0.2" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= -write-file-atomic@2.4.1: - version "2.4.1" - resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-2.4.1.tgz#d0b05463c188ae804396fd5ab2a370062af87529" - integrity sha512-TGHFeZEZMnv+gBFRfjAcxL5bPHrsGKtnb4qsFAws7/vlh+QfwAaySIw4AXP9ZskTTh5GWu3FLuJhsWVdiJPGvg== +write-file-atomic@^3.0.0: + version "3.0.3" + resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-3.0.3.tgz#56bd5c5a5c70481cd19c571bd39ab965a5de56e8" + integrity sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q== dependencies: - graceful-fs "^4.1.11" imurmurhash "^0.1.4" + is-typedarray "^1.0.0" signal-exit "^3.0.2" + typedarray-to-buffer "^3.1.5" -ws@^5.2.0: - version "5.2.2" - resolved "https://registry.yarnpkg.com/ws/-/ws-5.2.2.tgz#dffef14866b8e8dc9133582514d1befaf96e980f" - integrity sha512-jaHFD6PFv6UgoIVda6qZllptQsMlDEJkTQcybzzXDYM1XO9Y8em691FGMPmM46WGyLU4z9KMgQN+qrux/nhlHA== - dependencies: - async-limiter "~1.0.0" +ws@^7.2.3: + version "7.3.1" + resolved "https://registry.yarnpkg.com/ws/-/ws-7.3.1.tgz#d0547bf67f7ce4f12a72dfe31262c68d7dc551c8" + integrity sha512-D3RuNkynyHmEJIpD2qrgVkc9DQ23OrN/moAwZX4L8DfvszsJxpjQuUq3LMx6HoYji9fbIOBY18XWBsAux1ZZUA== xml-name-validator@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-3.0.0.tgz#6ae73e06de4d8c6e47f9fb181f78d648ad457c6a" integrity sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw== +xmlchars@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/xmlchars/-/xmlchars-2.2.0.tgz#060fe1bcb7f9c76fe2a17db86a9bc3ab894210cb" + integrity sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw== + +"xtend@>=4.0.0 <4.1.0-0": + version "4.0.2" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" + integrity sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ== + xtend@~3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/xtend/-/xtend-3.0.0.tgz#5cce7407baf642cba7becda568111c493f59665a" integrity sha1-XM50B7r2Qsunvs2laBEcST9ZZlo= -"y18n@^3.2.1 || ^4.0.0", y18n@^4.0.0: +y18n@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.0.tgz#95ef94f85ecc81d007c264e190a120f0a3c8566b" integrity sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w== -yallist@^3.0.0, yallist@^3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-3.0.3.tgz#b4b049e314be545e3ce802236d6cd22cd91c3de9" - integrity sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A== - -yargs-parser@10.x: - version "10.1.0" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-10.1.0.tgz#7202265b89f7e9e9f2e5765e0fe735a905edbaa8" - integrity sha512-VCIyR1wJoEBZUqk5PA+oOBF6ypbwh5aNB3I50guxAL/quggdfs4TtNHQrSazFA3fYZ+tEqfs0zIGlv0c/rgjbQ== - dependencies: - camelcase "^4.1.0" - -yargs-parser@^11.1.1: - version "11.1.1" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-11.1.1.tgz#879a0865973bca9f6bab5cbdf3b1c67ec7d3bcf4" - integrity sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ== +yargs-parser@18.x, yargs-parser@^18.1.2: + version "18.1.3" + resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-18.1.3.tgz#be68c4975c6b2abf469236b0c870362fab09a7b0" + integrity sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ== dependencies: camelcase "^5.0.0" decamelize "^1.2.0" -yargs-parser@^13.1.0: - version "13.1.1" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-13.1.1.tgz#d26058532aa06d365fe091f6a1fc06b2f7e5eca0" - integrity sha512-oVAVsHz6uFrg3XQheFII8ESO2ssAf9luWuAd6Wexsu4F3OtIW0o8IribPXYrD4WC24LWtPrJlGy87y5udK+dxQ== +yargs-parser@^13.1.2: + version "13.1.2" + resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-13.1.2.tgz#130f09702ebaeef2650d54ce6e3e5706f7a4fb38" + integrity sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg== dependencies: camelcase "^5.0.0" decamelize "^1.2.0" -yargs@^12.0.2: - version "12.0.5" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-12.0.5.tgz#05f5997b609647b64f66b81e3b4b10a368e7ad13" - integrity sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw== +yargs@^13.2.4: + version "13.3.2" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-13.3.2.tgz#ad7ffefec1aa59565ac915f82dccb38a9c31a2dd" + integrity sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw== dependencies: - cliui "^4.0.0" - decamelize "^1.2.0" + cliui "^5.0.0" find-up "^3.0.0" - get-caller-file "^1.0.1" - os-locale "^3.0.0" + get-caller-file "^2.0.1" require-directory "^2.1.1" - require-main-filename "^1.0.1" + require-main-filename "^2.0.0" set-blocking "^2.0.0" - string-width "^2.0.0" + string-width "^3.0.0" which-module "^2.0.0" - y18n "^3.2.1 || ^4.0.0" - yargs-parser "^11.1.1" + y18n "^4.0.0" + yargs-parser "^13.1.2" -yargs@^13.2.4: - version "13.2.4" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-13.2.4.tgz#0b562b794016eb9651b98bd37acf364aa5d6dc83" - integrity sha512-HG/DWAJa1PAnHT9JAhNa8AbAv3FPaiLzioSjCcmuXXhP8MlpHO5vwls4g4j6n30Z74GVQj8Xa62dWVx1QCGklg== +yargs@^15.3.1: + version "15.4.1" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-15.4.1.tgz#0d87a16de01aee9d8bec2bfbf74f67851730f4f8" + integrity sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A== dependencies: - cliui "^5.0.0" - find-up "^3.0.0" + cliui "^6.0.0" + decamelize "^1.2.0" + find-up "^4.1.0" get-caller-file "^2.0.1" - os-locale "^3.1.0" require-directory "^2.1.1" require-main-filename "^2.0.0" set-blocking "^2.0.0" - string-width "^3.0.0" + string-width "^4.2.0" which-module "^2.0.0" y18n "^4.0.0" - yargs-parser "^13.1.0" + yargs-parser "^18.1.2" -yn@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/yn/-/yn-3.1.0.tgz#fcbe2db63610361afcc5eb9e0ac91e976d046114" - integrity sha512-kKfnnYkbTfrAdd0xICNFw7Atm8nKpLcLv9AZGEt+kczL/WQVai4e2V6ZN8U/O+iI6WrNuJjNNOyu4zfhl9D3Hg== +yn@3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/yn/-/yn-3.1.1.tgz#1e87401a09d767c1d5eab26a6e4c185182d2eb50" + integrity sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==